標籤:overflow using TE context rtu time 直接 ide return
相關文章:ASP.NET WebApi OWIN 實現 OAuth 2.0
之前的項目實現,Token 放在要求標頭的 Headers 裡面,類似於這樣:
Accept: application/jsonContent-Type: application/jsonAuthorization: Bearer pADKsjwMv927u...
雖然這是最標準的實現方式,但有時候我們會面對一些業務變化,比如 Token 要求放在 URL 或是 Post Body 裡面,比如這樣:
https://www.domain.com/api/MyController?access_token=pADKsjwMv927u...
ASP.NET WebApi OWIN 實現上面的需求,有很多種方式,這邊只記錄兩種。
第一種方式,重寫OAuthBearerAuthenticationOptions
,將Startup.Auth.cs
改造如下:
public partial class Startup{ public void ConfigureAuth(IAppBuilder app) { var OAuthOptions = new OAuthAuthorizationServerOptions { AllowInsecureHttp = true, AuthenticationMode = AuthenticationMode.Active, TokenEndpointPath = new PathString("/token"), //擷取 access_token 認證服務要求地址 AuthorizeEndpointPath=new PathString("/authorize"), //擷取 authorization_code 認證服務要求地址 AccessTokenExpireTimeSpan = TimeSpan.FromSeconds(100), //access_token 到期時間 Provider = new OpenAuthorizationServerProvider(), //access_token 相關認證服務 AuthorizationCodeProvider = new OpenAuthorizationCodeProvider(), //authorization_code 認證服務 RefreshTokenProvider = new OpenRefreshTokenProvider() //refresh_token 認證服務 }; app.UseOAuthBearerTokens(OAuthOptions); //表示 token_type 使用 bearer 方式 app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions() { //從url中擷取token,相容hearder方式 Provider = new QueryStringOAuthBearerProvider("access_token") }); }}public class QueryStringOAuthBearerProvider : OAuthBearerAuthenticationProvider{ readonly string _name; public QueryStringOAuthBearerProvider(string name) { _name = name; } public override Task RequestToken(OAuthRequestTokenContext context) { var value = context.Request.Query.Get(_name); if (!string.IsNullOrEmpty(value)) { context.Token = value; } return Task.FromResult<object>(null); }}
測試效果:
或者直接簡單粗暴的方式(不推薦),增加請求攔截,添加Application_BeginRequest
代碼如下:
protected void Application_BeginRequest(object sender, EventArgs e){ //從url中擷取token的另外一種解決方式 if (ReferenceEquals(null, HttpContext.Current.Request.Headers["Authorization"])) { var token = HttpContext.Current.Request.Params["access_token"]; if (!String.IsNullOrEmpty(token)) { HttpContext.Current.Request.Headers.Add("Authorization", "Bearer " + token); } }}
項目源碼:https://github.com/yuezhongxin/OAuth2.Demo/
參考資料:
- How can I validate my custom Oauth2 access token in server-side
- ASP.NET Web Api: How to pass an access token (oAuth 2.0) using URL parameter?
ASP.NET WebApi OWIN 實現 OAuth 2.0(自訂擷取 Token)