Examples of ASP. NETCore integration with WeChat logon

Source: Internet
Author: User
Tags openid
This article mainly Introduces ASP. NETCore integrated login related information, has a certain reference value, interested friends can refer to this article mainly Introduces ASP. NET Core integrated login related information, has a certain reference value, interested friends can refer

Tools:

Visual Studio 2015 update 3

Asp. Net Core 1.0

1. preparations

Apply for a public platform interface test account. application URL: (mp.weixin.qq.com/debug/cgi-bin/sandbox? T = sandbox/login ). You can apply for an API test number without a public account. you can directly experience and test all the advanced interfaces on the public platform.

1.1 configure interface information

3.3 register and log on middleware

Open the Startup. cs file and add the code in Configure:

app.UseWeChatAuthentication(new WeChatOptions(){ AppId = "******", AppSecret = "******"});

Note that the code must be inserted under app. UseIdentity.

4. code

WeChatAppBuilderExtensions. cs:

// Copyright (c) .NET Foundation. All rights reserved.// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.using System;using Microsoft.AspNetCore.Authentication.WeChat;using Microsoft.Extensions.Options;namespace Microsoft.AspNetCore.Builder{ ///  /// Extension methods to add WeChat authentication capabilities to an HTTP application pipeline. ///  public static class WeChatAppBuilderExtensions {  ///   /// Adds the 
   middleware to the specified 
  , which enables WeChat authentication capabilities.  ///   /// The 
  to add the middleware to.  /// 
 
  A reference to this instance after the operation has completed.
   public static IApplicationBuilder UseWeChatAuthentication(this IApplicationBuilder app)  {   if (app == null)   {    throw new ArgumentNullException(nameof(app));   }   return app.UseMiddleware
 
  ();  }  /// 
    /// Adds the 
    middleware to the specified 
   , which enables WeChat authentication capabilities.  ///   /// 
  The 
   to add the middleware to.  /// 
  A 
   that specifies options for the middleware.  /// 
  
   A reference to this instance after the operation has completed.
    public static IApplicationBuilder UseWeChatAuthentication(this IApplicationBuilder app, WeChatOptions options)  {   if (app == null)   {    throw new ArgumentNullException(nameof(app));   }   if (options == null)   {    throw new ArgumentNullException(nameof(options));   }   return app.UseMiddleware
  
   (Options.Create(options));  } }}
  
 

WeChatDefaults. cs:

// Copyright (c) .NET Foundation. All rights reserved.// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.namespace Microsoft.AspNetCore.Authentication.WeChat{ public static class WeChatDefaults {  public const string AuthenticationScheme = "WeChat";  public static readonly string AuthorizationEndpoint = "https://open.weixin.qq.com/connect/oauth2/authorize";  public static readonly string TokenEndpoint = "https://api.weixin.qq.com/sns/oauth2/access_token";  public static readonly string UserInformationEndpoint = "https://api.weixin.qq.com/sns/userinfo"; }}

WeChatHandler. cs

// Copyright (c ). NET Foundation. all rights reserved. // Licensed under the Apache License, Version 2.0. see License.txt in the project root for license information. using Microsoft. aspNetCore. authentication. OAuth; using Microsoft. aspNetCore. builder; using Microsoft. aspNetCore. http. authentication; using Microsoft. aspNetCore. http. extensions; using Microsoft. extensions. primitives; using Newtonsoft. json. linq; using System. collections. generic; using System. net. http; using System. net. http. headers; using System. security. claims; using System. text; using Microsoft. aspNetCore. mvc; using System. threading. tasks; namespace Microsoft. aspNetCore. authentication. weChat {internal class WeChatHandler: OAuthHandler
 
  
{Public WeChatHandler (HttpClient httpClient): base (httpClient) {} protected override async Task HandleRemoteAuthenticateAsync () {AuthenticationProperties properties = null; var query = Request. query; var error = query ["error"]; if (! StringValues. IsNullOrEmpty (error) {var failureMessage = new StringBuilder (); failureMessage. Append (error); var errorDescription = query ["error_description"]; if (! StringValues. IsNullOrEmpty (errorDescription) {failureMessage. Append ("; Description ="). Append (errorDescription);} var errorUri = query ["error_uri"]; if (! StringValues. isNullOrEmpty (errorUri) {failureMessage. append ("; Uri = "). append (errorUri);} return AuthenticateResult. fail (failureMessage. toString ();} var code = query ["code"]; var state = query ["state"]; var oauthState = query ["oauthstate"]; properties = Options. stateDataFormat. unprotect (oauthState); if (state! = Options. StateAddition | properties = null) {return AuthenticateResult. Fail ("The oauth state was missing or invalid.");} // oauh2 10.12 CSRF if (! ValidateCorrelationId (properties) {return AuthenticateResult. fail ("Correlation failed. ");} if (StringValues. isNullOrEmpty (code) {return AuthenticateResult. fail ("Code was not found. ");} // Get tokens var tokens = await ExchangeCodeAsync (code, BuildRedirectUri (Options. callbackPath); var identity = new ClaimsIdentity (Options. claimsIssuer); AuthenticationTicket ticket = null; if (Options. weChatScop E = Options. infoScope) {// obtain user information ticket = await CreateTicketAsync (identity, properties, tokens);} else {// do not obtain information, only use openid identity. addClaim (new Claim (ClaimTypes. nameIdentifier, tokens. tokenType, ClaimValueTypes. string, Options. claimsIssuer); ticket = new AuthenticationTicket (new ClaimsPrincipal (identity), properties, Options. authenticationScheme);} if (ticket! = Null) {return AuthenticateResult. Success (ticket);} else {return AuthenticateResult. Fail ("Failed to retrieve user information from remote server .");}}///
  /// OAuth Step 1: Get code //////
  ///
  ///
  Protected override string BuildChallengeUrl (AuthenticationProperties properties, string redirectUri) {// encrypted OAuth status var oauthstate = Options. StateDataFormat. Protect (properties); // redirectUri = $ "{redirectUri }? {Nameof (oauthstate) }={ oauthstate} "; var queryBuilder = new QueryBuilder () {" appid ", Options. clientId}, {"redirect_uri", redirectUri}, {"response_type", "code"}, {"scope", Options. weChatScope}, {"state", Options. stateAddition },}; return Options. authorizationEndpoint + queryBuilder. toString ();}///
  /// Step 2 of OAuth, get token //////
  ///
  ///
  Protected override async Task
  
   
ExchangeCodeAsync (string code, string redirectUri) {var tokenRequestParameters = new Dictionary
   
    
() {"Appid", Options. clientId}, {"secret", Options. clientSecret}, {"code", code}, {"grant_type", "authorization_code" },}; var requestContent = new FormUrlEncodedContent (tokenRequestParameters); var requestMessage = new HttpRequestMessage (HttpMethod. post, Options. tokenEndpoint); requestMessage. headers. accept. add (new MediaTypeWithQualityHeaderValue ("application/json"); requestMessage. content = requestContent; var response = await Backchannel. sendAsync (requestMessage, Context. requestAborted); if (response. isSuccessStatusCode) {var payload = JObject. parse (await response. content. readAsStringAsync (); string ErrCode = payload. value
    
     
("Errcode"); string ErrMsg = payload. Value
     
      
("Errmsg"); if (! String. IsNullOrEmpty (ErrCode) |! String. isNullOrEmpty (ErrMsg) {return OAuthTokenResponse. failed (new Exception ($ "ErrCode: {ErrCode}, ErrMsg: {ErrMsg}");} var tokens = OAuthTokenResponse. success (payload); // use the TokenType attribute to save the openid tokens. tokenType = payload. value
      
        ("Openid"); return tokens;} else {var error = "OAuth token endpoint failure"; return OAuthTokenResponse. Failed (new Exception (error ));}}///
       /// Step 4 of OAuth, get user information //////
       ///
       ///
       ///
       Protected override async Task CreateTicketAsync (ClaimsIdentity identity, AuthenticationProperties properties, OAuthTokenResponse tokens) {var queryBuilder = new QueryBuilder () {"access_token", tokens. accessToken}, {"openid", tokens. tokenType}, // in step 2, the openid is saved to the TokenType attribute {"lang", "zh_CN" }}; var infoRequest = Options. userInformationEndpoint + queryBuilder. toString (); var response = await B Ackchannel. GetAsync (infoRequest, Context. RequestAborted); if (! Response. isSuccessStatusCode) {throw new HttpRequestException ($ "Failed to retrieve WeChat user information ({response. statusCode}) Please check if the authentication information is correct and the corresponding WeChat Graph API is enabled. ");} var user = JObject. parse (await response. content. readAsStringAsync (); var ticket = new AuthenticationTicket (new ClaimsPrincipal (identity), properties, Options. authenticationScheme); var context = new OAuthCreatingTicketContext (ticket, Context, Options, Backchannel, tokens, user); var identifier = user. value
       
         ("Openid"); if (! String. IsNullOrEmpty (identifier) {identity. AddClaim (new Claim (ClaimTypes. NameIdentifier, identifier, ClaimValueTypes. String, Options. ClaimsIssuer);} var nick name = user. Value
        
          ("Nickname"); if (! String. IsNullOrEmpty (nickname) {identity. AddClaim (new Claim (ClaimTypes. Name, nickname, ClaimValueTypes. String, Options. ClaimsIssuer);} var sex = user. Value
         
           ("Sex"); if (! String. isNullOrEmpty (sex) {identity. addClaim (new Claim ("urn: WeChat: sex", sex, ClaimValueTypes. string, Options. claimsIssuer);} var country = user. value
          
            ("Country"); if (! String. IsNullOrEmpty (country) {identity. AddClaim (new Claim (ClaimTypes. Country, country, ClaimValueTypes. String, Options. ClaimsIssuer);} var province = user. Value
           
             ("Province"); if (! String. IsNullOrEmpty (province) {identity. AddClaim (new Claim (ClaimTypes. StateOrProvince, province, ClaimValueTypes. String, Options. ClaimsIssuer);} var city = user. Value
            
              ("City"); if (! String. isNullOrEmpty (city) {identity. addClaim (new Claim ("urn: WeChat: city", city, ClaimValueTypes. string, Options. claimsIssuer);} var headimgurl = user. value
             
               ("Headimgurl"); if (! String. isNullOrEmpty (headimgurl) {identity. addClaim (new Claim ("urn: WeChat: headimgurl", headimgurl, ClaimValueTypes. string, Options. claimsIssuer);} var unionid = user. value
              
                ("Unionid"); if (! String. isNullOrEmpty (unionid) {identity. addClaim (new Claim ("urn: WeChat: unionid", unionid, ClaimValueTypes. string, Options. claimsIssuer);} await Options. events. creatingTicket (context); return context. ticket ;}}}
              
             
            
           
          
         
        
       
      
     
    
   
  
 

WeChatMiddleware. cs

// Copyright (c) .NET Foundation. All rights reserved.// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.using System;using System.Globalization;using System.Text.Encodings.Web;using Microsoft.AspNetCore.Authentication.OAuth;using Microsoft.AspNetCore.Builder;using Microsoft.AspNetCore.DataProtection;using Microsoft.AspNetCore.Http;using Microsoft.Extensions.Logging;using Microsoft.Extensions.Options;namespace Microsoft.AspNetCore.Authentication.WeChat{ ///  /// An ASP.NET Core middleware for authenticating users using WeChat. ///  public class WeChatMiddleware : OAuthMiddleware
 
   {  /// 
    /// Initializes a new 
   .  ///   /// 
  The next middleware in the HTTP pipeline to invoke.  /// 
    /// 
    /// 
    /// 
    /// 
  Configuration options for the middleware.  public WeChatMiddleware(   RequestDelegate next,   IDataProtectionProvider dataProtectionProvider,   ILoggerFactory loggerFactory,   UrlEncoder encoder,   IOptions
  
    sharedOptions,   IOptions
   
     options)   : base(next, dataProtectionProvider, loggerFactory, encoder, sharedOptions, options)  {   if (next == null)   {    throw new ArgumentNullException(nameof(next));   }   if (dataProtectionProvider == null)   {    throw new ArgumentNullException(nameof(dataProtectionProvider));   }   if (loggerFactory == null)   {    throw new ArgumentNullException(nameof(loggerFactory));   }   if (encoder == null)   {    throw new ArgumentNullException(nameof(encoder));   }   if (sharedOptions == null)   {    throw new ArgumentNullException(nameof(sharedOptions));   }   if (options == null)   {    throw new ArgumentNullException(nameof(options));   }   if (string.IsNullOrEmpty(Options.AppId))   {    throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, nameof(Options.AppId)));   }   if (string.IsNullOrEmpty(Options.AppSecret))   {    throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, nameof(Options.AppSecret)));   }  }  /// 
      /// Provides the 
      object for processing authentication-related requests.  ///   /// 
    
     An 
      configured with the 
      supplied to the constructor.
      protected override AuthenticationHandler
    
      CreateHandler()  {   return new WeChatHandler(Backchannel);  } }}
    
   
  
 

WeChatOptions. cs

// Copyright (c ). NET Foundation. all rights reserved. // Licensed under the Apache License, Version 2.0. see License.txt in the project root for license information. using System. collections. generic; using Microsoft. aspNetCore. authentication. weChat; using Microsoft. aspNetCore. http; using Microsoft. aspNetCore. identity; namespace Microsoft. aspNetCore. builder {////// Configuration options
  .///Public class WeChatOptions: oautexceptions {////// Initializes a new
  .///Public WeChatOptions () {AuthenticationScheme = WeChatDefaults. authenticationScheme; DisplayName = AuthenticationScheme; CallbackPath = new PathString ("/signin-wechat"); StateAddition = "# wechat_redirect"; AuthorizationEndpoint = WeChatDefaults. authorizationEndpoint; TokenEndpoint = WeChatDefaults. tokenEndpoint; UserInformationEndpoint = WeChatDefaults. userInformationEndpoint; // SaveTokens = true; // Baseline (the authorization page is not displayed, and you can only get the user's openid). // InfoScope (the authorization page is displayed. you can get the nickname, gender, and location through openid. In addition, even if the user is not concerned, the user can obtain the information as long as the user is authorized.) WeChatScope = InfoScope;} // WeChat uses a non-standard term for this field .////// Gets or sets the WeChat-assigned appId .///Public string AppId {get {return ClientId;} set {ClientId = value ;}}// WeChat uses a non-standard term for this field .////// Gets or sets the WeChat-assigned app secret .///Public string AppSecret {get {return ClientSecret;} set {ClientSecret = value;} public string StateAddition {get; set;} public string WeChatScope {get; set ;} public string baseline = "snsapi_base"; public string InfoScope = "snsapi_userinfo ";}}

The above is a detailed illustration of the ASP. NET Core integrated logon instance. For more information, see other related articles on php Chinese network!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.