ASP. NET Web API with Owin OAuth: invoking user-related web APIs

Source: Internet
Author: User
Tags oauth

Reference page:

Http://www.yuanjiaocheng.net/webapi/web-api-route.html

Http://www.yuanjiaocheng.net/webapi/parameter-binding.html

Http://www.yuanjiaocheng.net/webapi/action-method-returntype.html

Http://www.yuanjiaocheng.net/webapi/web-api-reqresq-format.html

Http://www.yuanjiaocheng.net/webapi/media-formatter.html

In the previous blog post, we successfully invoked the user-independent Web API by using Access tokens that were received by OAuth's client Credential Grant authorization method (which only validates the calling client, without verifying the logged-in user).

In this blog post, we will get access Token in the authorization mode (Grant_type=password) of OAuth's Resource Owner Password Credentials Grant and call the user with this token The associated Web API.

The corresponding scenario is to develop a mobile app for your own website (not a third-party app) that requires users to log on to the app without having to authorize the data that the app can access.

According to the OAuth specification, the client gets access Token in the following way:

Post/token http/1.1host:server.example.comauthorization:basic Czzcagrsa3f0mzpnwdfmqmf0m2jwcontent-type: application/x-www-form-urlencodedgrant_type=password&username=johndoe&password=a3ddj3w

Based on the above request method, a simple client is implemented in C # with HttpClient, with the following code:

 Public classoauthclienttest{PrivateHttpClient _httpclient;  Publicoauthclienttest () {_httpclient=NewHttpClient (); _httpclient.baseaddress=NewUri ("http://openapi.cnblogs.com"); } [Fact] Public AsyncTask get_accesss_token_by_resource_owner_password_credentials_grant () {Console.WriteLine (awaitGetaccesstoken ()); }    Private Asynctask<string>Getaccesstoken () {varClientId ="1234"; varClientsecret ="5678"; varParameters =Newdictionary<string,string>(); Parameters. ADD ("Grant_type","Password"); Parameters. ADD ("username","Blog Park Team"); Parameters. ADD ("Password","cnblogs.com"); _httpclient.defaultrequestheaders.authorization=NewAuthenticationheadervalue ("Basic", Convert.tobase64string (Encoding.ASCII.GetBytes (clientId+":"+Clientsecret))        ); varResponse =await_httpclient.postasync ("/token",Newformurlencodedcontent (parameters)); varResponsevalue =awaitResponse.        Content.readasstringasync (); if(Response. StatusCode = =System.Net.HttpStatusCode.OK) {returnJobject.parse (Responsevalue) ["Access_token"]. value<string>(); }        Else{Console.WriteLine (responsevalue); return string.        Empty; }    }}

(Note: The Client_id/client_secret here is changed to Basic Authorization to better follow the OAuth specification than before)

On the server side, based on Owin OAuth, the authorization method for Resource Owner Password Credentials Grant is simply overloaded Oauthauthorizationserverprovider.grantresourceownercredentials () method. The code is as follows:

 Public classcnblogsauthorizationserverprovider:oauthauthorizationserverprovider{//...     Public Override AsyncTask grantresourceownercredentials (Oauthgrantresourceownercredentialscontext context) {//Call the backend login service to verify the user name and password        varOauthidentity =Newclaimsidentity (context.        Options.authenticationtype); Oauthidentity.addclaim (NewClaim (claimtypes.name, context.        UserName)); varTicket =NewAuthenticationticket (Oauthidentity,Newauthenticationproperties ()); Context.        Validated (ticket); await Base.    Grantresourceownercredentials (context); }}

The complete Cnblogsauthorizationserverprovider implementation code is as follows (compared to the previous context. Trygetformcredentials was changed to context. Trygetbasiccredentials):

 Public classcnblogsauthorizationserverprovider:oauthauthorizationserverprovider{ Public Override AsyncTask validateclientauthentication (Oauthvalidateclientauthenticationcontext context) {stringclientId; stringClientsecret; Context. Trygetbasiccredentials ( outClientId, outClientsecret); if(ClientId = ="1234"&& Clientsecret = ="5678") {context.        Validated (CLIENTID); }        await Base.    Validateclientauthentication (context); }     Public Override AsyncTask grantclientcredentials (Oauthgrantclientcredentialscontext context) {varOauthidentity =Newclaimsidentity (context.        Options.authenticationtype); varTicket =NewAuthenticationticket (Oauthidentity,Newauthenticationproperties ()); Context.        Validated (ticket); await Base.    Grantclientcredentials (context); }     Public Override AsyncTask grantresourceownercredentials (Oauthgrantresourceownercredentialscontext context) {//Call the backend login service to verify the user name and password        varOauthidentity =Newclaimsidentity (context.        Options.authenticationtype); Oauthidentity.addclaim (NewClaim (claimtypes.name, context.        UserName)); varTicket =NewAuthenticationticket (Oauthidentity,Newauthenticationproperties ()); Context.        Validated (ticket); await Base.    Grantresourceownercredentials (context); }}
Cnblogsauthorizationserverprovider

This way, you can get Access tokens by running the client program.

Next, we take access tokens that we get in this way, and we can invoke the Web APIs that are relevant to the user.

On the server side we test with a simple Web API, the code is as follows:

 Public class userscontroller:apicontroller{    [authorize]    publicstring  getcurrent ()    {        return  User.Identity.Name;         // You can call the background User Service, get the number of users, or verify the user permissions to do the appropriate action     }}

The client then calls this web API with Access tokens that are Grant_type=password, and the client adds the following code:

 [fact]  public  async   Task call_webapi_by_resource_owner_password_credentials_grant () { var  token = await      Getaccesstoken (); _httpclient.defaultrequestheaders.authorization  = new  Authenticationheadervalue ( " bearer   "  await  (await  _ Httpclient.getasync ( " /api/users/current   "  

The client runs the following results:

"Blog Park Team"

Call succeeded! The result of the run is the username used to get access tokens.

Combined with the existing security mechanisms of ASP., with the power of OWIN, Microsoft.Owin.Security.OAuth does make it easier to develop OAuth-based Web APIs.

ASP. NET Web API with Owin OAuth: invoking user-related web APIs

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.