The use of OAuth in Webapi, the call method of the front and back table separation

Source: Internet
Author: User
Tags oauth

Some time ago, as the company architecture Service layer converted to WEBAPI, we studied the use of OAuth in Webapi, which encountered a lot of pits in which to document the correct use of OAuth.

1. What does OAuth do?

In the online browsing, everyone has seen this feature: Site A provides third-party login services, such as the use of Sina Weibo, QQ account login. When the user logs in using a third party account, the third party returns token to site A, and when site A calls the third party service to request the login user information, it must pass the token to the third party, and the third will allow the service request. Each subsequent request does not require re-authentication, and the token can be used directly. This is the typical application of OAuth.

2. Introduction to Simple use (use OAuth method for more information: Use client Credentials Grant authorization to issue tokens in ASP. Owin OAuth)

2.1, the user login process is the process of obtaining tokens, the front-end user Login sample code is as follows:

1 $.ajax ({2Type"POST",3Url:api_address +"token",//api_address for WEBAPI service address, because OAuth is set in the use of the property Tokenendpointpath = new PathString ("/token"), so request to "token" Automatically enter the certification process when linking. 4Data: {grant_type:"Password", Username:username, Password:password, Ran:Math.random ()},//Pass user name, password, authentication method5DataType:"JSON",6 success:function (Result) {7                 if(Result.access_token && result.access_token.length >0) {8                       //Result.access_token is a valid service invocation credential that can be stored in a cookie for the next use. 9Callback1,"Login successful. ");Ten                 } One                 Else { ACallback0,"Unknown Error! "); -                 } -             }, the error:function (XMLHttpRequest, Textstatus, Errorthrown) { -Callback0, XMLHttpRequest.responseJSON.error); -             } -});
Login Code

2.2, when the authentication method is password, the method is one step in the certification process. (the certification will only return token)

1  Public OverrideTask grantresourceownercredentials (oauthgrantresourceownercredentialscontext context)2 {3     varUsername=context. UserName;4     varpassword=context. Password;5     if(user name and password are not valid)6     {7Context.seterror ("User name or password is wrong! ”);//certification does not pass8     }9     ElseTen     { One     varOauthidentity =Newclaimsidentity (context. Options.authenticationtype); AOauthidentity.addclaim (NewClaim (claimtypes.name, context. UserName)); -     //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 (NewClaim ("UserID", user. Userid.tostring ())); the     varTicket =NewAuthenticationticket (Oauthidentity,Newauthenticationproperties ()); -Context. Validated (ticket);//certified by -     }  -     return Base. Grantresourceownercredentials (context); +}
Authentication Code

3. Have obtained token, how to use it?

Most of the examples on the web are in the way of using httpclient calls, and the complete separation of the front and back ends as a development trend, we need to call the jquery method.

1 $.ajax ({2Type: "Method",//Get,post,put,delete3Url:api_address + "Api/test",//If you call the TestController in Webapi4 data: {data},5DataType:"JSON",6 headers: {7                 "Authorization":"Bearer"+ "token"//add tokens obtained by login to the HTTP request header8             },9 success:function (Result) {Ten callback (result); One             }, A error:function (XMLHttpRequest, Textstatus, Errorthrown) { -                 //...  -             } the});
Invoke API

4. How do I access the API?

In the certification we have the user login success as a sign of authentication, but the users of different roles have different access rights (personally believe that the authentication should use the least-privilege authentication, such as the successful login in the example), how to control some controllers can not be accessed by low-privileged users.

1 [Authorize]2  Public classTestcontroller:apicontroller3 {4     //GET api/<controller>5      PublicHttpresponsemessage Get (intAppID)6     {7         return NULL;8     }9}
a typical apicontroller.

[Authorize] means that the request to access the controller must be authenticated (with token information in the request header), where we can customize a feature to verify the user's permissions and replace the attribute Authorizeattribute. (here only provides the idea, the concrete method please oneself grope, does not guarantee the following code correctness)

1  Public classCustomeAuthorizeAttribute:System.Web.Http.AuthorizeAttribute2 {3         protected Override BOOLisauthorized (System.Web.Http.Controllers.HttpActionContext actioncontext)4     {5         if(Base. IsAuthorized (actioncontext))6         {7             //The user's permissions are verified here, and Actioncontext can obtain the requested controller .8             varuser = HttpContext.Current.User.Identity;//user information in token9              if(can be accessed)Ten             { One                  return true; A             } -              return false; -            } the            return false; -         } - } -                 
Example Custom attributes (interceptors)

The use of OAuth in Webapi, the call method of the front and back table separation

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.