我从 beta5 迁移到 beta7 ASP.NET vNext,当我尝试使用无效的 JWT token 或根本没有 token 访问 protected API Controller 时,出现以下错误:
InvalidOperationException: The following authentication scheme was not accepted: Microsoft.AspNet.Http.Authentication.Internal.DefaultAuthenticationManager.d__10.MoveNext()
如果我尝试使用有效 token 访问 protected Controller ,我可以成功获得响应。
这是我 protected Controller :
[Authorize]
[Route("api/protected")]
public class ProtectedController : Controller
{
[Route("")]
public IEnumerable<object> Get()
{
var identity = User.Identity as ClaimsIdentity;
return identity.Claims.Select(c => new
{
Type = c.Type,
Value = c.Value
});
}
}
这是我的启动类(class):
public class Startup
{
public Startup(IHostingEnvironment env)
{
}
public static IConfiguration Configuration { get; set; }
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
}
// Configure is called after ConfigureServices is called.
public void Configure(IApplicationBuilder app, IApplicationEnvironment env)
{
ConfigureOAuthTokenConsumption(app);
app.UseMiddleware<StaticFileMiddleware>(new StaticFileOptions());
app.UseErrorPage();
app.UseMvc();
}
private void ConfigureOAuthTokenConsumption(IApplicationBuilder app)
{
// Api controllers with an [Authorize] attribute will be validated with JWT
app.UseOwin(addToPipeline =>
{
addToPipeline(next =>
{
var appBuilder = new AppBuilder();
appBuilder.Properties["builder.DefaultApp"] = next;
var issuer = Settings.Issuer;
var audience = Settings.Audience;
var secret = TextEncodings.Base64Url.Decode(Settings.Secret);
appBuilder.UseJwtBearerAuthentication(
new JwtBearerAuthenticationOptions
{
AuthenticationMode = AuthenticationMode.Active,
AllowedAudiences = new[] { audience },
IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
{
new SymmetricKeyIssuerSecurityTokenProvider(issuer, secret)
},
});
return appBuilder.Build<AppFunc>();
});
});
}
}
当我使用 beta5 时,一切正常。当我请求没有有效 token 的 protected Controller 时,我收到 401 响应,这是正确的行为。 我是否需要更改 ASP.NET vNext beta7 中的 JWT token 消耗配置?
最佳答案
我测试了代码,我发现 JWT token 可以正常工作,无需
[授权]
属性。因此,在 Controller 级别,用户已通过身份验证并且声明已存在。
还有一个与 CORS 设置相关的问题,因为通过 Postman 调用该站点工作正常,但是当我从不同的域访问它时,我有
The following authentication scheme was not accepted:
即使我传递有效 token 也会出错。 与 AuthorizationFilterAttribute 的情况相同 - 用户始终在过滤器中未经过身份验证,但在操作中正常。
到目前为止,我发现的唯一解决方法是添加 ActionFilterAttribute
并在操作执行之前检查权限
public override void OnActionExecuting(ActionExecutingContext context)
{
var principal = context.HttpContext.User.Identity as ClaimsIdentity;
if (!principal.IsAuthenticated)
{
context.Result = new HttpUnauthorizedResult();
}
base.OnActionExecuting(context);
}
此处用户已通过身份验证(如果 JWT 存在且有效),我们没有异常(exception),可以拒绝请求。
关于visual-studio-2015 - 从 ASP.NET vNext beta5 迁移到 beta7 后,JWT 承载 token 身份验证错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32649638/