-
Notifications
You must be signed in to change notification settings - Fork 550
Add Baidu Provider #247
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Add Baidu Provider #247
Changes from 1 commit
Commits
File filter
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
commit 7ae8d5ccb0e4ba072b9a4d3478a8622a2491010c
There are no files selected for viewing
20 changes: 20 additions & 0 deletions
20
src/AspNet.Security.OAuth.Baidu/AspNet.Security.OAuth.Baidu.csproj
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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
70
src/AspNet.Security.OAuth.Baidu/BaiduAuthenticationConstants.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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"; | ||
| /// <summary> | ||
| /// 当前登录用户的用户名,值可能为空。 | ||
| /// </summary> | ||
| public const string UserName = "urn:baidu:username"; | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Use |
||
| /// <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"; | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Use |
||
| /// <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
52
src/AspNet.Security.OAuth.Baidu/BaiduAuthenticationDefaults.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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
76
src/AspNet.Security.OAuth.Baidu/BaiduAuthenticationExtensions.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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
126
src/AspNet.Security.OAuth.Baidu/BaiduAuthenticationHandler.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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); | ||
| } | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Use
ClaimTypes.NameIdentifier