OAuth is a complex thing, and even if you recite the OAuth specification, you don't get it when you implement it. As a result, Microsoft.Owin.Security.OAuth came into being (its implementation code in the Katana project), helping developers to steal a lot of work and cut down a lot of material.
This blog post attempts to share with a simple example how to use the client Credentials grant authorization method to issue access tokens to clients based on Microsoft.Owin.Security.OAuth.
The authorization method of client Credentials grant is to authenticate only the client, not the user (Resource Owner), as long as the client sends access token through authentication. To give an example of a corresponding scenario, for example, we would like to provide a "get the latest blog post list of the homepage" Webapi to the iOS app. Since this data is irrelevant to the user, it does not involve user login and authorization, and does not require resource owner's participation. But we don't want anyone to be able to invoke this webapi, so it's OK to authenticate the client, but using the Credentials grant authorization method in OAuth is a good way to solve this problem.
The specific implementation is as follows:
1) Creating a Web API 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:
Public Partial classstartup{ Public voidConfigureauth (Iappbuilder app) {varOauthoptions =Newoauthauthorizationserveroptions {Tokenendpointpath=NewPathString ("/token"), Provider=NewCnblogsauthorizationserverprovider (), Accesstokenexpiretimespan= Timespan.fromdays ( -), Allowinsecurehttp=true }; App. Useoauthbearertokens (oauthoptions); }}
3) Create a new class Cnblogsauthorizationserverprovider, and inherit from Oauthauthorizationserverprovider, overloaded Oauthauthorizationserverprovider () and Grantclientcredentials () are the two methods. The code is as follows:
Public classcnblogsauthorizationserverprovider:oauthauthorizationserverprovider{ Public OverrideTask validateclientauthentication (Oauthvalidateclientauthenticationcontext context) {stringclientId; stringClientsecret; Context. Trygetformcredentials ( outClientId, outClientsecret); if(ClientId = ="1234"&& Clientsecret = ="5678") {context. Validated (CLIENTID); } return Base. Validateclientauthentication (context); } Public OverrideTask grantclientcredentials (Oauthgrantclientcredentialscontext context) {varOauthidentity =Newclaimsidentity (context. Options.authenticationtype); Oauthidentity.addclaim (NewClaim (Claimtypes.name,"IOS App")); varTicket =NewAuthenticationticket (Oauthidentity,Newauthenticationproperties ()); Context. Validated (ticket); return Base. Grantclientcredentials (context); }}
The client_id and Client_secret of the client are obtained in the Validateclientauthentication () method for validation.
Authorize the client in the Grantclientcredentials () method to grant access tokens.
In this way, the server-side code for OAuth is complete. So simple? Yes, it's that simple, because of the Microsoft.Owin.Security.OAuth.
4) Then write the client call code to test it:
Public classoauthclienttest{PrivateHttpClient _httpclient; Publicoauthclienttest () {_httpclient=NewHttpClient (); _httpclient.baseaddress=NewUri ("http://openapi.cnblogs.com"); } [Fact] Public voidget_accesss_token_by_client_credentials_grant () {varParameters =Newdictionary<string,string>(); Parameters. ADD ("client_id","1234"); Parameters. ADD ("Client_secret","5678"); Parameters. ADD ("Grant_type","client_credentials"); Console.WriteLine (_httpclient.postasync ("/token",Newformurlencodedcontent (Parameters)). Result.Content.ReadAsStringAsync (). Result); }}
The results of the operation are as follows:
{"Access_token": "8pqawilv_ Sjt7vrxambp7mebyaf3ko1gxyhsqa-opmoqf6xk1ypluczozgo-wwatu5ymgb0wsr0cuqmc8rszfwo8nwom7yg11fianhy2pniqtg2cydjf0sf0ggfs6it _i3mc_m1iefck2dlbpdjxpi24wngcpr0wp_zugzvykv314bm0pqmnnwg3klxr1diskrbs5-i59vctfszgkm7a0w "," Token_type ":" Bearer " , "expires_in": 1209599}
Get!
Resources
ASP. mvc:creating an OAuth client credentials grant Type token endpoint
Using client Credentials Grant authorization to issue tokens in ASP. Owin OAuth