Related article: ASP. WebApi OWIN implements OAuth 2.0
Prior to the implementation of the project, tokens are placed in the Headers of the request header, similar to this:
Accept: application/jsonContent-Type: application/jsonAuthorization: Bearer pADKsjwMv927u...
Although this is the most standard implementation, sometimes we face some business changes, such as Token requirements placed in the URL or Post Body, such as:
https://www.domain.com/api/MyController?access_token=pADKsjwMv927u...
The ASP. NET WebApi OWIN to achieve the above requirements, there are many ways, here only two records.
The first way, rewritten OAuthBearerAuthenticationOptions
, will be Startup.Auth.cs
transformed as follows:
Public Partial classstartup{ Public void Configureauth(Iappbuilder app) {varOauthoptions =Newoauthauthorizationserveroptions {allowinsecurehttp =true, Authenticationmode = Authenticationmode.Active, Tokenendpointpath =New pathstring("/token"),//Get Access_token Authentication Service request AddressAuthorizeendpointpath=New pathstring("/authorize"),//Get Authorization_code Authentication Service request AddressAccesstokenexpiretimespan = TimeSpan.FromSeconds( -),//access_token Expiration TimeProvider =New Openauthorizationserverprovider(),//access_token Related certification servicesAuthorizationcodeprovider =New Openauthorizationcodeprovider(),//authorization_code Certification ServicesRefreshtokenprovider =New Openrefreshtokenprovider()//refresh_token Certification Services}; App.Useoauthbearertokens(oauthoptions);//indicates token_type use bearer modeApp.useoauthbearerauthentication(New oauthbearerauthenticationoptions() {//Get token from URL, compatible with Hearder modeProvider =New Querystringoauthbearerprovider("Access_token") }); }} Public classquerystringoauthbearerprovider:oauthbearerauthenticationprovider{ReadOnly string_name; Public Querystringoauthbearerprovider(stringName) {_name = name; } Public OverrideTaskRequesttoken(Oauthrequesttokencontext context) {varValue = Context.Request.Query.Get(_name);if(!string.IsNullOrEmpty(value)) {context.Token= value; }returnTask.Fromresult<Object> (NULL); }}
Test results:
or simply rough Way (not recommended), increase request interception, add Application_BeginRequest
code as follows:
protected void Application_BeginRequest(Objectsender, EventArgs e) {//Another way to get tokens from a URL if(ReferenceEquals(NULL, HttpContext. Current.Request.Headers["Authorization"])) {vartoken = HttpContext. Current.Request.Params["Access_token"];if(! String.IsNullOrEmpty(token)) {HttpContext. Current.Request.Headers.ADD("Authorization","Bearer"+ token); } }}
Project Source: https://github.com/yuezhongxin/OAuth2.Demo/
Resources:
- How can I validate my custom Oauth2 access tokens in Server-side
- ASP. NET Web Api:how to pass an access token (OAuth 2.0) using URL parameter?
ASP. WebApi OWIN implements OAuth 2.0 (custom get Token)