zhaolei
2020-11-20 4a2e5b9a21940f11757be37d99f0944e240e908b
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
using Prow.OAuth;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.OAuth;
using Microsoft.AspNetCore.WebUtilities;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using System.Security.Claims;
using System.Net.Http;
using System.Net.Http.Headers;
#if !NETSTANDARD2_0
using System.Text.Json;
#else
using Newtonsoft.Json.Linq;
#endif
 
namespace Prow.AlipayAuth
{
    internal class AlipayHandler : LgbOAuthHandler<AlipayOptions>
    {
        /// <summary>
        /// 默认构造函数
        /// </summary>
        /// <param name="options"></param>
        /// <param name="logger"></param>
        /// <param name="encoder"></param>
        /// <param name="clock"></param>
        public AlipayHandler(IOptionsMonitor<AlipayOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock) : base(options, logger, encoder, clock)
        {
 
        }
 
        /// <summary>
        /// 生成认证地址方法
        /// </summary>
        /// <param name="properties"></param>
        /// <param name="redirectUri"></param>
        /// <returns></returns>
        protected override string BuildChallengeUrl(AuthenticationProperties properties, string redirectUri)
        {
            var scopeParameter = properties.GetParameter<ICollection<string>>(OAuthChallengeProperties.ScopeKey);
            var scope = scopeParameter != null ? FormatScope(scopeParameter) : FormatScope();
            var parameters = new Dictionary<string, string>()
            {
                { "app_id", Options.ClientId },
                { "scope", scope },
                { "redirect_uri", redirectUri }
            };
            return QueryHelpers.AddQueryString(Options.AuthorizationEndpoint, parameters);
        }
 
        /// <summary>
        /// HandleRemoteAuthenticateAsync 方法
        /// </summary>
        /// <returns></returns>
        protected override async Task<HandleRequestResult> HandleRemoteAuthenticateAsync()
        {
            // Alipay 未使用标准的 code 参数,导致必须重载此方法更改为 Alipay 使用的 app_auth_code
            var query = Request.Query;
            var properties = new AuthenticationProperties();
            var code = query["auth_code"];
 
#if !NETSTANDARD2_0
            var codeExchangeContext = new OAuthCodeExchangeContext(properties, code, BuildRedirectUri(Options.CallbackPath));
            using var tokens = await ExchangeCodeAsync(codeExchangeContext);
#else
            var tokens = await ExchangeCodeAsync(code, Options.CallbackPath);
#endif
 
            if (tokens.Error != null)
            {
                return HandleRequestResult.Fail(tokens.Error, properties);
            }
 
#if !NETSTANDARD2_0
            if (string.IsNullOrEmpty(tokens.AccessToken))
#else
            if (string.IsNullOrEmpty(tokens.Response.Value<string>("app_auth_token")))
#endif
            {
                return HandleRequestResult.Fail("Failed to retrieve access token.", properties);
            }
 
            var identity = new ClaimsIdentity(ClaimsIssuer);
 
            var ticket = await CreateTicketAsync(identity, properties, tokens);
            if (ticket != null)
            {
                return HandleRequestResult.Success(ticket);
            }
            else
            {
                return HandleRequestResult.Fail("Failed to retrieve user information from remote server.", properties);
            }
        }
 
#if !NETSTANDARD2_0
        /// <summary>
        /// 通过 code 获取 access_token 方法
        /// </summary>
        /// <param name="context"></param>
        /// <remarks>标准的都是 post 方法 微信使用 get</remarks>
        protected override async Task<OAuthTokenResponse> ExchangeCodeAsync(OAuthCodeExchangeContext context)
#else
        /// <summary>
        /// 通过 code 获取 access_token 方法
        /// </summary>
        /// <param name="code"></param>
        /// <param name="redirectUri"></param>
        /// <remarks>标准的都是 post 方法 微信使用 get</remarks>
        protected override async Task<OAuthTokenResponse> ExchangeCodeAsync(string code, string redirectUri)
#endif
        {
            var parameters = new Dictionary<string, string>
            {
                { "app_id", Options.ClientId },
                { "method", "alipay.system.oauth.token" },
                { "charset", "utf-8" },
                { "sign_type", "RSA2" },
                { "timestamp", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") },
                { "version", "1.0"},
                { "grant_type", "authorization_code" },
#if !NETSTANDARD2_0
                { "code", context.Code }
#else
                { "code", code }
#endif
            };
            parameters["sign"] = AlipaySignature.Sign(parameters, Options.SignKey);
 
            var endpoint = QueryHelpers.AddQueryString(Options.TokenEndpoint, parameters);
            var response = await Backchannel.GetAsync(endpoint, Context.RequestAborted);
            if (response.IsSuccessStatusCode)
            {
                var respon = await response.Content.ReadAsStringAsync();
#if !NETSTANDARD2_0
                var jsonDoc = JsonDocument.Parse(respon);
                var payload = JsonDocument.Parse(jsonDoc.RootElement.GetProperty("alipay_system_oauth_token_response").GetRawText());
#else
                var jsonDoc = JObject.Parse(respon);
                var payload = JObject.Parse(jsonDoc["alipay_open_auth_token_app_response"].Value<string>());
#endif
                return OAuthTokenResponse.Success(payload);
            }
            else
            {
                var error = "OAuth token endpoint failure: " + await Display(response);
                return OAuthTokenResponse.Failed(new Exception(error));
            }
        }
 
#if !NETSTANDARD2_0
        private static void ValidatePayload(JsonElement payload)
        {
            var code = payload.GetString("code");
            if (string.IsNullOrEmpty(code) || code != "10000") throw new Exception($"payload: {payload.ToString()}");
        }
#else
        private static void ValidatePayload(JObject payload)
        {
            var code = payload.Value<string>("code");
            if (code != "" && code != "10000") throw new Exception($"payload: {payload.ToString()}");
        }
#endif
 
        /// <summary>
        /// 生成用户信息请求地址方法
        /// </summary>
        /// <param name="tokens"></param>
        /// <returns></returns>
        protected override string BuildUserInfoUrl(OAuthTokenResponse tokens)
        {
            var parameters = new Dictionary<string, string>
            {
                { "app_id", Options.ClientId },
                { "method", "alipay.user.info.share" },
                { "charset", "utf-8" },
                { "sign_type", "RSA2" },
                { "timestamp", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") },
                { "version", "1.0" },
                { "auth_token", tokens.AccessToken }
            };
            parameters["sign"] = AlipaySignature.Sign(parameters, Options.SignKey);
            return QueryHelpers.AddQueryString(Options.UserInformationEndpoint, parameters);
        }
 
        /// <summary>
        /// 处理用户信息方法
        /// </summary>
        /// <param name="tokens"></param>
        /// <returns></returns>
#if !NETSTANDARD2_0
        protected override async Task<JsonElement> HandleUserInfoAsync(OAuthTokenResponse tokens)
#else
        protected override async Task<JObject> HandleUserInfoAsync(OAuthTokenResponse tokens)
#endif
        {
            var url = BuildUserInfoUrl(tokens);
            var requestMessage = new HttpRequestMessage(HttpMethod.Get, url);
            requestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            var response = await Backchannel.SendAsync(requestMessage, Context.RequestAborted);
            if (response.IsSuccessStatusCode)
            {
#if !NETSTANDARD2_0
                var jsonDoc = JsonDocument.Parse(await response.Content.ReadAsStringAsync()).RootElement;
                var user = JsonDocument.Parse(jsonDoc.GetProperty("alipay_user_info_share_response").GetRawText()).RootElement;
#else
                var jobDoc = JObject.Parse(await response.Content.ReadAsStringAsync());
                var user = JObject.Parse(jobDoc["alipay_user_info_share_response"].Value<string>());
#endif
                ValidatePayload(user);
                return user;
            }
            else
            {
                var error = "OAuth user information endpoint failure: " + await Display(response);
                throw new Exception(error);
            }
        }
 
        /// <summary>
        /// Format a list of OAuth scopes.
        /// </summary>
        /// <param name="scopes">List of scopes.</param>
        /// <returns>Formatted scopes.</returns>
        protected override string FormatScope(IEnumerable<string> scopes) => string.Join(",", scopes); // 腾讯 scope 使用逗号分隔
    }
}