1.OAuth Password Mode
2. Create a WEBAPI project in VS installed in NuGet:
Microsoft.AspNet.WebApi.Owin
Microsoft.Owin.Host.SystemWeb
These two class libraries and add Owin startup class startup
usingSystem;usingSystem.Threading.Tasks;usingMicrosoft.owin;usingOwin;usingMicrosoft.Owin.Security.OAuth; [Assembly:owinstartup (typeof(Webapioauth.startup))]namespacewebapioauth{ Public classStartup { Public voidConfiguration (Iappbuilder app) {varOauthoptions =Newoauthauthorizationserveroptions {allowinsecurehttp=true, Tokenendpointpath=NewPathString ("/token"),//get Access_token Authorized Service request AddressAuthorizeendpointpath =NewPathString ("/authorize"),//get Authorization_code Authorized Service request AddressAccesstokenexpiretimespan = Timespan.fromseconds (Ten),//Access_token Expiration TimeProvider=NewOpenauthorizationserverprovider (),//Access_token related Licensing Services }; App. Useoauthbearertokens (oauthoptions); //indicates that Token_type uses the bearer method to authenticate bearer tokens } }}
The Configureoauth (Iappbuilder app) method opens the OAuth service. Simply say the meaning of each parameter in the oauthauthorizationserveroptions:
Allowinsecurehttp: Allow client one HTTP protocol request;
Tokenendpointpath:token the requested address, i.e. http://localhost: port number/token;
Accesstokenexpiretimespan:token Expiration Time;
Provider: Provide the specific authentication strategy;
3. Inheriting the authorization service Oauthauthorizationserverprovider class
Overloading the Validateclientauthentication method to verify the correctness of the client
The overloaded Grantresourceownercredentials method implements the authentication of the user name password and the token is issued after verification.
Public classOpenauthorizationserverprovider:oauthauthorizationserverprovider {/// <summary> ///Verifies that the caller 's ClientID and Clientsecret have verified the legitimacy of the caller (ClientID, Clientsecret is a contract-good string). /// </summary> /// <param name= "context" ></param> /// <returns></returns> Public Override AsyncTask validateclientauthentication (Oauthvalidateclientauthenticationcontext context) {stringclientId; stringClientsecret; Context. Trygetbasiccredentials ( outClientId, outClientsecret); if(ClientId = ="1234"&& Clientsecret = ="5678") {context. Validated (CLIENTID); } await Base. Validateclientauthentication (context); } /// <summary> ///obtaining a user name and password for authentication by overloading Grantresourceownercredentials/// </summary> /// <param name= "context" ></param> /// <returns></returns> Public Override AsyncTask grantresourceownercredentials (Oauthgrantresourceownercredentialscontext context) {//Call the backend login service to verify the user name and password if(Context. UserName! ="Admin"|| Context. Password! ="123456") {context. SetError ("invalid_grant","The user name or password is incorrect. "); return; } varOauthidentity =Newclaimsidentity (context. Options.authenticationtype); Oauthidentity.addclaim (NewClaim (claimtypes.name, context. UserName)); varTicket =NewAuthenticationticket (Oauthidentity,Newauthenticationproperties ()); Context. Validated (ticket); await Base. Grantresourceownercredentials (context); } }
Add the [authorize] label to the method where authentication is required, and access to this interface must be authenticated by authorization.
All of the above server-side code is complete.
4. Create a new client project to test add a test class
classOauthclienttest {PrivateHttpClient _httpclient; Private stringtoken; Publicoauthclienttest () {_httpclient=NewHttpClient (); _httpclient.baseaddress=NewUri ("http://localhost"); } Public Asynctask<string>Getaccesstoken () {varClientId ="1234"; varClientsecret ="5678"; varParameters =Newdictionary<string,string>(); Parameters. ADD ("Grant_type","Password"); Parameters. ADD ("username","Admin"); Parameters. ADD ("Password","123456"); _httpclient.defaultrequestheaders.authorization=NewAuthenticationheadervalue ("Basic", Convert.tobase64string (Encoding.ASCII.GetBytes (clientId+":"+Clientsecret)) ); varResponse =await_httpclient.postasync ("Oauthtest/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; } } Public AsyncTask call_webapi_by_resource_owner_password_credentials_grant () {if(string. IsNullOrEmpty (token) token=awaitGetaccesstoken (); Console.WriteLine (token); _httpclient.defaultrequestheaders.authorization=NewAuthenticationheadervalue ("Bearer", token); Console.WriteLine (await(await_httpclient.getasync ("oauthtest/api/values")). Content.readasstringasync ()); } }
Test is called in the Main method:
Static void Main (string[] args) { varnew oauthclienttest (); var task = clienttest.call_webapi_by_resource_owner_password_credentials_grant (); Task. Wait (); // var token = Clienttest.getaccesstoken (); // var strtoken = token. Result; // Console.WriteLine (strtoken); console.readline (); }
The results are as follows:
The long string of characters is token, "value1, value2" is the result of the access Webapi return, indicating that the access was successful.
Reference 1:http://www.cnblogs.com/xishuai/p/aspnet-webapi-owin-oauth2.html
Reference 2:http://www.cnblogs.com/leo_wl/p/4919783.html
"7". NET WebAPI Owin OAuth 2.0 password Mode Authentication instance