相关文章: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