|
| 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; |
| 8 | +using System.Collections.Generic; |
| 9 | +using System.Linq; |
| 10 | +using System.Net.Http; |
| 11 | +using System.Security.Claims; |
| 12 | +using System.Threading.Tasks; |
| 13 | +using AspNet.Security.OAuth.Extensions; |
| 14 | +using JetBrains.Annotations; |
| 15 | +using Microsoft.AspNetCore.Authentication; |
| 16 | +using Microsoft.AspNetCore.Authentication.OAuth; |
| 17 | +using Microsoft.AspNetCore.Http.Authentication; |
| 18 | +using Microsoft.AspNetCore.WebUtilities; |
| 19 | +using Microsoft.Extensions.Logging; |
| 20 | +using Newtonsoft.Json.Linq; |
| 21 | + |
| 22 | +namespace AspNet.Security.OAuth.QQ |
| 23 | +{ |
| 24 | + public class QQAuthenticationHandler : OAuthHandler<QQAuthenticationOptions> |
| 25 | + { |
| 26 | + public QQAuthenticationHandler([NotNull] HttpClient client) |
| 27 | + : base(client) |
| 28 | + { |
| 29 | + } |
| 30 | + |
| 31 | + protected override async Task<AuthenticationTicket> CreateTicketAsync([NotNull] ClaimsIdentity identity, |
| 32 | + [NotNull] AuthenticationProperties properties, [NotNull] OAuthTokenResponse tokens) |
| 33 | + { |
| 34 | + var identifier = await GetUserIdentifierAsync(tokens); |
| 35 | + if (string.IsNullOrEmpty(identifier)) |
| 36 | + { |
| 37 | + throw new HttpRequestException("An error occurred while retrieving the user identifier."); |
| 38 | + } |
| 39 | + |
| 40 | + var address = QueryHelpers.AddQueryString(Options.UserInformationEndpoint, new Dictionary<string, string> |
| 41 | + { |
| 42 | + ["oauth_consumer_key"] = Options.ClientId, |
| 43 | + ["access_token"] = tokens.AccessToken, |
| 44 | + ["openid"] = identifier, |
| 45 | + }); |
| 46 | + |
| 47 | + var response = await Backchannel.GetAsync(address); |
| 48 | + if (!response.IsSuccessStatusCode) |
| 49 | + { |
| 50 | + Logger.LogError("An error occurred while retrieving the user profile: the remote server " + |
| 51 | + "returned a {Status} response with the following payload: {Headers} {Body}.", |
| 52 | + /* Status: */ response.StatusCode, |
| 53 | + /* Headers: */ response.Headers.ToString(), |
| 54 | + /* Body: */ await response.Content.ReadAsStringAsync()); |
| 55 | + |
| 56 | + throw new HttpRequestException("An error occurred while retrieving user information."); |
| 57 | + } |
| 58 | + |
| 59 | + var payload = JObject.Parse(await response.Content.ReadAsStringAsync()); |
| 60 | + |
| 61 | + var status = payload.Value<int>("ret"); |
| 62 | + if (status != 0) |
| 63 | + { |
| 64 | + Logger.LogError("An error occurred while retrieving the user profile: the remote server " + |
| 65 | + "returned a {Status} response with the following message: {Message}.", |
| 66 | + /* Status: */ status, |
| 67 | + /* Message: */ payload.Value<string>("msg")); |
| 68 | + |
| 69 | + throw new HttpRequestException("An error occurred while retrieving user information."); |
| 70 | + } |
| 71 | + |
| 72 | + identity.AddOptionalClaim("urn:qq:picture", QQAuthenticationHelper.GetPicture(payload), Options.ClaimsIssuer) |
| 73 | + .AddOptionalClaim("urn:qq:picture_medium", QQAuthenticationHelper.GetPictureMedium(payload), Options.ClaimsIssuer) |
| 74 | + .AddOptionalClaim("urn:qq:picture_full", QQAuthenticationHelper.GetPictureFull(payload), Options.ClaimsIssuer) |
| 75 | + .AddOptionalClaim("urn:qq:avatar", QQAuthenticationHelper.GetAvatar(payload), Options.ClaimsIssuer) |
| 76 | + .AddOptionalClaim("urn:qq:avatar_full", QQAuthenticationHelper.GetAvatarFull(payload), Options.ClaimsIssuer); |
| 77 | + |
| 78 | + var principal = new ClaimsPrincipal(identity); |
| 79 | + var ticket = new AuthenticationTicket(principal, properties, Options.AuthenticationScheme); |
| 80 | + |
| 81 | + var context = new OAuthCreatingTicketContext(ticket, Context, Options, Backchannel, tokens, payload); |
| 82 | + await Options.Events.CreatingTicket(context); |
| 83 | + |
| 84 | + return context.Ticket; |
| 85 | + } |
| 86 | + |
| 87 | + protected override async Task<OAuthTokenResponse> ExchangeCodeAsync([NotNull] string code, [NotNull] string redirectUri) |
| 88 | + { |
| 89 | + var address = QueryHelpers.AddQueryString(Options.TokenEndpoint, new Dictionary<string, string>() |
| 90 | + { |
| 91 | + ["client_id"] = Options.ClientId, |
| 92 | + ["client_secret"] = Options.ClientSecret, |
| 93 | + ["redirect_uri"] = redirectUri, |
| 94 | + ["code"] = code, |
| 95 | + ["grant_type"] = "authorization_code", |
| 96 | + }); |
| 97 | + |
| 98 | + var request = new HttpRequestMessage(HttpMethod.Get, address); |
| 99 | + |
| 100 | + var response = await Backchannel.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, Context.RequestAborted); |
| 101 | + if (!response.IsSuccessStatusCode) |
| 102 | + { |
| 103 | + Logger.LogError("An error occurred while retrieving an access token: the remote server " + |
| 104 | + "returned a {Status} response with the following payload: {Headers} {Body}.", |
| 105 | + /* Status: */ response.StatusCode, |
| 106 | + /* Headers: */ response.Headers.ToString(), |
| 107 | + /* Body: */ await response.Content.ReadAsStringAsync()); |
| 108 | + |
| 109 | + return OAuthTokenResponse.Failed(new Exception("An error occurred while retrieving an access token.")); |
| 110 | + } |
| 111 | + |
| 112 | + var payload = JObject.FromObject(QueryHelpers.ParseQuery(await response.Content.ReadAsStringAsync()) |
| 113 | + .ToDictionary(pair => pair.Key, k => k.Value.ToString())); |
| 114 | + |
| 115 | + return OAuthTokenResponse.Success(payload); |
| 116 | + } |
| 117 | + |
| 118 | + private async Task<string> GetUserIdentifierAsync(OAuthTokenResponse tokens) |
| 119 | + { |
| 120 | + var address = QueryHelpers.AddQueryString(Options.UserIdentificationEndpoint, "access_token", tokens.AccessToken); |
| 121 | + var request = new HttpRequestMessage(HttpMethod.Get, address); |
| 122 | + |
| 123 | + var response = await Backchannel.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, Context.RequestAborted); |
| 124 | + if (!response.IsSuccessStatusCode) |
| 125 | + { |
| 126 | + Logger.LogError("An error occurred while retrieving the user identifier: the remote server " + |
| 127 | + "returned a {Status} response with the following payload: {Headers} {Body}.", |
| 128 | + /* Status: */ response.StatusCode, |
| 129 | + /* Headers: */ response.Headers.ToString(), |
| 130 | + /* Body: */ await response.Content.ReadAsStringAsync()); |
| 131 | + |
| 132 | + throw new HttpRequestException("An error occurred while retrieving the user identifier."); |
| 133 | + } |
| 134 | + |
| 135 | + var body = await response.Content.ReadAsStringAsync(); |
| 136 | + |
| 137 | + var index = body.IndexOf("{"); |
| 138 | + if (index > 0) |
| 139 | + { |
| 140 | + body = body.Substring(index, body.LastIndexOf("}") - index + 1); |
| 141 | + } |
| 142 | + |
| 143 | + var payload = JObject.Parse(body); |
| 144 | + |
| 145 | + return payload.Value<string>("openid"); |
| 146 | + } |
| 147 | + |
| 148 | + protected override string FormatScope() => string.Join(",", Options.Scope); |
| 149 | + } |
| 150 | +} |
0 commit comments