Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 44 additions & 2 deletions src/AspNet.Security.OAuth.Weixin/WeixinAuthenticationHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,15 @@

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Security.Claims;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using JetBrains.Annotations;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.OAuth;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.WebUtilities;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
Expand All @@ -31,6 +33,25 @@ public WeixinAuthenticationHandler(
{
}

private const string OauthState = "_oauthstate";
private const string State = "state";

protected override async Task<HandleRequestResult> HandleRemoteAuthenticateAsync()
{
if (!IsWeixinAuthorizationEndpointInUse())
{
if (Request.Query.TryGetValue(OauthState, out var stateValue))
{
var query = Request.Query.ToDictionary(c => c.Key, c => c.Value, StringComparer.OrdinalIgnoreCase);
if (query.TryGetValue(State, out var _))
{
query[State] = stateValue;
Request.QueryString = QueryString.Create(query);
}
}
}
return await base.HandleRemoteAuthenticateAsync();
}
protected override async Task<AuthenticationTicket> CreateTicketAsync([NotNull] ClaimsIdentity identity, [NotNull] AuthenticationProperties properties, [NotNull] OAuthTokenResponse tokens)
{
var address = QueryHelpers.AddQueryString(Options.UserInformationEndpoint, new Dictionary<string, string>
Expand Down Expand Up @@ -109,16 +130,37 @@ protected override async Task<OAuthTokenResponse> ExchangeCodeAsync(string code,

protected override string BuildChallengeUrl(AuthenticationProperties properties, string redirectUri)
{
return QueryHelpers.AddQueryString(Options.AuthorizationEndpoint, new Dictionary<string, string>
var stateValue = Options.StateDataFormat.Protect(properties);
var addRedirectHash = false;
if (!IsWeixinAuthorizationEndpointInUse())
{
//Store state in redirectUri when authorizing Wechat Web pages to prevent "too long state parameters" error
redirectUri = QueryHelpers.AddQueryString(redirectUri, OauthState, stateValue);
addRedirectHash = true;
}

redirectUri = QueryHelpers.AddQueryString(Options.AuthorizationEndpoint, new Dictionary<string, string>
{
["appid"] = Options.ClientId,
["scope"] = FormatScope(),
["response_type"] = "code",
["redirect_uri"] = redirectUri,
["state"] = Options.StateDataFormat.Protect(properties)
[State] = addRedirectHash ? OauthState : stateValue
});

if (addRedirectHash)
{
// The parameters necessary for Web Authorization of Wechat
redirectUri += "#wechat_redirect";
}
return redirectUri;
}

protected override string FormatScope() => string.Join(",", Options.Scope);

private bool IsWeixinAuthorizationEndpointInUse()
{
return string.Equals(Options.AuthorizationEndpoint, WeixinAuthenticationDefaults.AuthorizationEndpoint, StringComparison.OrdinalIgnoreCase);
}
}
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
/*
/*
* Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
* See https://github.com/aspnet-contrib/AspNet.Security.OAuth.Providers
* for more information concerning the license and the contributors participating to this project.
Expand Down Expand Up @@ -34,15 +34,25 @@ protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage
string location = queryString["redirect_uri"] ?? RedirectUri;
string state = queryString["state"];

var builder = new UriBuilder(location);

// Retain the _oauthstate parameter in redirect_uri for WeChat (see #262)
const string OAuthStateKey = "_oauthstate";
var redirectQuery = HttpUtility.ParseQueryString(builder.Query);
string oauthState = redirectQuery[OAuthStateKey];

// Remove any query string parameters we do not explictly need to retain
queryString.Clear();

queryString.Add("code", "a6ed8e7f-471f-44f1-903b-65946475f351");
queryString.Add("state", state);

var builder = new UriBuilder(location)
if (!string.IsNullOrEmpty(oauthState))
{
Query = queryString.ToString(),
};
queryString.Add(OAuthStateKey, oauthState);
}

builder.Query = queryString.ToString();

var redirectRequest = new HttpRequestMessage(request.Method, builder.Uri);

Expand Down
57 changes: 57 additions & 0 deletions test/AspNet.Security.OAuth.Providers.Tests/Wechat/WechatTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
/*
* Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
* See https://github.com/aspnet-contrib/AspNet.Security.OAuth.Providers
* for more information concerning the license and the contributors participating to this project.
*/

using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.Extensions.DependencyInjection;
using Xunit;
using Xunit.Abstractions;

namespace AspNet.Security.OAuth.Weixin
{
public class WechatTests : OAuthTests<WeixinAuthenticationOptions>
{
public WechatTests(ITestOutputHelper outputHelper)
{
OutputHelper = outputHelper;
}

public override string DefaultScheme => WeixinAuthenticationDefaults.AuthenticationScheme;

protected internal override void RegisterAuthentication(AuthenticationBuilder builder)
{
builder.AddWeixin(options =>
{
ConfigureDefaults(builder, options);
options.AuthorizationEndpoint = "https://open.weixin.qq.com/connect/oauth2/authorize";
});
}

[Theory]
[InlineData(ClaimTypes.NameIdentifier, "my-id")]
[InlineData(ClaimTypes.Name, "John Smith")]
[InlineData(ClaimTypes.Gender, "Male")]
[InlineData(ClaimTypes.Country, "CN")]
[InlineData("urn:weixin:city", "Beijing")]
[InlineData("urn:weixin:headimgurl", "https://weixin.qq.local/image.png")]
[InlineData("urn:weixin:openid", "my-open-id")]
[InlineData("urn:weixin:privilege", "a,b,c")]
[InlineData("urn:weixin:province", "Hebei")]
public async Task Can_Sign_In_Using_Wechat(string claimType, string claimValue)
{
// Arrange
using (var server = CreateTestServer())
{
// Act
var claims = await AuthenticateUserAsync(server);

// Assert
AssertClaim(claims, claimType, claimValue);
}
}
}
}
35 changes: 35 additions & 0 deletions test/AspNet.Security.OAuth.Providers.Tests/Wechat/bundle.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
{
"$schema": "https://raw.githubusercontent.com/justeat/httpclient-interception/master/src/HttpClientInterception/Bundles/http-request-bundle-schema.json",
"items": [
{
"uri": "https://api.weixin.qq.com/sns/oauth2/access_token?appid=my-client-id&secret=my-client-secret&code=a6ed8e7f-471f-44f1-903b-65946475f351&grant_type=authorization_code",
"contentFormat": "json",
"contentJson": {
"access_token": "secret-access-token",
"token_type": "access",
"refresh_token": "secret-refresh-token",
"expires_in": "300",
"openid": "my-open-id"
}
},
{
"uri": "https://api.weixin.qq.com/sns/userinfo?access_token=secret-access-token&openid=my-open-id",
"contentFormat": "json",
"contentJson": {
"unionid": "my-id",
"nickname": "John Smith",
"sex": "Male",
"country": "CN",
"openid": "my-open-id",
"province": "Hebei",
"city": "Beijing",
"headimgurl": "https://weixin.qq.local/image.png",
"privilege": [
"a",
"b",
"c"
]
}
}
]
}