1. 程式人生 > >ASP.NET WebApi OWIN 實現 OAuth 2.0(自定義獲取 Token)

ASP.NET WebApi OWIN 實現 OAuth 2.0(自定義獲取 Token)

href timespan 獲取 edi prot cep b- med 2-0

相關文章:ASP.NET WebApi OWIN 實現 OAuth 2.0

之前的項目實現,Token 放在請求頭的 Headers 裏面,類似於這樣:

Accept: application/json
Content-Type: application/json
Authorization: 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)