|
| 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.Encodings.Web; |
| 12 | +using System.Text.Json; |
| 13 | +using Microsoft.Extensions.Logging; |
| 14 | +using Microsoft.Extensions.Options; |
| 15 | + |
| 16 | +namespace AspNet.Security.OAuth.Zoho; |
| 17 | + |
| 18 | +public partial class ZohoAuthenticationHandler : OAuthHandler<ZohoAuthenticationOptions> |
| 19 | +{ |
| 20 | + public ZohoAuthenticationHandler( |
| 21 | + [NotNull] IOptionsMonitor<ZohoAuthenticationOptions> options, |
| 22 | + [NotNull] ILoggerFactory logger, |
| 23 | + [NotNull] UrlEncoder encoder) |
| 24 | + : base(options, logger, encoder) |
| 25 | + { |
| 26 | + } |
| 27 | + |
| 28 | + protected override async Task<AuthenticationTicket> CreateTicketAsync( |
| 29 | + [NotNull] ClaimsIdentity identity, |
| 30 | + [NotNull] AuthenticationProperties properties, |
| 31 | + [NotNull] OAuthTokenResponse tokens) |
| 32 | + { |
| 33 | + var userInformationEndpoint = CreateEndpoint(ZohoAuthenticationDefaults.UserInformationPath); |
| 34 | + using var requestMessage = new HttpRequestMessage(HttpMethod.Get, userInformationEndpoint); |
| 35 | + requestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(MediaTypeNames.Application.Json)); |
| 36 | + requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", tokens.AccessToken); |
| 37 | + requestMessage.Version = Backchannel.DefaultRequestVersion; |
| 38 | + |
| 39 | + using var response = await Backchannel.SendAsync(requestMessage, HttpCompletionOption.ResponseHeadersRead, Context.RequestAborted); |
| 40 | + if (!response.IsSuccessStatusCode) |
| 41 | + { |
| 42 | + await Log.UserProfileErrorAsync(Logger, response, Context.RequestAborted); |
| 43 | + throw new HttpRequestException("An error occurred while retrieving the user profile."); |
| 44 | + } |
| 45 | + |
| 46 | + using var payload = JsonDocument.Parse(await response.Content.ReadAsStringAsync(Context.RequestAborted)); |
| 47 | + |
| 48 | + var principal = new ClaimsPrincipal(identity); |
| 49 | + var context = new OAuthCreatingTicketContext(principal, properties, Context, Scheme, Options, Backchannel, tokens, payload.RootElement); |
| 50 | + context.RunClaimActions(); |
| 51 | + |
| 52 | + await Events.CreatingTicket(context); |
| 53 | + return new AuthenticationTicket(context.Principal!, context.Properties, Scheme.Name); |
| 54 | + } |
| 55 | + |
| 56 | + protected override async Task<OAuthTokenResponse> ExchangeCodeAsync(OAuthCodeExchangeContext context) |
| 57 | + { |
| 58 | + var nameValueCollection = new Dictionary<string, string?> |
| 59 | + { |
| 60 | + ["client_id"] = Options.ClientId, |
| 61 | + ["client_secret"] = Options.ClientSecret, |
| 62 | + ["code"] = context.Code, |
| 63 | + ["redirect_uri"] = context.RedirectUri, |
| 64 | + ["grant_type"] = "authorization_code" |
| 65 | + }; |
| 66 | + |
| 67 | + if (context.Properties.Items.TryGetValue(OAuthConstants.CodeVerifierKey, out var codeVerifier)) |
| 68 | + { |
| 69 | + nameValueCollection.Add(OAuthConstants.CodeVerifierKey, codeVerifier!); |
| 70 | + context.Properties.Items.Remove(OAuthConstants.CodeVerifierKey); |
| 71 | + } |
| 72 | + |
| 73 | + var tokenEndpoint = CreateEndpoint(ZohoAuthenticationDefaults.TokenPath); |
| 74 | + using var request = new HttpRequestMessage(HttpMethod.Post, tokenEndpoint); |
| 75 | + request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(MediaTypeNames.Application.Json)); |
| 76 | + request.Content = new FormUrlEncodedContent(nameValueCollection); |
| 77 | + request.Version = Backchannel.DefaultRequestVersion; |
| 78 | + |
| 79 | + using var response = await Backchannel.SendAsync(request, Context.RequestAborted); |
| 80 | + if (!response.IsSuccessStatusCode) |
| 81 | + { |
| 82 | + await Log.ExchangeCodeErrorAsync(Logger, response, Context.RequestAborted); |
| 83 | + return OAuthTokenResponse.Failed(new Exception("An error occurred while retrieving an access token.")); |
| 84 | + } |
| 85 | + |
| 86 | + var payload = JsonDocument.Parse(await response.Content.ReadAsStringAsync(Context.RequestAborted)); |
| 87 | + |
| 88 | + return OAuthTokenResponse.Success(payload); |
| 89 | + } |
| 90 | + |
| 91 | + /// <summary> |
| 92 | + /// Creates the endpoint for the Zoho API using the location parameter. |
| 93 | + /// If the location parameter doesn't match any of the supported locations, the default location (US) is used. |
| 94 | + /// We don't use the <c>accounts-server</c> parameter for security reasons. |
| 95 | + /// </summary> |
| 96 | + /// <param name="path">The request path.</param> |
| 97 | + /// <returns>The API endpoint for the Zoho API.</returns> |
| 98 | + private string CreateEndpoint(string path) |
| 99 | + { |
| 100 | + var location = Context.Request.Query["location"]; |
| 101 | + |
| 102 | + var domain = location.ToString().ToLowerInvariant() switch |
| 103 | + { |
| 104 | + "au" => "https://accounts.zoho.com.au", |
| 105 | + "ca" => "https://accounts.zohocloud.ca", |
| 106 | + "eu" => "https://accounts.zoho.eu", |
| 107 | + "us" => "https://accounts.zoho.com", |
| 108 | + "in" => "https://accounts.zoho.in", |
| 109 | + "jp" => "https://accounts.zoho.jp", |
| 110 | + "sa" => "https://accounts.zoho.sa", |
| 111 | + "uk" => "https://accounts.zoho.uk", |
| 112 | + _ => "https://accounts.zoho.com" |
| 113 | + }; |
| 114 | + |
| 115 | + var builder = new UriBuilder(domain) |
| 116 | + { |
| 117 | + Path = path, |
| 118 | + Port = -1, |
| 119 | + Scheme = Uri.UriSchemeHttps, |
| 120 | + }; |
| 121 | + |
| 122 | + return builder.Uri.ToString(); |
| 123 | + } |
| 124 | + |
| 125 | + private static partial class Log |
| 126 | + { |
| 127 | + internal static async Task UserProfileErrorAsync(ILogger logger, HttpResponseMessage response, CancellationToken cancellationToken) |
| 128 | + { |
| 129 | + UserProfileError( |
| 130 | + logger, |
| 131 | + response.StatusCode, |
| 132 | + response.Headers.ToString(), |
| 133 | + await response.Content.ReadAsStringAsync(cancellationToken)); |
| 134 | + } |
| 135 | + |
| 136 | + internal static async Task ServerInfoErrorAsync(ILogger logger, HttpResponseMessage response, CancellationToken cancellationToken) |
| 137 | + { |
| 138 | + ServerInfoErrorAsync( |
| 139 | + logger, |
| 140 | + response.StatusCode, |
| 141 | + response.Headers.ToString(), |
| 142 | + await response.Content.ReadAsStringAsync(cancellationToken)); |
| 143 | + } |
| 144 | + |
| 145 | + internal static async Task ExchangeCodeErrorAsync(ILogger logger, HttpResponseMessage response, CancellationToken cancellationToken) |
| 146 | + { |
| 147 | + ExchangeCodeError( |
| 148 | + logger, |
| 149 | + response.StatusCode, |
| 150 | + response.Headers.ToString(), |
| 151 | + await response.Content.ReadAsStringAsync(cancellationToken)); |
| 152 | + } |
| 153 | + |
| 154 | + [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}.")] |
| 155 | + private static partial void UserProfileError( |
| 156 | + ILogger logger, |
| 157 | + System.Net.HttpStatusCode status, |
| 158 | + string headers, |
| 159 | + string body); |
| 160 | + |
| 161 | + [LoggerMessage(2, LogLevel.Error, "An error occurred while retrieving the server info: the remote server returned a {Status} response with the following payload: {Headers} {Body}.")] |
| 162 | + private static partial void ServerInfoErrorAsync( |
| 163 | + ILogger logger, |
| 164 | + HttpStatusCode status, |
| 165 | + string headers, |
| 166 | + string body); |
| 167 | + |
| 168 | + [LoggerMessage(3, LogLevel.Error, "An error occurred while retrieving an access token: the remote server returned a {Status} response with the following payload: {Headers} {Body}.")] |
| 169 | + private static partial void ExchangeCodeError( |
| 170 | + ILogger logger, |
| 171 | + HttpStatusCode status, |
| 172 | + string headers, |
| 173 | + string body); |
| 174 | + } |
| 175 | +} |
0 commit comments