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
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.Net.Http;
using System.Net.Http.Headers;
using System.Linq;
#if !NETSTANDARD2_0
using System.Text.Json;
#else
using Newtonsoft.Json.Linq;
#endif
namespace Prow.TencentAuth
{
    internal class TencentHandler : LgbOAuthHandler<TencentOptions>
    {
        /// <summary>
        /// 默认构造函数
        /// </summary>
        /// <param name="options"></param>
        /// <param name="logger"></param>
        /// <param name="encoder"></param>
        /// <param name="clock"></param>
        public TencentHandler(IOptionsMonitor<TencentOptions> 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>()
            {
                { "client_id", Options.ClientId },
                { "redirect_uri", redirectUri },
                { "scope", scope },
                { "response_type", "code" },
                {"state", "" }
            };
            parameters["state"] = Options.StateDataFormat.Protect(properties);
            return QueryHelpers.AddQueryString(Options.AuthorizationEndpoint, parameters);
        }
 
#if !NETSTANDARD2_0
        /// <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>
            {
                { "client_id", Options.ClientId },
                { "client_secret", Options.ClientSecret },
                { "code", context.Code},
                { "redirect_uri", context.RedirectUri },
                { "grant_type", "authorization_code" }
            };
 
            var endpoint = QueryHelpers.AddQueryString(Options.TokenEndpoint, parameters);
            var response = await Backchannel.GetAsync(endpoint, Context.RequestAborted);
            if (response.IsSuccessStatusCode)
            {
                // respon: access_token=FE04CCE2&expires_in=7776000&refresh_token=88E4BE14
                var respon = await response.Content.ReadAsStringAsync();
                var segs = respon.Split('&').ToList().Select(s => s.Split('=').Last()).ToList();
                var payload = JsonDocument.Parse($"{{\"access_token\": \"{segs[0]}\", \"expires_in\": \"{segs[1]}\", \"refresh_token\": \"{segs[2]}\"}}");
                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="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>
            {
                { "client_id", Options.ClientId },
                { "client_secret", Options.ClientSecret },
                { "code", code},
                { "redirect_uri", redirectUri },
                { "grant_type", "authorization_code" }
            };
 
            var endpoint = QueryHelpers.AddQueryString(Options.TokenEndpoint, parameters);
            var response = await Backchannel.GetAsync(endpoint, Context.RequestAborted);
            if (response.IsSuccessStatusCode)
            {
                // respon: access_token=FE04CCE2&expires_in=7776000&refresh_token=88E4BE14
                var respon = await response.Content.ReadAsStringAsync();
                var segs = respon.Split('&').ToList().Select(s => s.Split('=').Last()).ToList();
                var payload = JObject.Parse($"{{\"access_token\": \"{segs[0]}\", \"expires_in\": \"{segs[1]}\", \"refresh_token\": \"{segs[2]}\"}}");
                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>
#if !NETSTANDARD2_0
        protected override async Task<JsonElement> HandleUserInfoAsync(OAuthTokenResponse tokens)
#else
        protected override async Task<JObject> HandleUserInfoAsync(OAuthTokenResponse tokens)
#endif
        {
            var openIdRespon = await ExchangeOpenIdAsync(tokens.AccessToken);
            return await base.HandleUserInfoAsync(OAuthTokenResponse.Success(openIdRespon));
        }
 
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
#if !NETSTANDARD2_0
        protected virtual async Task<JsonDocument> ExchangeOpenIdAsync(string accessToken)
#else
        protected virtual async Task<JObject> ExchangeOpenIdAsync(string accessToken)
#endif
        {
            var parameters = new Dictionary<string, string>
            {
                { "access_token", accessToken }
            };
            var endpoint = QueryHelpers.AddQueryString(Options.OpenIdEndpoint, parameters);
            var requestMessage = new HttpRequestMessage(HttpMethod.Get, endpoint);
            requestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            var response = await Backchannel.SendAsync(requestMessage, Context.RequestAborted);
            if (response.IsSuccessStatusCode)
            {
                var respon = await response.Content.ReadAsStringAsync();
                respon = respon.Replace("callback(", "").Replace(");", "").Replace("{", $"{{ \"access_token\": \"{accessToken}\",");
#if !NETSTANDARD2_0
                return JsonDocument.Parse(respon);
#else
                return JObject.Parse(respon);
#endif
            }
            else
            {
                var error = "OAuth user information endpoint failure: " + await Display(response);
                throw new Exception(error);
            }
        }
 
        /// <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
                { "oauth_consumer_key", tokens.Response.RootElement.GetString("client_id")},
                { "openid", tokens.Response.RootElement.GetString("openid")}
#else
                { "oauth_consumer_key", tokens.Response.Value<string>("client_id") },
                { "openid", tokens.Response.Value<string>("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 使用逗号分隔
    }
}