asp.net core integrated micro-Letter Login _ Practical Tips

Source: Internet
Author: User
Tags oauth openid reserved static class ticket visual studio

Tools:

Visual Studio 2015 Update 3

asp.net Core 1.0

1 Preparation work

Application for micro-trust public Platform Interface test account number, application URL: (http://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=sandbox/login). Application interface test number without public account, you can directly experience and test all the advanced interface of public platform.

1.1 Configuring Interface Information

1.2 Modify the page authorization information

Click "Modify" to fill in your site's domain name on the pop-up page:

2 new Web site projects

2.1 Select asp.net Core Web application Template

2.2 Select the Web application and change the authentication to personal user account

3 Integrated micro-Credit login function

3.1 Adding references

Open Project.json file, add Reference Microsoft.AspNetCore.Authentication.OAuth

3.2 Adding code files

Create a new folder in your project, name it Wechatoauth, and add a code file (with all the code at the end of this article).

3.3 Registered micro-letter Login Middleware

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

App. Usewechatauthentication (New Wechatoptions ()
{

 AppId = "Hu Jintao",

 appsecret = "Hu Jintao"

});

Note that the insertion position of the code must be in the app. Useidentity () below.

4 Code

WeChatAppBuilderExtensions.cs:

Copyright (c). NET Foundation.
All rights reserved. Licensed under the Apache License, Version 2.0.

License.txt in the project root for License information.
Using System;
Using Microsoft.AspNetCore.Authentication.WeChat;

Using Microsoft.Extensions.Options; namespace Microsoft.AspNetCore.Builder {///<summary>///Extension methods to add WeChat authentication
 Ties to an HTTP application pipeline. </summary> public static class Wechatappbuilderextensions {///<summary>///Adds the <see cref= "Wechatmiddleware"/> Middleware to the specified <see cref= "Iapplicationbuilder"/&GT; which enables
  Authentication capabilities. </summary>///<param name= "app" >the <see cref= "Iapplicationbuilder"/> To add the middleware  t;/param>///<returns>a Reference to this instance after the operation has Static Iapplicationbuilder usewechatauthentication (This IApplicationbuilder app) {if (app = null) {throw new ArgumentNullException (nameof (APP)); Return app.
  Usemiddleware<wechatmiddleware> (); }///<summary>///Adds the <see cref= "Wechatmiddleware"/> Middleware to the specified <see "cref="
  Plicationbuilder "/&gt, which enables WeChat authentication. </summary>///<param name= "app" >the <see cref= "Iapplicationbuilder"/> To add the middleware t;/param>///<param name= "Options" >a <see cref= "Wechatoptions"/> that specifies options for the Middlewa re.</param>///<returns>a Reference to-instance after the operation has p Ublic static Iapplicationbuilder usewechatauthentication (this iapplicationbuilder app, wechatoptions options) {if (a
   PP = = null) {throw new ArgumentNullException (nameof (APP)); } if (options = null) {throw new ArgumentNullException (Nameof (OptiONS)); Return app.
  Usemiddleware<wechatmiddleware> (Options) (options.create);
 }
 }
}

WeChatDefaults.cs:

Copyright (c). NET Foundation. All rights reserved.
Licensed under the Apache License, Version 2.0. 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.

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;
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<wechatoptions > {public wechathandler (httpclient httpclient): Base (httpclient) {} protected override async Task<a
   Uthenticateresult> 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 (";D escription=").
    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 is MIS

   Sing or invalid. ");} OAuth2 10.12 CSRF if (! Validatecorrelationid (properties)) {return Authenticateresult.fail ("COrrelation failed. ");}
   if (Stringvalues.isnullorempty (code)) {return Authenticateresult.fail ("code is not found.");

   //Get tokens var tokens = await Exchangecodeasync (code, Buildredirecturi (Options.callbackpath));

   var identity = new Claimsidentity (Options.claimsissuer);

   Authenticationticket ticket = null;  if (Options.wechatscope = = Options.infoscope) {//get user Information ticket = await Createticketasync (identity, properties,
   tokens); else {//do not get information, use OpenID identity only. 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."); }///<summary>///oauth first step, getCode///</summary>///<param name= "Properties" ></param>///<param name= "Redirecturi" >< /param>///<returns></returns> protected override string Buildchallengeurl (Authenticationproperties p

   roperties, String Redirecturi) {//encrypted OAuth state 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 (); ///<summary>///OAuth Step Two, get token///</summary>///<param name= "code" ></param>/ <param name= "Redirecturi" ></param>///<returns></returns> protected override Async Task&lt ; oauthtokenrEsponse> Exchangecodeasync (String code, string Redirecturi) {var tokenrequestparameters = new Dictionary<strin
    G, string> () {{"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<string> ("Errcode"); String errmsg = payload.

    Value<string> ("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 property to save the OpenID tokens. Tokentype = payload.

    Value<string> ("OpenID");
   return tokens;
    else {var error = "OAuth token endpoint Failure";
   Return oauthtokenresponse.failed (new Exception (error)); }///<summary>///oauth step Fourth, get user information///</summary>///<param name= "Identity" ></param&gt
  ; <param name= "Properties" ></param>///<param name= "tokens" ></param>///&LT;RETURNS&GT;&L t;/returns> protected override Async task<authenticationticket> Createticketasync (claimsidentity identity, Authenticationproperties properties, Oauthtokenresponse tokens) {var querybuilder = new QueryBuilder () {{"A Ccess_token ", tokens. Accesstoken}, {"OpenID", tokens. Tokentype},//in the second step, OpenID is deposited in the Tokentype attribute {"Lang", "Zh_cN "}};

   var inforequest = options.userinformationendpoint + querybuilder.tostring ();
   var response = await Backchannel.getasync (inforequest, context.requestaborted); if (!response. Issuccessstatuscode) {throw new Httprequestexception ($ "Failed to retrieve WeChat user information ({response). StatusCode}) Please check if the authentication information are correct and the corresponding WeChat Graph API is enabled. "
   ); The 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<string> ("OpenID"); if (!string. IsNullOrEmpty (identifier)) {identity.
   Addclaim (New Claim (Claimtypes.nameidentifier, identifier, claimvaluetypes.string, Options.claimsissuer)); var nickname = user. Value<string> ("nickname"); if (!string. IsNullOrEmpty (nickname)) {identity.
   Addclaim (New Claim (Claimtypes.name, nickname, Claimvaluetypes.string, Options.claimsissuer)); var sex = user.
   value<string> ("Sex"); if (!string. IsNullOrEmpty (Sex)) {identity.
   Addclaim (New Claim ("Urn:WeChat:sex", Sex, Claimvaluetypes.string, Options.claimsissuer)); var country = user.
   Value<string> ("Country"); if (!string. IsNullOrEmpty (Country)) {identity.
   Addclaim (New Claim (Claimtypes.country, Country, claimvaluetypes.string, Options.claimsissuer)); var province = user.
   Value<string> ("province"); if (!string. IsNullOrEmpty (province)) {identity.
   Addclaim (New Claim (Claimtypes.stateorprovince, Province, Claimvaluetypes.string, Options.claimsissuer)); var city = user.
   Value<string> ("City"); if (!string. IsNullOrEmpty (city)) {identity. Addclaim (New Claim ("Urn:WeChat:city", City, Claimvaluetypes.string, Options.claimsissuer));
   var headimgurl = user.
   Value<string> ("Headimgurl"); if (!string. IsNullOrEmpty (Headimgurl)) {identity.
   Addclaim (New Claim ("Urn:WeChat:headimgurl", Headimgurl, Claimvaluetypes.string, Options.claimsissuer)); var Unionid = user.
   Value<string> ("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.

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 {///<summary>///a asp.net Core middleware for Authentica
 Ting users using WeChat. </summary> public class Wechatmiddleware:oauthmiddleware<wechatoptions> {///<summary>///
  Initializes a new <see cref= "Wechatmiddleware"/&GT;. </summary>///<param name= "Next" >the next middleware in the HTTP pipeline to invoke.</param>// /<param name= "Dataprotectionprovider" ></param>///<paRam Name= "Loggerfactory" ></param>///<param name= "encoder" ></param>///<param "Name=" Sharedo Ptions "></param>///<param name=" Options ">configuration options for the middleware.</param> publ IC Wechatmiddleware (requestdelegate Next, Idataprotectionprovider Dataprotectionprovider, ILoggerFactory LoggerF Actory, Urlencoder Encoder, ioptions<sharedauthenticationoptions> sharedoptions, IOptions<WeChatOptions& Gt
   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 (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)); }///<summary>///provides the <see cref= "Authenticationhandler{t}"/> Object for processing authent
  ication-related requests. </summary>///<returns>an <see cref= "Authenticationhandler{t}"/> configured with the <see = "Wechatoptions"/> supplied to the constructor.</returns> protected override authenticationhandler<
  Wechatoptions> Createhandler () {Return to New Wechathandler (backchannel);

 }
 }
}

WeChatOptions.cs

Copyright (c). NET Foundation.
All rights reserved. Licensed under the Apache License, Version 2.0.

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 {///<summary>///Configuration options for <see cref= "Wechatmiddlewar
 E "/&GT;. </summary> public class Wechatoptions:oauthoptions {///<summary>///Initializes a new <see C
  ref= "Wechatoptions"/&GT;
   </summary> 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; Basescope (does not eject the authorization page, direct jump, can only obtain user OpenID),//infoscope (pop-up authorization page, can get the nickname, Sex, location by OpenID.
  And, even in the case of no concern, as long as the user authorization, can also obtain its information) Wechatscope = Infoscope;
  }//WeChat uses a non-standard term for this field.
  <summary>///Gets or sets the wechat-assigned appId.
   </summary> public string AppId {get {return ClientId;}
  set {ClientId = value;}
  }//WeChat uses a non-standard term for this field.
  <summary>///Gets or sets the Wechat-assigned app secret.
   </summary> public string Appsecret {get {return clientsecret;}
  set {Clientsecret = value;}
  public string Stateaddition {get; set;}

  public string Wechatscope {get; set;}

  public string basescope = "Snsapi_base";
 public string infoscope = "Snsapi_userinfo";

 }
}

This article has been sorted out to the ASP. NET micro-Credit Development tutorial Summary, you are welcome to learn to read.

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Related Article

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.