我在startup.cs中配置了auth策略
services.AddAuthorization(auth =>
{
auth.AddPolicy("Bearer", policy => policy
.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
.RequireAuthenticatedUser().Build());
});
我在api控制器的属性中使用它:
[Authorize("Bearer")]
当我在VS代码中运行调试器时,我得到一个异常:
fail: Microsoft.AspNetCore.Server.Kestrel[13]
Connection id "0HL14EICAK26S": An unhandled exception was thrown by the application.
System.InvalidOperationException: The AuthorizationPolicy named: 'Bearer' was not found.
at Microsoft.AspNetCore.Authorization.AuthorizationPolicy.<CombineAsync>d__9.MoveNext()
当我通过dotnet run
运行程序时,我没有得到此异常,并且能够获取授权属性。
为什么会这样?
答案 0 :(得分:0)
清理,修复并重建项目......它再次神奇地工作......
答案 1 :(得分:0)
我需要添加以下内容,以使项目中的所有内容都能正常工作。这是Startup.cs
//Authentication
services.AddAuthentication()
.AddScheme<AuthOptions1, AuthenticationHandler1>("Scheme1", opt => { })
.AddScheme<AuthOptions2, AuthenticationHandler2>("Scheme2", opt => { });
//Authorization
services.AddAuthorization(opt =>
{
opt.AddPolicy("Policy1", policy =>
{
policy.AddAuthenticationSchemes("Scheme1");
policy.RequireAuthenticatedUser();
});
opt.AddPolicy("Policy2", policy =>
{
policy.AddAuthenticationSchemes("Scheme2");
policy.RequireAuthenticatedUser();
});
});
然后在我的控制器中添加以下内容:
[Authorize("Policy1")]