Server and client interaction based on ASP. (ii) Get OAuth 2.0 authentication Permissions

Source: Internet
Author: User
Tags oauth

ASP. OAUTH2 authentication for the basic Web API
    • Add token extra Fields
    • Add Scope Authorization Field
    • Persistent tokens
    • Time interval for token design
    • Failed token after refreshing token
    • Custom Validation "Restart IIS pool token invalidation, verify permissions"
process of OAUTH2 certification

The client sends the password (grant_type,client_id,client_secret) to the server-side request, the authentication returns access token, and the client then obtains the access token according to the access Token gets permission to access the Web API.

Configuration and Preparation: Here we use the OAUTH2 service-side implementation, which requires the introduction of authorize (authorization server dependency) and Resourceserver (resource server dependency).

After adding the authorize flag, the API request test, if not through the OAUTH2 authentication mechanism will appear, the request is rejected

At the beginning, when the program starts, the client accesses the API, the design enters the security authentication state

1    Public void Configuration (Iappbuilder app) 2         {3            4            app. Usecors (Corsoptions.allowall); 5             Configureauth (APP); 6         }
View Code
1App. Useoauthbearertokens (Newoauthauthorizationserveroptions2             {3Tokenendpointpath =NewPathString ("/token"),4Provider =NewApplicationoauthprovider (),5                 //Refreshtokenprovider = new Applicationrefreshtokenprovider (),6Accesstokenexpiretimespan = Timespan.fromhours (2),7Authenticationmode =authenticationmode.active,8                 //HTTPS is allowed only allowinsecurehttp = False9Allowinsecurehttp =trueTen                 //applicationcandisplayerrors = False One});
View Code

First step: Get access tokens based on password passwords (when passwords and accounts are correct)

        <summary>//Verify Customer [client_id and Client_secret Verification]///</summary>//<param NA Me= "Context" ></param>///<returns></returns> public override Task Validateclientauthen Tication (Oauthvalidateclientauthenticationcontext context) {//http://localhost:48339/token/            /grant_type=client_credentials&client_id=irving&client_secret=123456 string client_id;            String Client_secret; Context.            Trygetformcredentials (out client_id, out Client_secret); if (client_id = = "abc" && Client_secret = = "123456") {context.            Validated (client_id); } else {//context.                Response.statuscode = Convert.ToInt32 (Httpstatuscode.ok); Context.            SetError ("Invalid_client", "Client is not valid"); } return base.        Validateclientauthentication (context); }

 <summary>///client authorization [generate access token]///</summary>//<param name= "context" >& lt;/param>//<returns></returns> public override Task Grantclientcredentials (Oauthgrantclie Ntcredentialscontext context) {/* var client = _oauthclientservice.getclient (context.                 CLIENTID); Oauthidentity.addclaim (New Claim (Claimtypes.name, client.             ClientName)); *///var oauthidentity = new Claimsidentity (context.            Options.authenticationtype);            Oauthidentity.addclaim (New Claim (Claimtypes.name, "iphone"));            var ticket = new Authenticationticket (oauthidentity, New Authenticationproperties () {Allowrefresh = true}); Context.            Validated (ticket); Return base.            Grantclientcredentials (context); var oauthidentity = new Claimsidentity (context.            Options.authenticationtype); Oauthidentity.addclaim (New Claim (claimtyPes.            Name, "iphone")); User information and other necessary information can be added to the token for use in the API service (            The Oauthidentity object is used in HttpContext.Current.User.Identity, and user.identity can be used directly in WEBAPI Controller).            Oauthidentity.addclaim (New Claim ("UserID", "Irving"));            var ticket = new Authenticationticket (oauthidentity, New Authenticationproperties ()); Context. Validated (ticket);//certification via return base.        Grantclientcredentials (context); }

Step Two: Refresh token

<summary>//        refresh token[Refresh Refresh_token]//</summary>//        <param name= "Context" > </param>        ///<returns></returns> public override Task Grantrefreshtoken ( Oauthgrantrefreshtokencontext context)        {            //enforce client binding of Refresh token            if (context. Ticket = = NULL | | Context. Ticket.identity = = NULL | | !context. Ticket.Identity.IsAuthenticated)            {                context. SetError ("Invalid_grant", "Refresh token is not valid");            }            else            {                //additional claim is needed-separate access token updating from authentication                 //requests in Ref Reshtokenprovider.createasync () method            }            return base. Grantrefreshtoken (context);        }

The next step is to use the client to call the client via the account password, which is described in detail in an essay.

Server and client interaction based on ASP. (ii) Get OAuth 2.0 authentication Permissions

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.