|
| 1 | +{{>partial_header}} |
| 2 | + |
| 3 | +using System; |
| 4 | +using System.Threading.Tasks; |
| 5 | +using Newtonsoft.Json; |
| 6 | +using RestSharp; |
| 7 | +using RestSharp.Authenticators; |
| 8 | + |
| 9 | +namespace {{packageName}}.{{clientPackage}}.Auth |
| 10 | +{ |
| 11 | + /// <summary> |
| 12 | + /// An authenticator for OAuth2 authentication flows |
| 13 | + /// </summary> |
| 14 | + public class OAuthAuthenticator : IAuthenticator |
| 15 | + { |
| 16 | + private TokenResponse{{nrt?}} _token; |
| 17 | + |
| 18 | + /// <summary> |
| 19 | + /// Returns the current authentication token. Can return null if there is no authentication token, or it has expired. |
| 20 | + /// </summary> |
| 21 | + public string{{nrt?}} Token |
| 22 | + { |
| 23 | + get |
| 24 | + { |
| 25 | + if (_token == null) return null; |
| 26 | + if (_token.ExpiresIn == null) return _token.AccessToken; |
| 27 | + if (_token.ExpiresAt < DateTime.Now) return null; |
| 28 | +
|
| 29 | + return _token.AccessToken; |
| 30 | + } |
| 31 | + } |
| 32 | + |
| 33 | + readonly string _tokenUrl; |
| 34 | + readonly string _clientId; |
| 35 | + readonly string _clientSecret; |
| 36 | + readonly string{{nrt?}} _scope; |
| 37 | + readonly string _grantType; |
| 38 | + readonly JsonSerializerSettings _serializerSettings; |
| 39 | + readonly IReadableConfiguration _configuration; |
| 40 | + |
| 41 | + /// <summary> |
| 42 | + /// Initialize the OAuth2 Authenticator |
| 43 | + /// </summary> |
| 44 | + public OAuthAuthenticator( |
| 45 | + string tokenUrl, |
| 46 | + string clientId, |
| 47 | + string clientSecret, |
| 48 | + string{{nrt?}} scope, |
| 49 | + OAuthFlow? flow, |
| 50 | + JsonSerializerSettings serializerSettings, |
| 51 | + IReadableConfiguration configuration) |
| 52 | + { |
| 53 | + _tokenUrl = tokenUrl; |
| 54 | + _clientId = clientId; |
| 55 | + _clientSecret = clientSecret; |
| 56 | + _scope = scope; |
| 57 | + _serializerSettings = serializerSettings; |
| 58 | + _configuration = configuration; |
| 59 | +
|
| 60 | + switch (flow) |
| 61 | + { |
| 62 | + /*case OAuthFlow.ACCESS_CODE: |
| 63 | + _grantType = "authorization_code"; |
| 64 | + break; |
| 65 | + case OAuthFlow.IMPLICIT: |
| 66 | + _grantType = "implicit"; |
| 67 | + break; |
| 68 | + case OAuthFlow.PASSWORD: |
| 69 | + _grantType = "password"; |
| 70 | + break;*/ |
| 71 | + case OAuthFlow.APPLICATION: |
| 72 | + _grantType = "client_credentials"; |
| 73 | + break; |
| 74 | + default: |
| 75 | + break; |
| 76 | + } |
| 77 | + } |
| 78 | + |
| 79 | + /// <summary> |
| 80 | + /// Creates an authentication parameter from an access token. |
| 81 | + /// </summary> |
| 82 | + /// <returns>An authentication parameter.</returns> |
| 83 | + protected async ValueTask<Parameter> GetAuthenticationParameter() |
| 84 | + { |
| 85 | + var token = string.IsNullOrEmpty(Token) ? await GetToken().ConfigureAwait(false) : Token; |
| 86 | + return new HeaderParameter(KnownHeaders.Authorization, token); |
| 87 | + } |
| 88 | + |
| 89 | + /// <summary> |
| 90 | + /// Gets the token from the OAuth2 server. |
| 91 | + /// </summary> |
| 92 | + /// <returns>An authentication token.</returns> |
| 93 | + async Task<string> GetToken() |
| 94 | + { |
| 95 | + var client = new RestClient(_tokenUrl, configureSerialization: serializerConfig => serializerConfig.UseSerializer(() => new CustomJsonCodec(_serializerSettings, _configuration))); |
| 96 | +
|
| 97 | + var request = new RestRequest(); |
| 98 | + if (!string.IsNullOrWhiteSpace(_token?.RefreshToken)) |
| 99 | + { |
| 100 | + request.AddParameter("grant_type", "refresh_token") |
| 101 | + .AddParameter("refresh_token", _token.RefreshToken); |
| 102 | + } |
| 103 | + else |
| 104 | + { |
| 105 | + request |
| 106 | + .AddParameter("grant_type", _grantType) |
| 107 | + .AddParameter("client_id", _clientId) |
| 108 | + .AddParameter("client_secret", _clientSecret); |
| 109 | + } |
| 110 | + if (!string.IsNullOrEmpty(_scope)) |
| 111 | + { |
| 112 | + request.AddParameter("scope", _scope); |
| 113 | + } |
| 114 | + _token = await client.PostAsync<TokenResponse>(request).ConfigureAwait(false); |
| 115 | + // RFC6749 - token_type is case insensitive. |
| 116 | + // RFC6750 - In Authorization header Bearer should be capitalized. |
| 117 | + // Fix the capitalization irrespective of token_type casing. |
| 118 | + switch (_token?.TokenType?.ToLower()) |
| 119 | + { |
| 120 | + case "bearer": |
| 121 | + return $"Bearer {_token.AccessToken}"; |
| 122 | + default: |
| 123 | + return $"{_token?.TokenType} {_token?.AccessToken}"; |
| 124 | + } |
| 125 | + } |
| 126 | + |
| 127 | + /// <summary> |
| 128 | + /// Retrieves the authentication token (creating a new one if necessary) and adds it to the current request |
| 129 | + /// </summary> |
| 130 | + /// <param name="client"></param> |
| 131 | + /// <param name="request"></param> |
| 132 | + /// <returns></returns> |
| 133 | + public async ValueTask Authenticate(IRestClient client, RestRequest request) |
| 134 | + => request.AddOrUpdateParameter(await GetAuthenticationParameter().ConfigureAwait(false)); |
| 135 | + } |
| 136 | +} |
0 commit comments