ASP.NET授权筛选器拒绝用户在指定角色中的访问权限

时间:2018-03-28 16:35:22

标签: asp.net-core asp.net-core-mvc asp.net-core-2.0 asp.net-authorization

在我的ASP.NET Core 2.0应用程序中,我遇到了一个问题,管理员登录用户无法访问控制器我在[Authorize(Policy="AdminAlone")]使用了授权过滤器。

我确认用户处于“管理员”角色并在startup.cs中添加了该策略,但在我尝试访问控制器时,它会重定向到AccessDenied视图。

我在link上看到了类似的问题,但解决方案并没有帮助我

MVC客户端中的启动类 - 配置服务

services.AddMvc();
services.AddSession();

JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();

services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddAuthorization(options =>
{
    options.AddPolicy("AdminAlone", policy => policy.RequireRole("Administrators"));
});

services.AddAuthentication(options =>
{
    options.DefaultScheme = "Cookies";
    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultForbidScheme = JwtBearerDefaults.AuthenticationScheme;

})
.AddCookie("Cookies")
.AddOpenIdConnect("Bearer", options =>
{
    options.SignInScheme = "Cookies";

    options.Authority = "http://localhost:5000";
    options.RequireHttpsMetadata = false;

    options.ClientId = "mvcWeb";
    options.ClientSecret = "spring12345";
    options.ResponseType = OidcConstants.ResponseTypes.CodeIdToken;

    options.SaveTokens = true;
    options.GetClaimsFromUserInfoEndpoint = true;

    options.Scope.Add("NuB.HospitalSearch");
    options.Scope.Add("offline_access");
});

Web API配置服务

var jwtSecurityTokenHandler = new JwtSecurityTokenHandler
{
    InboundClaimTypeMap = new Dictionary<string, string>()
};

services
.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(option =>
{
   option.Audience = "NuB.HospitalSearch";
   option.Authority = "http://localhost:5000";
   option.RequireHttpsMetadata = false;
   option.SecurityTokenValidators.Clear();
   option.SecurityTokenValidators.Add(jwtSecurityTokenHandler);
   option.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
   {
       ValidateAudience = true,
       ValidAudience = "NuB.HospitalSearch",
       ValidateIssuer = true
   };
});

1 个答案:

答案 0 :(得分:0)

您可以尝试以下方法。在AddOpenIdConnect配置中添加

options.TokenValidationParameters = new TokenValidationParameters {
   NameClaimType = JwtClaimTypes.Name,
   RoleClaimType = JwtClaimTypes.Role
};

实际上,此属性定义验证令牌所需的类型和定义。有关更详细的说明,请参阅 Dominick Baier 中的this帖子。