|
| 1 | +/* |
| 2 | + * Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0) |
| 3 | + * See https://github.com/aspnet-contrib/AspNet.Security.OAuth.Providers |
| 4 | + * for more information concerning the license and the contributors participating to this project. |
| 5 | + */ |
| 6 | + |
| 7 | +using System.Net; |
| 8 | +using System.Net.Http.Headers; |
| 9 | +using System.Net.Mime; |
| 10 | +using System.Security.Claims; |
| 11 | +using System.Text; |
| 12 | +using System.Text.Encodings.Web; |
| 13 | +using System.Text.Json; |
| 14 | +using Microsoft.Extensions.Logging; |
| 15 | +using Microsoft.Extensions.Options; |
| 16 | + |
| 17 | +namespace AspNet.Security.OAuth.Airtable; |
| 18 | + |
| 19 | +public partial class AirtableAuthenticationHandler : OAuthHandler<AirtableAuthenticationOptions> |
| 20 | +{ |
| 21 | + public AirtableAuthenticationHandler( |
| 22 | + [NotNull] IOptionsMonitor<AirtableAuthenticationOptions> options, |
| 23 | + [NotNull] ILoggerFactory logger, |
| 24 | + [NotNull] UrlEncoder encoder) |
| 25 | + : base(options, logger, encoder) |
| 26 | + { |
| 27 | + } |
| 28 | + |
| 29 | + protected override async Task<AuthenticationTicket> CreateTicketAsync( |
| 30 | + [NotNull] ClaimsIdentity identity, |
| 31 | + [NotNull] AuthenticationProperties properties, |
| 32 | + [NotNull] OAuthTokenResponse tokens) |
| 33 | + { |
| 34 | + using var request = new HttpRequestMessage(HttpMethod.Get, Options.UserInformationEndpoint); |
| 35 | + request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); |
| 36 | + request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", tokens.AccessToken); |
| 37 | + |
| 38 | + using var response = await Backchannel.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, Context.RequestAborted); |
| 39 | + if (!response.IsSuccessStatusCode) |
| 40 | + { |
| 41 | + await Log.UserProfileErrorAsync(Logger, response, Context.RequestAborted); |
| 42 | + throw new HttpRequestException("An error occurred while retrieving the user profile."); |
| 43 | + } |
| 44 | + |
| 45 | + using var payload = JsonDocument.Parse(await response.Content.ReadAsStringAsync(Context.RequestAborted)); |
| 46 | + |
| 47 | + var principal = new ClaimsPrincipal(identity); |
| 48 | + var context = new OAuthCreatingTicketContext(principal, properties, Context, Scheme, Options, Backchannel, tokens, payload.RootElement); |
| 49 | + context.RunClaimActions(); |
| 50 | + |
| 51 | + await Events.CreatingTicket(context); |
| 52 | + return new AuthenticationTicket(context.Principal!, context.Properties, Scheme.Name); |
| 53 | + } |
| 54 | + |
| 55 | + protected override async Task<OAuthTokenResponse> ExchangeCodeAsync([NotNull]OAuthCodeExchangeContext context) |
| 56 | + { |
| 57 | + var tokenRequestParameters = new Dictionary<string, string> |
| 58 | + { |
| 59 | + { "client_id", Options.ClientId }, |
| 60 | + { "redirect_uri", context.RedirectUri }, |
| 61 | + { "client_secret", Options.ClientSecret }, |
| 62 | + { "code", context.Code }, |
| 63 | + { "grant_type", "authorization_code" } |
| 64 | + }; |
| 65 | + |
| 66 | + // PKCE https://tools.ietf.org/html/rfc7636#section-4.5, see BuildChallengeUrl |
| 67 | + if (context.Properties.Items.TryGetValue(OAuthConstants.CodeVerifierKey, out var codeVerifier)) |
| 68 | + { |
| 69 | + tokenRequestParameters.Add(OAuthConstants.CodeVerifierKey, codeVerifier!); |
| 70 | + context.Properties.Items.Remove(OAuthConstants.CodeVerifierKey); |
| 71 | + } |
| 72 | + |
| 73 | + using var requestMessage = new HttpRequestMessage(HttpMethod.Post, Options.TokenEndpoint); |
| 74 | + requestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(MediaTypeNames.Application.Json)); |
| 75 | + requestMessage.Content = new FormUrlEncodedContent(tokenRequestParameters); |
| 76 | + requestMessage.Headers.Authorization = CreateAuthorizationHeader(); |
| 77 | + requestMessage.Version = Backchannel.DefaultRequestVersion; |
| 78 | + |
| 79 | + var response = await Backchannel.SendAsync(requestMessage, Context.RequestAborted); |
| 80 | + var body = await response.Content.ReadAsStringAsync(Context.RequestAborted); |
| 81 | + |
| 82 | + return response.IsSuccessStatusCode switch |
| 83 | + { |
| 84 | + true => OAuthTokenResponse.Success(JsonDocument.Parse(body)), |
| 85 | + false => await ParseInvalidResponseAsync(response) |
| 86 | + }; |
| 87 | + } |
| 88 | + |
| 89 | + private AuthenticationHeaderValue CreateAuthorizationHeader() |
| 90 | + { |
| 91 | + var credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes( |
| 92 | + string.Concat( |
| 93 | + EscapeDataString(Options.ClientId), |
| 94 | + ":", |
| 95 | + EscapeDataString(Options.ClientSecret)))); |
| 96 | + |
| 97 | + return new AuthenticationHeaderValue("Basic", credentials); |
| 98 | + } |
| 99 | + |
| 100 | + private static string EscapeDataString(string value) |
| 101 | + { |
| 102 | + if (string.IsNullOrEmpty(value)) |
| 103 | + { |
| 104 | + return string.Empty; |
| 105 | + } |
| 106 | + |
| 107 | + return Uri.EscapeDataString(value).Replace("%20", "+", StringComparison.Ordinal); |
| 108 | + } |
| 109 | + |
| 110 | + private async Task<OAuthTokenResponse> ParseInvalidResponseAsync(HttpResponseMessage response) |
| 111 | + { |
| 112 | + await Log.ExchangeCodeErrorAsync(Logger, response, Context.RequestAborted); |
| 113 | + return OAuthTokenResponse.Failed(new Exception("An error occurred while retrieving an access token.")); |
| 114 | + } |
| 115 | + |
| 116 | + private static partial class Log |
| 117 | + { |
| 118 | + internal static async Task UserProfileErrorAsync(ILogger logger, HttpResponseMessage response, CancellationToken cancellationToken) |
| 119 | + { |
| 120 | + UserProfileError( |
| 121 | + logger, |
| 122 | + response.StatusCode, |
| 123 | + response.Headers.ToString(), |
| 124 | + await response.Content.ReadAsStringAsync(cancellationToken)); |
| 125 | + } |
| 126 | + |
| 127 | + internal static async Task ExchangeCodeErrorAsync(ILogger logger, HttpResponseMessage response, CancellationToken cancellationToken) |
| 128 | + { |
| 129 | + ExchangeCodeError( |
| 130 | + logger, |
| 131 | + response.StatusCode, |
| 132 | + response.Headers.ToString(), |
| 133 | + await response.Content.ReadAsStringAsync(cancellationToken)); |
| 134 | + } |
| 135 | + |
| 136 | + [LoggerMessage(1, LogLevel.Error, "An error occurred while retrieving the user profile: the remote server returned a {Status} response with the following payload: {Headers} {Body}.")] |
| 137 | + private static partial void UserProfileError( |
| 138 | + ILogger logger, |
| 139 | + System.Net.HttpStatusCode status, |
| 140 | + string headers, |
| 141 | + string body); |
| 142 | + |
| 143 | + [LoggerMessage(2, LogLevel.Error, "An error occurred while retrieving an access token: the remote server returned a {Status} response with the following payload: {Headers} {Body}.")] |
| 144 | + private static partial void ExchangeCodeError( |
| 145 | + ILogger logger, |
| 146 | + HttpStatusCode status, |
| 147 | + string headers, |
| 148 | + string body); |
| 149 | + } |
| 150 | +} |
0 commit comments