|
| 1 | +using System; |
| 2 | +using System.Collections.Generic; |
| 3 | +using System.Net; |
| 4 | +using System.Net.Http; |
| 5 | +using System.Net.Http.Headers; |
| 6 | +using System.Runtime.Serialization.Json; |
| 7 | +using System.Text; |
| 8 | +using System.Threading; |
| 9 | +using System.Threading.Tasks; |
| 10 | + |
| 11 | +namespace Kaive.HttpClient.OAuth2Handler.Authorizer |
| 12 | +{ |
| 13 | + public class Authorizer : IAuthorizer |
| 14 | + { |
| 15 | + private readonly AuthorizerOptions _options; |
| 16 | + private readonly Func<System.Net.Http.HttpClient> _httpClientFactory; |
| 17 | + |
| 18 | + // ReSharper disable once UnusedMember.Global |
| 19 | + public Authorizer(AuthorizerOptions options) |
| 20 | + : this(options, () => new System.Net.Http.HttpClient()) |
| 21 | + { |
| 22 | + } |
| 23 | + |
| 24 | + public Authorizer(AuthorizerOptions options, Func<System.Net.Http.HttpClient> httpClientFactory) |
| 25 | + { |
| 26 | + _options = options ?? throw new ArgumentNullException(nameof(options)); |
| 27 | + _httpClientFactory = httpClientFactory ?? throw new ArgumentNullException(nameof(httpClientFactory)); |
| 28 | + } |
| 29 | + |
| 30 | + public async Task<TokenResponse> GetTokenAsync(CancellationToken? cancellationToken = null) |
| 31 | + { |
| 32 | + cancellationToken = cancellationToken ?? new CancellationToken(false); |
| 33 | + switch (_options.GrantType) |
| 34 | + { |
| 35 | + case GrantType.ClientCredentials: |
| 36 | + return await GetTokenWithClientCredentials(cancellationToken.Value); |
| 37 | + case GrantType.ResourceOwnerPasswordCredentials: |
| 38 | + return await GetTokenWithResourceOwnerPasswordCredentials(cancellationToken.Value); |
| 39 | + default: |
| 40 | + throw new NotSupportedException($"Requested grant type '{_options.GrantType}' is not supported."); |
| 41 | + } |
| 42 | + } |
| 43 | + |
| 44 | + private Task<TokenResponse> GetTokenWithClientCredentials(CancellationToken cancellationToken) |
| 45 | + { |
| 46 | + if (_options.TokenEndpointUri == null) throw new ArgumentException("TokenEndpointUrl option cannot be null."); |
| 47 | + if (!_options.TokenEndpointUri.IsAbsoluteUri) throw new ArgumentException("TokenEndpointUrl must be an absolute Url."); |
| 48 | + |
| 49 | + var properties = new Dictionary<string, string> |
| 50 | + { |
| 51 | + { "grant_type", "client_credentials" } |
| 52 | + }; |
| 53 | + |
| 54 | + return GetTokenAsync(properties, cancellationToken); |
| 55 | + } |
| 56 | + |
| 57 | + private Task<TokenResponse> GetTokenWithResourceOwnerPasswordCredentials(CancellationToken cancellationToken) |
| 58 | + { |
| 59 | + if (_options.TokenEndpointUri == null) throw new ArgumentException("TokenEndpointUrl option cannot be null."); |
| 60 | + if (!_options.TokenEndpointUri.IsAbsoluteUri) throw new ArgumentException("TokenEndpointUrl must be an absolute Url."); |
| 61 | + |
| 62 | + if (_options.Username == null) throw new ArgumentException("Username cannot be null."); |
| 63 | + if (_options.Password == null) throw new ArgumentException("Password cannot be null."); |
| 64 | + |
| 65 | + var properties = new Dictionary<string, string> |
| 66 | + { |
| 67 | + { "grant_type", "password" }, |
| 68 | + { "username", _options.Username }, |
| 69 | + { "password", _options.Password } |
| 70 | + }; |
| 71 | + |
| 72 | + return GetTokenAsync(properties, cancellationToken); |
| 73 | + } |
| 74 | + |
| 75 | + private async Task<TokenResponse> GetTokenAsync(IDictionary<string, string> properties, CancellationToken cancellationToken) |
| 76 | + { |
| 77 | + using (var client = _httpClientFactory()) |
| 78 | + { |
| 79 | + if (_options.CredentialsTransportMethod == CredentialsTransportMethod.BasicAuthenticationCredentials) |
| 80 | + client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", GetBasicAuthorizationHeaderValue()); |
| 81 | + else if (_options.CredentialsTransportMethod == CredentialsTransportMethod.FormAuthenticationCredentials) |
| 82 | + { |
| 83 | + properties.Add("client_id", _options.ClientId); |
| 84 | + properties.Add("client_secret", _options.ClientSecret); |
| 85 | + } |
| 86 | + |
| 87 | + client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); |
| 88 | + |
| 89 | + if (_options.Scope != null) |
| 90 | + properties.Add("scope", string.Join(" ", _options.Scope)); |
| 91 | + |
| 92 | + if (_options.Resource != null) |
| 93 | + properties.Add("resource", _options.Resource); |
| 94 | + |
| 95 | + var tokenUri = _options.TokenEndpointUri; |
| 96 | + if (_options.SetGrantTypeOnQueryString) |
| 97 | + tokenUri = new UriBuilder(tokenUri) {Query = "grant_type=" + properties["grant_type"]}.Uri; |
| 98 | + |
| 99 | + var response = await client.PostAsync(tokenUri, new FormUrlEncodedContent(properties), cancellationToken); |
| 100 | + if (cancellationToken.IsCancellationRequested) |
| 101 | + return null; |
| 102 | + |
| 103 | + if (!response.IsSuccessStatusCode) |
| 104 | + { |
| 105 | + RaiseProtocolException(response.StatusCode, await response.Content.ReadAsStringAsync()); |
| 106 | + return null; |
| 107 | + } |
| 108 | + |
| 109 | + var serializer = new DataContractJsonSerializer(typeof(TokenResponse)); |
| 110 | + return serializer.ReadObject(await response.Content.ReadAsStreamAsync()) as TokenResponse; |
| 111 | + } |
| 112 | + } |
| 113 | + |
| 114 | + private string GetBasicAuthorizationHeaderValue() |
| 115 | + { |
| 116 | + if (_options.ClientId == null) throw new ArgumentException("ClientId cannot be null."); |
| 117 | + if (_options.ClientSecret == null) throw new ArgumentException("ClientSecret cannot be null."); |
| 118 | + return Convert.ToBase64String(Encoding.UTF8.GetBytes($"{_options.ClientId}:{_options.ClientSecret}")); |
| 119 | + } |
| 120 | + |
| 121 | + private void RaiseProtocolException(HttpStatusCode statusCode, string message) |
| 122 | + { |
| 123 | + if (_options.OnError != null) |
| 124 | + _options.OnError(statusCode, message); |
| 125 | + else |
| 126 | + throw new OAuthException(statusCode, message); |
| 127 | + } |
| 128 | + } |
| 129 | +} |
0 commit comments