zhaolei
2020-11-20 921de2254ff5712a44ed8575ee8efe34252f6603
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
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;
#if NETSTANDARD2_0
using Newtonsoft.Json.Linq;
#else
using System.Text.Json;
#endif
namespace Prow.WeChatAuth
{
    internal class WeChatHandler : LgbOAuthHandler<WeChatOptions>
    {
        /// <summary>
        /// 默认构造函数
        /// </summary>
        /// <param name="options"></param>
        /// <param name="logger"></param>
        /// <param name="encoder"></param>
        /// <param name="clock"></param>
        public WeChatHandler(IOptionsMonitor<WeChatOptions> 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>()
            {
                { "appid", Options.ClientId },
                { "redirect_uri", redirectUri },
                { "scope", scope },
                { "response_type", "code" }
            };
            parameters["state"] = Options.StateDataFormat.Protect(properties);
            return QueryHelpers.AddQueryString(Options.AuthorizationEndpoint, parameters);
        }
 
#if NETSTANDARD2_0
        /// <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)
        {
            var parameters = new Dictionary<string, string>
            {
                {  "appid", Options.ClientId },
                {  "secret", Options.ClientSecret },
                {  "code", code},
                {  "grant_type", "authorization_code" }
            };
 
            var endpoint = QueryHelpers.AddQueryString(Options.TokenEndpoint, parameters);
            var response = await Backchannel.GetAsync(endpoint, Context.RequestAborted);
            if (response.IsSuccessStatusCode)
            {
                var payload = JObject.Parse(await response.Content.ReadAsStringAsync());
                return OAuthTokenResponse.Success(payload);
            }
            else
            {
                var error = "OAuth token endpoint failure: " + await Display(response);
                return OAuthTokenResponse.Failed(new Exception(error));
            }
        }
#else
        /// <summary>
        /// 通过 code 获取 access_token 方法
        /// </summary>
        /// <param name="context"></param>
        /// <remarks>标准的都是 post 方法 微信使用 get</remarks>
        protected override async Task<OAuthTokenResponse> ExchangeCodeAsync(OAuthCodeExchangeContext context)
        {
            var parameters = new Dictionary<string, string>
            {
                {  "appid", Options.ClientId },
                {  "secret", Options.ClientSecret },
                {  "code", context.Code},
                {  "grant_type", "authorization_code" }
            };
 
            var endpoint = QueryHelpers.AddQueryString(Options.TokenEndpoint, parameters);
            var response = await Backchannel.GetAsync(endpoint, Context.RequestAborted);
            if (response.IsSuccessStatusCode)
            {
                var payload = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
                return OAuthTokenResponse.Success(payload);
            }
            else
            {
                var error = "OAuth token endpoint failure: " + await Display(response);
                return OAuthTokenResponse.Failed(new Exception(error));
            }
        }
#endif
 
        /// <summary>
        /// 生成用户信息请求地址方法
        /// </summary>
        /// <param name="tokens"></param>
        /// <returns></returns>
        protected override string BuildUserInfoUrl(OAuthTokenResponse tokens)
        {
            var tokenRequestParameters = new Dictionary<string, string>()
            {
                { "access_token", tokens.AccessToken },
#if NETSTANDARD2_0
                { "openid", tokens.Response.Value<string>("openid") }
#else
                { "openid", tokens.Response.RootElement.GetString("openid")}
#endif
            };
            return QueryHelpers.AddQueryString(Options.UserInformationEndpoint, tokenRequestParameters);
        }
 
        /// <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 使用逗号分隔
    }
}