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
Add Baidu provider
  • Loading branch information
kinosang committed May 22, 2019
commit b0e36ac5ab965e71d18b435e7b0a67d76469e245
7 changes: 7 additions & 0 deletions AspNet.Security.OAuth.Providers.sln
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,8 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "test", "test", "{D7CEAA0A-5
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AspNet.Security.OAuth.Providers.Tests", "test\AspNet.Security.OAuth.Providers.Tests\AspNet.Security.OAuth.Providers.Tests.csproj", "{842A4AA5-A82B-468E-9C25-BCD63C9C8E48}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AspNet.Security.OAuth.Baidu", "src\AspNet.Security.OAuth.Baidu\AspNet.Security.OAuth.Baidu.csproj", "{D7E61F39-7503-4ECA-9A86-43F04D4DBE7D}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand Down Expand Up @@ -312,6 +314,10 @@ Global
{842A4AA5-A82B-468E-9C25-BCD63C9C8E48}.Debug|Any CPU.Build.0 = Debug|Any CPU
{842A4AA5-A82B-468E-9C25-BCD63C9C8E48}.Release|Any CPU.ActiveCfg = Release|Any CPU
{842A4AA5-A82B-468E-9C25-BCD63C9C8E48}.Release|Any CPU.Build.0 = Release|Any CPU
{D7E61F39-7503-4ECA-9A86-43F04D4DBE7D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{D7E61F39-7503-4ECA-9A86-43F04D4DBE7D}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D7E61F39-7503-4ECA-9A86-43F04D4DBE7D}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D7E61F39-7503-4ECA-9A86-43F04D4DBE7D}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down Expand Up @@ -365,6 +371,7 @@ Global
{ED8A220C-45FE-45C6-9B8F-BB009ACE972E} = {C1352FD3-AE8B-43EE-B45B-F6E0B3FBAC6D}
{7C2E82CE-F6EC-41A8-AA22-3466505F95D8} = {C1352FD3-AE8B-43EE-B45B-F6E0B3FBAC6D}
{842A4AA5-A82B-468E-9C25-BCD63C9C8E48} = {D7CEAA0A-50F4-4BE9-90B8-EED43F4CB39B}
{D7E61F39-7503-4ECA-9A86-43F04D4DBE7D} = {C1352FD3-AE8B-43EE-B45B-F6E0B3FBAC6D}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {C7B54DE2-6407-4802-AD9C-CE54BF414C8C}
Expand Down
20 changes: 20 additions & 0 deletions src/AspNet.Security.OAuth.Baidu/AspNet.Security.OAuth.Baidu.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<Project Sdk="Microsoft.NET.Sdk">

<Import Project="..\..\build\packages.props" />

<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
</PropertyGroup>

<PropertyGroup>
<Description>ASP.NET Core security middleware enabling Baidu authentication.</Description>
<Authors>Chino Chang</Authors>
<PackageTags>aspnetcore;authentication;baidu;oauth;security</PackageTags>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="JetBrains.Annotations" Version="$(JetBrainsVersion)" PrivateAssets="All" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.OAuth" Version="$(AspNetCoreVersion)" />
</ItemGroup>

</Project>
19 changes: 19 additions & 0 deletions src/AspNet.Security.OAuth.Baidu/BaiduAuthenticationConstants.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
/*
* 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.
*/

namespace AspNet.Security.OAuth.Baidu
{
/// <summary>
/// Contains constants specific to the <see cref="BaiduAuthenticationHandler"/>.
/// </summary>
public static class BaiduAuthenticationConstants
{
public static class Claims
{
public const string Portrait = "urn:baidu:portrait";
}
}
}
52 changes: 52 additions & 0 deletions src/AspNet.Security.OAuth.Baidu/BaiduAuthenticationDefaults.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
/*
* 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 Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.OAuth;

namespace AspNet.Security.OAuth.Baidu
{
/// <summary>
/// Default values for Baidu authentication.
/// </summary>
public static class BaiduAuthenticationDefaults
{
/// <summary>
/// Default value for <see cref="AuthenticationScheme.Name"/>.
/// </summary>
public const string AuthenticationScheme = "Baidu";

/// <summary>
/// Default value for <see cref="AuthenticationScheme.DisplayName"/>.
/// </summary>
public const string DisplayName = "Baidu";

/// <summary>
/// Default value for <see cref="RemoteAuthenticationOptions.CallbackPath"/>.
/// </summary>
public const string CallbackPath = "/signin-baidu";

/// <summary>
/// Default value for <see cref="AuthenticationSchemeOptions.ClaimsIssuer"/>.
/// </summary>
public const string Issuer = "Baidu";

/// <summary>
/// Default value for <see cref="OAuthOptions.AuthorizationEndpoint"/>.
/// </summary>
public const string AuthorizationEndpoint = "https://openapi.baidu.com/oauth/2.0/authorize";

/// <summary>
/// Default value for <see cref="OAuthOptions.TokenEndpoint"/>.
/// </summary>
public const string TokenEndpoint = "https://openapi.baidu.com/oauth/2.0/token";

/// <summary>
/// Default value for <see cref="OAuthOptions.UserInformationEndpoint"/>.
/// </summary>
public const string UserInformationEndpoint = "https://openapi.baidu.com/rest/2.0/passport/users/getLoggedInUser";
}
}
76 changes: 76 additions & 0 deletions src/AspNet.Security.OAuth.Baidu/BaiduAuthenticationExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
/*
* 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;
using AspNet.Security.OAuth.Baidu;
using JetBrains.Annotations;
using Microsoft.AspNetCore.Authentication;

namespace Microsoft.Extensions.DependencyInjection
{
/// <summary>
/// Extension methods to add Baidu authentication capabilities to an HTTP application pipeline.
/// </summary>
public static class BaiduAuthenticationExtensions
{
/// <summary>
/// Adds <see cref="BaiduAuthenticationHandler"/> to the specified
/// <see cref="AuthenticationBuilder"/>, which enables Baidu authentication capabilities.
/// </summary>
/// <param name="builder">The authentication builder.</param>
/// <returns>The <see cref="AuthenticationBuilder"/>.</returns>
public static AuthenticationBuilder AddBaidu([NotNull] this AuthenticationBuilder builder)
{
return builder.AddBaidu(BaiduAuthenticationDefaults.AuthenticationScheme, options => { });
}

/// <summary>
/// Adds <see cref="BaiduAuthenticationHandler"/> to the specified
/// <see cref="AuthenticationBuilder"/>, which enables Baidu authentication capabilities.
/// </summary>
/// <param name="builder">The authentication builder.</param>
/// <param name="configuration">The delegate used to configure the OpenID 2.0 options.</param>
/// <returns>The <see cref="AuthenticationBuilder"/>.</returns>
public static AuthenticationBuilder AddBaidu(
[NotNull] this AuthenticationBuilder builder,
[NotNull] Action<BaiduAuthenticationOptions> configuration)
{
return builder.AddBaidu(BaiduAuthenticationDefaults.AuthenticationScheme, configuration);
}

/// <summary>
/// Adds <see cref="BaiduAuthenticationHandler"/> to the specified
/// <see cref="AuthenticationBuilder"/>, which enables Baidu authentication capabilities.
/// </summary>
/// <param name="builder">The authentication builder.</param>
/// <param name="scheme">The authentication scheme associated with this instance.</param>
/// <param name="configuration">The delegate used to configure the Baidu options.</param>
/// <returns>The <see cref="AuthenticationBuilder"/>.</returns>
public static AuthenticationBuilder AddBaidu(
[NotNull] this AuthenticationBuilder builder, [NotNull] string scheme,
[NotNull] Action<BaiduAuthenticationOptions> configuration)
{
return builder.AddBaidu(scheme, BaiduAuthenticationDefaults.DisplayName, configuration);
}

/// <summary>
/// Adds <see cref="BaiduAuthenticationHandler"/> to the specified
/// <see cref="AuthenticationBuilder"/>, which enables Baidu authentication capabilities.
/// </summary>
/// <param name="builder">The authentication builder.</param>
/// <param name="scheme">The authentication scheme associated with this instance.</param>
/// <param name="caption">The optional display name associated with this instance.</param>
/// <param name="configuration">The delegate used to configure the Baidu options.</param>
/// <returns>The <see cref="AuthenticationBuilder"/>.</returns>
public static AuthenticationBuilder AddBaidu(
[NotNull] this AuthenticationBuilder builder,
[NotNull] string scheme, [CanBeNull] string caption,
[NotNull] Action<BaiduAuthenticationOptions> configuration)
{
return builder.AddOAuth<BaiduAuthenticationOptions, BaiduAuthenticationHandler>(scheme, caption, configuration);
}
}
}
67 changes: 67 additions & 0 deletions src/AspNet.Security.OAuth.Baidu/BaiduAuthenticationHandler.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
/*
* 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.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
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.WebUtilities;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Newtonsoft.Json.Linq;

namespace AspNet.Security.OAuth.Baidu
{
public class BaiduAuthenticationHandler : OAuthHandler<BaiduAuthenticationOptions>
{
public BaiduAuthenticationHandler(
[NotNull] IOptionsMonitor<BaiduAuthenticationOptions> options,
[NotNull] ILoggerFactory logger,
[NotNull] UrlEncoder encoder,
[NotNull] ISystemClock clock)
: base(options, logger, encoder, clock)
{
}

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>
{
["access_token"] = tokens.AccessToken
});

var request = new HttpRequestMessage(HttpMethod.Get, address);
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

var response = await Backchannel.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, Context.RequestAborted);
if (!response.IsSuccessStatusCode)
{
Logger.LogError("An error occurred while retrieving the user profile: the remote server " +
"returned a {Status} response with the following payload: {Headers} {Body}.",
/* Status: */ response.StatusCode,
/* Headers: */ response.Headers.ToString(),
/* Body: */ await response.Content.ReadAsStringAsync());

throw new HttpRequestException("An error occurred while retrieving the user profile.");
}

var payload = JObject.Parse(await response.Content.ReadAsStringAsync());

var principal = new ClaimsPrincipal(identity);
var context = new OAuthCreatingTicketContext(principal, properties, Context, Scheme, Options, Backchannel, tokens, payload);
context.RunClaimActions(payload);

await Options.Events.CreatingTicket(context);
return new AuthenticationTicket(context.Principal, context.Properties, Scheme.Name);
}
}
}
41 changes: 41 additions & 0 deletions src/AspNet.Security.OAuth.Baidu/BaiduAuthenticationOptions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
/*
* 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.Net;
using System.Security.Claims;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.OAuth;
using Microsoft.AspNetCore.Http;

namespace AspNet.Security.OAuth.Baidu
{
/// <summary>
/// Defines a set of options used by <see cref="BaiduAuthenticationHandler"/>.
/// </summary>
public class BaiduAuthenticationOptions : OAuthOptions
{
public BaiduAuthenticationOptions()
{
ClaimsIssuer = BaiduAuthenticationDefaults.Issuer;
CallbackPath = new PathString(BaiduAuthenticationDefaults.CallbackPath);

AuthorizationEndpoint = BaiduAuthenticationDefaults.AuthorizationEndpoint;
TokenEndpoint = BaiduAuthenticationDefaults.TokenEndpoint;
UserInformationEndpoint = BaiduAuthenticationDefaults.UserInformationEndpoint;

ClaimActions.MapJsonKey(ClaimTypes.NameIdentifier, "uid");
ClaimActions.MapJsonKey(ClaimTypes.Name, "uname");
ClaimActions.MapCustomJson(BaiduAuthenticationConstants.Claims.Portrait,
user =>
{
var portrait = user.Value<string>("portrait");
return string.IsNullOrWhiteSpace(portrait)
? null
: $"https://tb.himg.baidu.com/sys/portrait/item/{WebUtility.UrlEncode(portrait)}";
});
}
}
}
50 changes: 50 additions & 0 deletions test/AspNet.Security.OAuth.Providers.Tests/Baidu/BaiduTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
/*
* 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.Baidu
{
public class BaiduTests : OAuthTests<BaiduAuthenticationOptions>
{
public BaiduTests(ITestOutputHelper outputHelper)
{
OutputHelper = outputHelper;
}

public override string DefaultScheme => BaiduAuthenticationDefaults.AuthenticationScheme;

protected internal override void RegisterAuthentication(AuthenticationBuilder builder)
{
builder.AddBaidu(options =>
{
ConfigureDefaults(builder, options);
});
}

[Theory]
[InlineData(ClaimTypes.NameIdentifier, "my-id")]
[InlineData(ClaimTypes.Name, "my-name")]
[InlineData("urn:baidu:portrait", "https://tb.himg.baidu.com/sys/portrait/item/my-portrait")]
public async Task Can_Sign_In_Using_Baidu(string claimType, string claimValue)
{
// Arrange
using (var server = CreateTestServer())
{
// Act
var claims = await AuthenticateUserAsync(server);

// Assert
AssertClaim(claims, claimType, claimValue);
}
}
}
}
25 changes: 25 additions & 0 deletions test/AspNet.Security.OAuth.Providers.Tests/Baidu/bundle.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
{
"$schema": "https://raw.githubusercontent.com/justeat/httpclient-interception/master/src/HttpClientInterception/Bundles/http-request-bundle-schema.json",
"items": [
{
"uri": "https://openapi.baidu.com/oauth/2.0/token",
"method": "POST",
"contentFormat": "json",
"contentJson": {
"access_token": "secret-access-token",
"token_type": "access",
"refresh_token": "secret-refresh-token",
"expires_in": "300"
}
},
{
"uri": "https://openapi.baidu.com/rest/2.0/passport/users/getLoggedInUser?access_token=secret-access-token",
"contentFormat": "json",
"contentJson": {
"uid": "my-id",
"uname": "my-name",
"portrait": "my-portrait"
}
}
]
}