Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
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
Next Next commit
Add Baidu Provider
  • Loading branch information
ArcherTrister committed Jun 30, 2018
commit 7ae8d5ccb0e4ba072b9a4d3478a8622a2491010c
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>zhengchun;Chino Chang</Authors>
<PackageTags>aspnetcore;authentication;oauth;security;baidu</PackageTags>
</PropertyGroup>

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

</Project>
70 changes: 70 additions & 0 deletions src/AspNet.Security.OAuth.Baidu/BaiduAuthenticationConstants.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
/*
* 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
{
/// <summary>
/// 当前登录用户的数字ID
/// </summary>
public const string UserId = "urn:baidu:userid";
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Use ClaimTypes.NameIdentifier

/// <summary>
/// 当前登录用户的用户名,值可能为空。
/// </summary>
public const string UserName = "urn:baidu:username";
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Use ClaimTypes.Name

/// <summary>
/// 用户真实姓名,可能为空。
/// </summary>
public const string RealName = "urn:baidu:realname";
/// <summary>
/// 当前登录用户的头像
/// </summary>
public const string Portrait = "urn:baidu:portrait";
/// <summary>
/// 自我简介,可能为空。
/// </summary>
public const string UserDetail = "urn:baidu:userdetail";
/// <summary>
/// 生日,以yyyy-mm-dd格式显示。
/// </summary>
public const string Birthday = "urn:baidu:birthday";
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Use ClaimTypes.DateOfBirth

/// <summary>
/// 婚姻状况
/// </summary>
public const string Marriage = "urn:baidu:marriage";
/// <summary>
/// 血型
/// </summary>
public const string Blood = "urn:baidu:blood";
/// <summary>
/// 体型
/// </summary>
public const string Figure = "urn:baidu:figure";
/// <summary>
/// 星座
/// </summary>
public const string Constellation = "urn:baidu:constellation";
/// <summary>
/// 学历
/// </summary>
public const string Education = "urn:baidu:education";
/// <summary>
/// 当前职业
/// </summary>
public const string Trade = "urn:baidu:trade";
/// <summary>
/// 职位
/// </summary>
public const string Job = "urn:baidu:job";
}
}
}
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 = "http://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/getInfo";
}
}
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>A reference to this instance after the operation has completed.</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>A reference to this instance after the operation has completed.</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);
}
}
}
126 changes: 126 additions & 0 deletions src/AspNet.Security.OAuth.Baidu/BaiduAuthenticationHandler.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
/*
* 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 System.Collections.Generic;
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.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 response = await Backchannel.GetAsync(address);
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 user information.");
}

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

var status = payload.Value<long>("userid");
if (status <= 0)
{
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 user information.");
}

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);
}

protected override async Task<OAuthTokenResponse> ExchangeCodeAsync(string code, string redirectUri)
{
var address = QueryHelpers.AddQueryString(Options.TokenEndpoint, new Dictionary<string, string>()
{
["client_id"] = Options.ClientId,
["client_secret"] = Options.ClientSecret,
["code"] = code,
["grant_type"] = "authorization_code",
["redirect_uri"] = redirectUri
});

var response = await Backchannel.GetAsync(address);
if (!response.IsSuccessStatusCode)
{
Logger.LogError("An error occurred while retrieving an access token: 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());

return OAuthTokenResponse.Failed(new Exception("An error occurred while retrieving an access token."));
}

var payload = JObject.Parse(await response.Content.ReadAsStringAsync());
if (!string.IsNullOrEmpty(payload.Value<string>("errcode")))
{
Logger.LogError("An error occurred while retrieving an access token: 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());

return OAuthTokenResponse.Failed(new Exception("An error occurred while retrieving an access token."));
}
return OAuthTokenResponse.Success(payload);
}

protected override string BuildChallengeUrl(AuthenticationProperties properties, string redirectUri)
{
return QueryHelpers.AddQueryString(Options.AuthorizationEndpoint, new Dictionary<string, string>
{
["client_id"] = Options.ClientId,
["scope"] = FormatScope(),
["response_type"] = "code",
["redirect_uri"] = redirectUri,
["state"] = Options.StateDataFormat.Protect(properties)
});
}

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