Skip to content

Commit b60c567

Browse files
Merge pull request #2 from myvas/alpha/3.0
3.0.100-alpha2
2 parents 7ae2330 + 3b1c441 commit b60c567

16 files changed

+296
-125
lines changed

src/WeixinAuth/Apis/IWeixinAuthApi.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
using Microsoft.AspNetCore.Authentication.OAuth;
2-
using Newtonsoft.Json.Linq;
32
using System.Net.Http;
3+
using System.Text.Json;
44
using System.Threading;
55
using System.Threading.Tasks;
66

@@ -9,6 +9,6 @@ namespace Myvas.AspNetCore.Authentication.WeixinAuth.Internal
99
internal interface IWeixinAuthApi
1010
{
1111
Task<OAuthTokenResponse> GetToken(HttpClient backchannel, string tokenEndpoint, string appId, string appSecret, string code, CancellationToken cancellationToken);
12-
Task<JObject> GetUserInfo(HttpClient backchannel, string userInformationEndpoint, string accessToken, string openid, CancellationToken cancellationToken, WeixinAuthLanguageCodes languageCode = WeixinAuthLanguageCodes.zh_CN);
12+
Task<JsonDocument> GetUserInfo(HttpClient backchannel, string userInformationEndpoint, string accessToken, string openid, CancellationToken cancellationToken, WeixinAuthLanguageCodes languageCode = WeixinAuthLanguageCodes.zh_CN);
1313
}
1414
}

src/WeixinAuth/Apis/WeixinAuthApi.cs

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,11 @@
22
using Microsoft.AspNetCore.WebUtilities;
33
using Microsoft.Extensions.Logging;
44
using Microsoft.Extensions.Options;
5-
using Newtonsoft.Json.Linq;
65
using System;
76
using System.Collections.Generic;
87
using System.Net.Http;
98
using System.Text;
9+
using System.Text.Json;
1010
using System.Threading;
1111
using System.Threading.Tasks;
1212

@@ -67,7 +67,7 @@ public async Task<OAuthTokenResponse> GetToken(HttpClient backchannel, string to
6767
// "scope":"SCOPE",
6868
// "unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL"
6969
//}
70-
var payload = JObject.Parse(content);
70+
var payload = JsonDocument.Parse(content);
7171
int errorCode = WeixinAuthHandlerHelper.GetErrorCode(payload);
7272
if (errorCode != 0)
7373
{
@@ -113,7 +113,7 @@ public async Task<OAuthTokenResponse> RefreshToken(HttpClient backchannel, strin
113113
// "openid":"OPENID",
114114
// "scope":"SCOPE"
115115
//}
116-
var payload = JObject.Parse(content);
116+
var payload = JsonDocument.Parse(content);
117117
int errorCode = WeixinAuthHandlerHelper.GetErrorCode(payload);
118118
if (errorCode != 0)
119119
{
@@ -149,10 +149,10 @@ public async Task<bool> ValidateToken(HttpClient backchannel, string validateTok
149149
}
150150

151151
var content = await response.Content.ReadAsStringAsync();
152-
var payload = JObject.Parse(content);
152+
var payload = JsonDocument.Parse(content);
153153
try
154154
{
155-
var errcode = payload.Value<int>("errcode");
155+
var errcode = payload.RootElement.GetInt32("errcode", 0);
156156
return (errcode == 0);
157157
}
158158
catch { }
@@ -164,7 +164,7 @@ public async Task<bool> ValidateToken(HttpClient backchannel, string validateTok
164164
/// </summary>
165165
/// <param name="accessToken"></param>
166166
/// <returns></returns>
167-
public async Task<JObject> GetUserInfo(HttpClient backchannel, string userInformationEndpoint, string accessToken, string openid, CancellationToken cancellationToken, WeixinAuthLanguageCodes languageCode = WeixinAuthLanguageCodes.zh_CN)
167+
public async Task<JsonDocument> GetUserInfo(HttpClient backchannel, string userInformationEndpoint, string accessToken, string openid, CancellationToken cancellationToken, WeixinAuthLanguageCodes languageCode = WeixinAuthLanguageCodes.zh_CN)
168168
{
169169
var tokenRequestParameters = new Dictionary<string, string>()
170170
{
@@ -198,7 +198,7 @@ public async Task<JObject> GetUserInfo(HttpClient backchannel, string userInform
198198
// ],
199199
// "unionid": " o6_bmasdasdsad6_2sgVt7hMZOPfL"
200200
//}
201-
var payload = JObject.Parse(content);
201+
var payload = JsonDocument.Parse(content);
202202

203203
int errorCode = WeixinAuthHandlerHelper.GetErrorCode(payload);
204204
if (errorCode != 0)

src/WeixinAuth/Extensions/ClaimsExtensions.cs

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,5 @@
11
using System;
2-
using System.Collections.Generic;
3-
using System.Linq;
42
using System.Security.Claims;
5-
using System.Threading.Tasks;
63

74
namespace Myvas.AspNetCore.Authentication.WeixinAuth.Internal
85
{
Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
using System.IO;
2+
using System.Text;
3+
using System.Text.Json;
4+
5+
namespace Myvas.AspNetCore.Authentication.WeixinAuth.Internal
6+
{
7+
internal static class JsonDocumentAuthExtensions
8+
{
9+
public static string GetString(this JsonElement element, string key)
10+
{
11+
if (element.TryGetProperty(key, out var property) && property.ValueKind != JsonValueKind.Null)
12+
{
13+
return property.ToString();
14+
}
15+
16+
return null;
17+
}
18+
19+
public static string GetString(this JsonDocument doc, string key)
20+
{
21+
return doc.RootElement.GetString(key);
22+
}
23+
24+
public static int GetInt32(this JsonElement element, string key, int defaultValue = 0)
25+
{
26+
var s = element.GetString(key);
27+
try { return int.Parse(s); } catch { return defaultValue; }
28+
}
29+
30+
public static string[] GetStringArray(this JsonElement element, string key)
31+
{
32+
var s = element.GetString(key);
33+
try { return s.Split(',', System.StringSplitOptions.RemoveEmptyEntries); } catch { return null; }
34+
}
35+
36+
public static JsonDocument AppendElement(this JsonDocument doc, string name, string value)
37+
{
38+
using (var ms = new MemoryStream())
39+
{
40+
using (var writer = new Utf8JsonWriter(ms))
41+
{
42+
writer.WriteStartObject();
43+
44+
foreach (var existElement in doc.RootElement.EnumerateObject())
45+
{
46+
existElement.WriteTo(writer);
47+
}
48+
49+
// Append new element
50+
writer.WritePropertyName(name);
51+
writer.WriteStringValue(value);
52+
53+
writer.WriteEndObject();
54+
}
55+
56+
var resultJson = Encoding.UTF8.GetString(ms.ToArray());
57+
return JsonDocument.Parse(resultJson);
58+
}
59+
}
60+
public static JsonDocument AppendElement(this JsonDocument doc, JsonElement element)
61+
{
62+
using (var ms = new MemoryStream())
63+
{
64+
using (var writer = new Utf8JsonWriter(ms))
65+
{
66+
writer.WriteStartObject();
67+
68+
foreach (var existElement in doc.RootElement.EnumerateObject())
69+
{
70+
existElement.WriteTo(writer);
71+
}
72+
73+
element.WriteTo(writer);
74+
75+
writer.WriteEndObject();
76+
}
77+
78+
var resultJson = Encoding.UTF8.GetString(ms.ToArray());
79+
return JsonDocument.Parse(resultJson);
80+
}
81+
}
82+
}
83+
}

src/WeixinAuth/Extensions/JsonKeyArrayClaimAction.cs

Lines changed: 31 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,17 @@
11
using Microsoft.AspNetCore.Authentication.OAuth.Claims;
2-
using Newtonsoft.Json.Linq;
3-
using System;
4-
using System.Collections.Generic;
52
using System.Security.Claims;
6-
using System.Text;
3+
using System.Text.Json;
74

85
namespace Myvas.AspNetCore.Authentication.WeixinAuth.Internal
96
{
107
internal class JsonKeyArrayClaimAction : ClaimAction
118
{
9+
public JsonKeyArrayClaimAction(string claimType, string valueType)
10+
: base(claimType, valueType)
11+
{
12+
JsonKey = claimType.ToLower();
13+
}
14+
1215
/// <summary>
1316
/// Creates a new JsonKeyArrayClaimAction.
1417
/// </summary>
@@ -25,14 +28,32 @@ public JsonKeyArrayClaimAction(string claimType, string valueType, string jsonKe
2528
/// </summary>
2629
public string JsonKey { get; }
2730

28-
public override void Run(JObject userData, ClaimsIdentity identity, string issuer)
29-
{
30-
var values = userData?[JsonKey];
31-
if (!(values is JArray)) return;
31+
#region removed from 3.0, JObject replaced by JsonElement
32+
//public override void Run(JObject userData, ClaimsIdentity identity, string issuer)
33+
//{
34+
// var values = userData?[JsonKey];
35+
// if (!(values is JArray)) return;
3236

33-
foreach (var value in values)
37+
// foreach (var value in values)
38+
// {
39+
// identity.AddClaim(new Claim(ClaimType, value.ToString(), ValueType, issuer));
40+
// }
41+
//}
42+
#endregion
43+
44+
public override void Run(JsonElement userData, ClaimsIdentity identity, string issuer)
45+
{
46+
var isArray = userData.GetArrayLength() > 0;
47+
if (isArray)
48+
{
49+
var arr = userData.GetStringArray(JsonKey);
50+
foreach (var value in arr)
51+
identity.AddClaim(new Claim(ClaimType, value.ToString(), ValueType, issuer));
52+
}
53+
else
3454
{
35-
identity.AddClaim(new Claim(ClaimType, value.ToString(), ValueType, issuer));
55+
var s = userData.GetString(JsonKey);
56+
identity.AddClaim(new Claim(ClaimType, s, ValueType, issuer));
3657
}
3758
}
3859
}
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
using Microsoft.Extensions.Logging;
2+
using System;
3+
4+
namespace Myvas.AspNetCore.Authentication.WeixinAuth.Internal
5+
{
6+
internal static class LoggingExtensions
7+
{
8+
private static Action<ILogger, string, string, Exception> _handleChallenge;
9+
10+
static LoggingExtensions()
11+
{
12+
_handleChallenge = LoggerMessage.Define<string, string>(
13+
eventId: new EventId(1, "HandleChallenge"),
14+
logLevel: LogLevel.Debug,
15+
formatString: "HandleChallenge with Location: {Location}; and Set-Cookie: {Cookie}.");
16+
}
17+
18+
public static void HandleChallenge(this ILogger logger, string location, string cookie)
19+
=> _handleChallenge(logger, location, cookie, null);
20+
}
21+
}
Lines changed: 5 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,37 +1,32 @@
11
using Microsoft.AspNetCore.Authentication.OAuth;
2-
using Newtonsoft.Json.Linq;
3-
using System;
4-
using System.Collections.Generic;
5-
using System.Linq;
6-
using System.Threading.Tasks;
72

83
namespace Myvas.AspNetCore.Authentication.WeixinAuth.Internal
94
{
105
internal static class OAuthTokenResponseExtensions
116
{
127
public static string GetUnionId(this OAuthTokenResponse response)
138
{
14-
return response.Response.Value<string>("unionid");
9+
return response.Response.RootElement.GetString("unionid");
1510
}
1611

1712
public static string GetOpenId (this OAuthTokenResponse response)
1813
{
19-
return response.Response.Value<string>("openid");
14+
return response.Response.RootElement.GetString("openid");
2015
}
2116

2217
public static string GetScope(this OAuthTokenResponse response)
2318
{
24-
return response.Response.Value<string>("scope");
19+
return response.Response.RootElement.GetString("scope");
2520
}
2621

2722
public static string GetErrorCode(this OAuthTokenResponse response)
2823
{
29-
return response.Response.Value<string>("errcode");
24+
return response.Response.RootElement.GetString("errcode");
3025
}
3126

3227
public static string GetErrorMsg(this OAuthTokenResponse response)
3328
{
34-
return response.Response.Value<string>("errmsg");
29+
return response.Response.RootElement.GetString("errmsg");
3530
}
3631
}
3732
}

0 commit comments

Comments
 (0)