相关文章: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?
原文地址:https://www.cnblogs.com/xishuai/p/9130770.html
时间: 2024-11-29 11:17:39