-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathWebAuthenticator.cs
75 lines (64 loc) · 2.28 KB
/
WebAuthenticator.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
using System;
using System.Threading.Tasks;
using System.Diagnostics;
using Microsoft.AspNetCore.Http;
using StravaSharp.OAuth2Client;
using RestSharp.Authenticators;
using RestSharp;
using System.Linq;
using Microsoft.AspNetCore.WebUtilities;
namespace Sample.Web
{
/// <summary>
/// Web authenticator
/// </summary>
public class WebAuthenticator : IAuthenticator
{
private readonly StravaClient _client;
private readonly IHttpContextAccessor _httpContextAccessor;
/// <summary>
/// The access token that was received from the server.
/// </summary>
public string AccessToken {
get {
return _httpContextAccessor.HttpContext.Session.GetString("AccessToken");
}
set {
_httpContextAccessor.HttpContext.Session.SetString("AccessToken", value);
}
}
public bool IsAuthenticated => AccessToken != null;
public WebAuthenticator(StravaClient client, IHttpContextAccessor httpContextAccessor)
{
_client = client;
_httpContextAccessor = httpContextAccessor ?? throw new ArgumentNullException(nameof(httpContextAccessor));
}
public Uri GetLoginLinkUri()
{
var uri = _client.GetAuthorizationUrl();
return new Uri(uri);
}
public async Task<bool> OnPageLoaded(Uri uri)
{
if (uri.AbsoluteUri.StartsWith(_client.Configuration.RedirectUri))
{
Debug.WriteLine("Navigated to redirect url.");
var parameters = QueryHelpers.ParseQuery(uri.Query)
.ToDictionary(x => x.Key, x => string.Concat(x.Value));
await _client.Authorize(parameters);
if (!string.IsNullOrEmpty(_client.AccessToken))
{
AccessToken = _client.AccessToken;
return true;
}
}
return false;
}
public ValueTask Authenticate(IRestClient client, RestRequest request)
{
if (!string.IsNullOrEmpty(AccessToken))
request.AddHeader("Authorization", "Bearer " + AccessToken);
return ValueTask.CompletedTask;
}
}
}