我正在使用 isentittyserver4 并且我授权了我的 Controller 或操作。
[Authorize(Roles ="app.admin")]
[Route("products")]
public class ProductsController : Controller
{
}
我的 token 包含角色。我可以访问 User
对象属性中的角色。
- User.IsInRole("app.admin");//错误
- User.IsInRole("app.viewer");//真
但是,如果我使用不包含 app.admin
但包含 app.viewer
的 token 发送请求
但是请求响应403禁止。但应该是401未经授权。
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
.AddIdentityServerAuthentication(options =>
{
options.Authority = Configuration.GetValue<string>("Authority");
options.ApiName = Configuration.GetValue<string>("ApiName");
options.RequireHttpsMetadata = false;
});
services.AddMvc();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseAuthentication();
app.UseMvc();
}
}
最佳答案
应该是 403,或者至少是 401 以外的任何值。
原因如下。
假设管道返回 401。处理程序会将请求视为未经身份验证,并触发 SSO 流程。但是,用户已经在身份提供商端进行了身份验证。然后,身份提供者将静默返回相同/新的 token ,并且流程将返回到应用程序。根据实际的返回地址,会发生以下两种情况之一:
返回地址始终是应用程序的主页 - 用户会注意到他们被重定向到主页,但他们认为自己已经经过身份验证,这种情况不应该发生。您将收到有关应用中可能存在错误的报告。
返回地址与触发 SSO 流程的地址完全相同。但我们已经讨论过如果返回 401,它会返回到身份提供者。然后,浏览器陷入 IdP 和您的应用之间的重定向无限循环。您将收到严重错误的报告。
如果授权返回403而不是401,您可以在应用程序端的管道末端捕获它(我相信一个简单的操作过滤器应该可以完成假设您检查状态的工作在 OnActionExecuted
中)并以适当的方式处理,例如返回由于用户缺乏所需权限而无法显示所请求资源的原因的信息。
关于c# - IdentityServer4授权返回403禁止而不是401,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49552156/