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

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

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

Accept: application/json
Content-Type: application/json
Authorization: Bearer pADKsjwMv927u...

雖然這是最標準的實現方式,但有時候咱們會面對一些業務變化,好比 Token 要求放在 URL 或是 Post Body 裏面,好比這樣:github

https://www.domain.com/api/MyController?access_token=pADKsjwMv927u...

ASP.NET WebApi OWIN 實現上面的需求,有不少種方式,這邊只記錄兩種。web

第一種方式,重寫OAuthBearerAuthenticationOptions,將Startup.Auth.cs改造以下:json

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);
    }
}

測試效果:api

或者直接簡單粗暴的方式(不推薦),增長請求攔截,添加Application_BeginRequest代碼以下:app

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/dom

參考資料:ide

相關文章
相關標籤/搜索