【发布时间】:2016-04-09 08:00:26
【问题描述】:
我在 asp.net 5 (RC1) 中有一个几乎可以工作的 OAuth2 实现。我的解决方案基于 Mark Hughes 在Token Based Authentication in ASP.NET 5 (vNext) 中给出的代码,非常棒。
我的问题是我的设置正在使用 CORS 请求,并且几乎每个请求之前都有一个 OPTIONS 请求。即使我只将 Authorize 属性应用于 GetAll 控制器操作/方法,如下所示,前面的 OPTIONS 请求也是授权的。
[Route("api/[controller]")]
public class TextController : Controller
{
[HttpGet]
[Authorize("Bearer", Roles = "admin")]
public IEnumerable<string> GetAll()
{
return _repository.GetAll;
}
...
}
startup.cs 中的授权服务设置如下:
services.AddAuthorization(auth =>
{
auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder()
.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
.RequireAuthenticatedUser().Build());
});
有什么方法可以改变授权中间件的行为以跳过对 OPTIONS 请求的授权?
注意:
我尝试创建自己的授权属性,但由于某种原因,IsAuthenticated 始终评估为 false,就好像在到达此代码时授权尚未发生:
public class BearerAuthorizationAttribute : Attribute, IAuthorizationFilter
{
private readonly string Role;
public BearerAuthorizationAttribute(string Role = null)
{
this.Role = Role;
}
[Authorize("Bearer")]
public void OnAuthorization(Microsoft.AspNet.Mvc.Filters.AuthorizationContext context)
{
string meth = context.HttpContext.Request.Method;
if (meth != "OPTIONS")
{
if (!context.HttpContext.User.Identity.IsAuthenticated)
{
context.Result = new ContentResult() { Content = "Unauthorized", StatusCode = 401 };
return;
}
if (Role != null && !context.HttpContext.User.IsInRole(Role))
{
context.Result = new ContentResult() { Content = "Unauthorized, role level insufficient", StatusCode = 401 };
return;
}
}
}
}
【问题讨论】:
标签: c# oauth-2.0 cors asp.net-core jwt