Using client Credentials Grant authorization to issue tokens in ASP. Owin OAuth based on

Source: Internet
Author: User
Tags oauth ticket

1) Create a Web API 4 project with Visual Studio 2013/2015, vs generates a bunch of OAuth-related code.

2) Open Startup.Auth.cs, simplify the code, we only need to implement the client Credentials grant authorization method to get token, all other unrelated code to clear all, and finally left the following code:

Using system;using system.collections.generic;using system.linq;using microsoft.aspnet.identity;using Microsoft.aspnet.identity.entityframework;using microsoft.owin;using microsoft.owin.security.cookies;using Microsoft.owin.security.google;using microsoft.owin.security.oauth;using owin;using WebApi4.Providers;using Webapi4.models;namespace webapi4{public partial class Startup {public static oauthauthorizationserveroption        s oauthoptions {get; private set;}        public static string Publicclientid {get; private set;} For more information about configuring authentication, go to http://go.microsoft.com/fwlink/? linkid=301864 public void Configureauth (Iappbuilder app) {var oauthoptions = new Oauthauthorizat ionserveroptions {tokenendpointpath = new pathstring ("/token"),//example of an address for token: http://localhost  : 54342/token Provider = new Customauthorizationserverprovider (),//Accesstokenexpiretimespan = Timespan.fromdays (+),//token hasValidity period allowinsecurehttp = true}; App.        Useoauthbearertokens (oauthoptions); }    }}

  

3) Create a new class Customauthorizationserverprovider, and inherit from Oauthauthorizationserverprovider, overloaded Oauthauthorizationserverprovider () and Grantclientcredentials () are the two methods. The code is as follows:

Using microsoft.owin.security;using microsoft.owin.security.oauth;using system;using System.Collections.Generic; Using system.linq;using system.security.claims;using system.threading.tasks;using system.web;namespace webapi4.providers{public class Customauthorizationserverprovider:oauthauthorizationserverprovider {//&L T;summary>///In Validateclientauthentication () method to obtain the client's client_id and Client_secret to verify///In Grantclien The Tcredentials () method authorizes the client to grant access tokens to//</summary>//<param name= "context" ></pa ram>//<returns></returns> public override Task Validateclientauthentication (Oauthvalidatec            Lientauthenticationcontext context) {string clientId;            String Clientsecret; Context. Trygetbasiccredentials (out ClientId, out clientsecret);//Use Basic authentication to pass clientId and clientsecret; Use form Authentication Trygetformcredentials if (clientId == "XSJ" && Clientsecret = = "1989") {context.            Validated (CLIENTID); } return base.        Validateclientauthentication (context); } public override Task Grantclientcredentials (Oauthgrantclientcredentialscontext context) {var o authidentity = new Claimsidentity (context.            Options.authenticationtype);            Oauthidentity.addclaim (New Claim (Claimtypes.name, "XSJ"));            var ticket = new Authenticationticket (oauthidentity, New Authenticationproperties ()); Context.            Validated (ticket); Return base.        Grantclientcredentials (context); }    }}

  

4) Then write the client call code to test it:

Using system;using system.collections.generic;using system.linq;using system.net.http;using System.Net.Http.Headers ; using system.text;using system.web;using system.web.mvc;namespace webapi4.controllers{public class Homecontroller:c            Ontroller {public ActionResult Index () {viewbag.title = "Home page";        return View (); } public Contentresult Get_accesss_token_by_client_credentials_grant () {//home/get_accesss_token _by_client_credentials_grant
Use form authentication to pass ClientID with Clientsecret//httpclient _httpclient = new HttpClient (); _httpclient.baseaddress = new Uri ("http://localhost:54342"); var parameters = new dictionary<string, string> (); Parameters. ADD ("client_id", "XSJ"); Parameters. ADD ("Client_secret", "1989"); Parameters. ADD ("Grant_type", "client_credentials");////string result = _httpclient.postasync ("/token", New formurlencoded Content (Parameters)). Result.Content.ReadAsStringAsync (). Result; return Content (Result);
Use Basic authentication to pass ClientId with clientsecret var clientId = "XSJ";//user name var Clientsecret = "1989" ;//password HttpClient _httpclient = new HttpClient (); _httpclient.baseaddress = new Uri ("http://localhost:54342"); _httpclient.defaultrequestheaders.authorization = new Authenticationheadervalue ("Basic", convert.tobase64string ( Encoding.ASCII.GetBytes (ClientId + ":" + Clientsecret)); var parameters = new dictionary<string, string> (); Parameters. ADD ("Grant_type", "client_credentials"); string result = _httpclient.postasync ("/token", new Formurlencodedcontent (parameters)). Result.Content.ReadAsStringAsync (). Result; return Content (Result); } }}

return Result:

{"Access_token": "Ah7eq761wpuqjffaw0q9qoxy1lxq3bxvsfnjiixomg2u_ppsvyxw5xmdr1tywffsyn4x2vpkqw0hffsonndg6os3zu-_ Nag5aycjmcotypkvqqbkueahxzdf8qvwiibyli0u7oxhtnyv_opeuzkuucucecboloc9_y4ff627uevqerzritk_ oot0atxsykftxuw2m0puxhlwpb2p6ys25g "," Token_type ":" Bearer "," expires_in ": 1209599}

Note: Use Basic authentication to pass ClientID and Clientsecret, Trygetformcredentials () in the server Customauthorizationserverprovider Change to Trygetbasiccredentials ()

Use Fiddler to obtain tokens:

Resources

Http://www.cnblogs.com/dudu/p/4569857.html

Http://www.hackered.co.uk/articles/asp-net-mvc-creating-an-oauth-client-credentials-grant-type-token-endpoint

Using client Credentials Grant authorization to issue tokens in ASP. Owin OAuth based on

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.