"Client Authentication" is implemented in the ASP. NET API using OAuth2.0

Source: Internet
Author: User

One. Implement a class that inherits from Oauthauthorizationserverprovider and implements the relevant authentication and Access_token issued in the form of "client-side authentication".

public class Myownoauthprovider:oauthauthorizationserverprovider {private static readonly Logger Logger = Logma Nager.        GetLogger ("Myownoauth");        <summary>//Client Authentication///</summary>//<param name= "context" ></param> <returns></returns> public override Task Validateclientauthentication (oauthvalidateclientauthen            Ticationcontext context) {string clientId;            String Clientsecret; Gets the client's incoming user name and password in context.            Trygetformcredentials (out Clientid,out Clientsecret); Logger.            Info ("Username:" +clientid+ "Password:" +clientsecret+ "login website ...");                You can use your own data validation, such as through database queries and so on if (clientId = = "Myownapp" && Clientsecret = = "ctmdsh!320") { Context.            Validated (CLIENTID); } return base.        Validateclientauthentication (context);     }///<summary>//To issue access tokens after authorizing the client in the method   </summary>//<param name= "context" ></param>//<returns></returns> public override Task Grantclientcredentials (Oauthgrantclientcredentialscontext context) {var Oaut hidentity = new Claimsidentity (context.            Options.authenticationtype);            Oauthidentity.addclaim (New Claim ("Myownapp", "LJX"));            The API can be used to get the values in this way.            var identity = (claimsidentity) user.identity; var mayiaccount = identity.              Findfirstvalue ("Myownapp");            var ticket = new Authenticationticket (oauthidentity,new authenticationproperties ()); Context.            Validated (ticket); Logger.            Info ("LJX issued to User Access_token ..."); Return base.        Grantclientcredentials (context); }    }

  

Overload Validateclientauthentication method, implement client-side verification, overload Grantclientcredentials method, implement Access_token release.

Two. With the relevant configuration, set the processing class that you created provider to Authroize.
1. Locate the Startup.auth in the App_start folder, locate the Oauthoptions method, and modify the corresponding provider completion configuration:
    oauthoptions = new Oauthauthorizationserveroptions            {                Tokenendpointpath = new PathString ("/token"),                 Myownoauthprovider(),               //Authorizeendpointpath = new PathString ("/api/account/externallogin"),                Accesstokenexpiretimespan = Timespan.fromdays (+),                //in production mode allowinsecurehttp = False                Allowinsecurehttp = True            };

  

Myownoauthprovider is replaced with the validation logic class we created ourselves.


Three. Add the [authorize] property to the Controller or action in the API.

Four. Note If you want to implement cross-domain access, you need to include the Configureauth method in the Startup.auth file
App. Usecors (Corsoptions.allowall);

Of course, you need to first use NuGet to install Microsoft.Owin.Cors references.

Five. The call to implement the response on the client.

1. To set the $.ajax before the submission of the processing method:

$ (function () {$.ajaxsetup ({cache:false, beforesend:function (xhr, option) {VA            R Opentid = "Myownapp";            var Opensecret = "ctmdsh!320";            Alert ("Start"); $.ajax ({type: ' Post ', Async:false, Url:hosturl + "token", D ATA: {client_id:opentid, Client_secret:opensecret,grant_type: "Client_credentials"}, Tokenskip:true, Success:function (data) {XHR.SETR                                    Equestheader ("Authorization", "Bearer" + Data.access_token);            }            }); }}, Complete:function () {}, Error:function (a) {if (typeof Consol            E.log = = = "function") {Console.log (a.responsetext); }        }    });})

  

CLIENT_ID indicates the user, Client_secret indicates the password, grant_type: "Client_credentials" indicates the authentication method.

2. Directly invoke the Response API interface on the corresponding page.
    $ (function () {                                    $.ajax ({            type: "Get",            URL: "Http://localhost:51067/api/values",            success:function ( Data) {                alert (data);            }        );    })

  





"Client Authentication" is implemented in the ASP. NET API using OAuth2.0

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.