OAuth2.0 Information
Original intention: always want to organize the Authorization series demo, let oneself Project high-end big Still, list the novice authorization series, help small white programmer not in for authorization headache
OAuth allows users to provide a token instead of a user name and password to access their data stored in a particular service provider. Each token authorizes a specific website (for example, a video editing site) to access a specific resource (for example, a video in only one album) within a specific period of time (for example, within the next 2 hours). In this way, OAuth allows users to authorize third-party websites to access certain information that they store in other service providers, rather than all content.
The above concepts are from: Https://zh.wikipedia.org/wiki/OAuth
Detailed theoretical knowledge, refer to the article as follows, this article is in practice
1.http://www.cnblogs.com/lanxiaoke/p/6358332.html
2.https://www.cnblogs.com/selimsong/p/8037717.html
3.http://www.cnblogs.com/xishuai/p/aspnet-webapi-owin-oauth2.html
Project Practice Development
Step 1 and Step 2 are OK, crossing will be happy.
Step 1
Install through NuGet
Microsoft.Owin.Security.OAuth
Owin Microsoft.Owin.Host.SystemWeb (Key)
Step 2
Owin Microsoft.Owin.Host.SystemWeb (Key)
Microsoft.Owin.Security.OAuth
Microsoft.Owin.Security.Cookies (can be ignored)
Microsoft.AspNet.Identity.Owin
The point is that Step 1 is missing a core DLL, and this core DLL is less able to start deployment Owin
New Startup.cs
[Assembly:owinstartup (typeof(Oauth2.startup))] namespace oauth2{ publicpartialclass Startup { public void Configuration (Iappbuilder app) { Configureauth (app); }}}
Owin Microsoft.Owin.Host.SystemWeb through this DLL, program startup time registration, if not referenced, the method will not take effect, crossing can hit a breakpoint to try
New Startup.Auth.cs
namespaceoauth2{ Public Partial classStartup { Public voidConfigureauth (Iappbuilder app) {app. Useoauthbearerauthentication (Newoauthbearerauthenticationoptions () {//get token from URL, compatible with Hearder mode//Provider = new Querystringoauthbearerprovider ("Access_token") }); varOauthoptions =Newoauthauthorizationserveroptions {allowinsecurehttp=true, Tokenendpointpath=NewPathString ("/token"),//Get Access_token Authentication Service request AddressAuthorizeendpointpath =NewPathString ("/authorize"),//Get Authorization_code Authentication Service request AddressAccesstokenexpiretimespan = Timespan.fromseconds (3600),//Access_token Expiration TimeProvider=NewOpenauthorizationserverprovider (),//Access_token Related certification servicesAuthorizationcodeprovider =NewOpenauthorizationcodeprovider (),//Authorization_code Certification ServicesRefreshtokenprovider =NewOpenrefreshtokenprovider ()//Refresh_token Certification Services }; App. Useoauthbearertokens (oauthoptions); //indicates Token_type uses Bearer method } } Public classQuerystringoauthbearerprovider:oauthbearerauthenticationprovider {ReadOnly string_name; PublicQuerystringoauthbearerprovider (stringname) {_name=name; } Public OverrideTask Requesttoken (Oauthrequesttokencontext context) {varValue =context. Request.Query.Get (_name); if(!string. IsNullOrEmpty (value)) {context. Token=value; } returntask.fromresult<Object> (NULL); } }}
Sharp-eyed classmates must notice that the two class names are the same, the namespace is the same, why no error please note the keyword partial
The Openauthorizationserverprovider sample code is shown in detail in the demo, only the code needs attention to the place
/// <summary> ///Verifying client Information/// </summary> Public Override AsyncTask validateclientauthentication (Oauthvalidateclientauthenticationcontext context) {stringclientId; stringClientsecret; if(!context. Trygetbasiccredentials (out clientId, out Clientsecret)) {context. Trygetformcredentials ( outClientId, outClientsecret); } if(ClientId! ="Xishuai"|| Clientsecret! ="123") {context. SetError ("invalid_client","client or Clientsecret is not valid"); return; } context. Validated (); }
Public string basestring () { string"xishuai"; string " 123 " ; return " : " + Clientsecret)); }
Context. Trygetbasiccredentials Otherwise cannot parse the validation does not pass
The Openauthorizationcodeprovider sample code is shown in detail in demo
The Openrefreshtokenprovider sample code is shown in detail in demo
New ValueController.cs
Public classValuecontroller:apicontroller {//get api/values access_token authentication to access[Authorize] [HttpGet] Publicienumerable<string>Index () {return New string[] {"value1","value2" }; }
Get authorization code [HttpGet] [Route ("Api/authorization_code")] PublicHttpresponsemessage Get (stringcode) { return NewHttpresponsemessage () {Content=NewStringcontent (Code, ENCODING.UTF8,"Text/plain") }; } }
New OAuthon2Controller.cs
Public classOauthon2controller:controller {//depending on your project portPrivate Const stringHost_address ="http://localhost:60903"; //Get:oauthon2 Direct access to the authorization Code link for easy access to code Public stringIndex () {stringClientId ="Xishuai"; stringURL = $"{Host_address}/authorize?grant_type=authorization_code&response_type=code&client_id={clientid} &redirect_uri={httputility.urlencode ($"{Host_address}/api/authorization_code")}"; returnURL; } }
According to the URL obtained, the red part of the URL is copied to the browser can get to the code
Now code has the will get Access_token
Grant_type:authorization_code
Code: The red URL on the graph is returned to you
Client_id:xishuai can be understood as AppID custom, because the code is fixed, you can change
Redirect_uri: This link you can also change, accept code in ValueController.cs (Action:api/authorization_code)
Http://localhost:60903/api/authorization_code
This place needs to be aware of the need to be consistent with you getting code Redirect_uri.
String url = $ "{host_address}/authorize?grant_type=authorization_code&response_type=code&client_id={ Clientid}&redirect_uri={httputility.urlencode ($ "{Host_address}/api/authorization_code")} ";
And then you get Access_token to call Api/value/index.
If you enter the wrong place, you will get a failure.
Authorization bearer back space in input Access_token
SOURCE download
ASP. NET OAuth 2.0 Novice Road