c# - 身份验证角色不起作用.net core mvc
问题描述
大家,我在我的应用程序中使用身份验证在.net core MVC 中使用身份一切正常,即使我检查 User.IsInRole("Admin") 工作完美我尝试使用的是检查控制器中的授权,但它没有即使用户没有权限也可以打开页面我尝试使用 jwt 的警察但没有意义
这是我的创业
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DotnetCore")));
// inject user Identity to use it in case without email vervication
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
services.AddAuthentication("CookieAuthentication")
.AddCookie("CookieAuthentication", config =>
{
config.Cookie.Name = "UserLoginCookie"; // Name of cookie
config.LoginPath = "/Home/Index"; // Path for the redirect to user login page
config.AccessDeniedPath = "/Home/AccessDenied";
});
services.AddAuthorization(config =>
{
config.AddPolicy("IsAdmin", policyBuilder =>
{
policyBuilder.UserRequireCustomClaim(ClaimTypes.Role);
});
});
// services.AddOptions();
//In-Memory
services.AddDistributedMemoryCache();
services.AddSession(options => {
options.IdleTimeout = TimeSpan.FromDays(1);
});
services.Configure<EmailSettings>(Configuration.GetSection("EmailSettings"));
// add lang
services.AddLocalization(options => options.ResourcesPath = "Resources");
// add lang
services.AddMvc()
.AddViewLocalization(option => { option.ResourcesPath = "Resources"; })
.AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
.AddDataAnnotationsLocalization();
services.Configure<RequestLocalizationOptions>(opts =>
{
var supportedCultures = new List<CultureInfo>
{
new CultureInfo("en"),
new CultureInfo("fr"),
};
opts.DefaultRequestCulture = new RequestCulture("en");
opts.SupportedCultures = supportedCultures;
opts.SupportedUICultures = supportedCultures;
});
//Password Strength Setting
services.Configure<IdentityOptions>(options =>
{
// Password settings
options.Password.RequireDigit = true;
options.Password.RequireNonAlphanumeric = false;
options.Password.RequireUppercase = false;
options.Password.RequireLowercase = false;
// Lockout settings
options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(30);
options.Lockout.MaxFailedAccessAttempts = 5;
options.Lockout.AllowedForNewUsers = true;
// User settings
options.User.RequireUniqueEmail = true;
});
//JWT Token for User Authentication
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = Configuration["Jwt:Issuer"],
ValidAudience = Configuration["Jwt:Audience"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))
};
});
// Add application services.
services.AddTransient<IEmailSender, EmailSender>();
services.AddScoped<IAuthorizationHandler, PoliciesAuthorizationHandler>();
services.AddScoped<IAuthorizationHandler, RolesAuthorizationHandler>();
services.AddControllersWithViews();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
var options = app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>();
app.UseRequestLocalization(options.Value);
app.UseSession();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
// who are you?
app.UseAuthentication();
// are you allowed?
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
我的登录代码是
var result = await _signInManager.PasswordSignInAsync(model.Username, model.Password, model.RememberMe, lockoutOnFailure: true);
if (result.Succeeded)
{
_logger.LogInformation("User logged in.");
//added new part of jwt
//Save token in session object
var tokenvalue = GenerateJSONWebToken(model);
HttpContext.Session.SetString(tokenvalue, "tokencode");
// End of Jwt
return RedirectToAction("Index", "DashBoard");
}
if (result.IsLockedOut)
{
_logger.LogWarning("User account locked out.");
return RedirectToAction(nameof(Lockout));
}
else
{
ModelState.AddModelError(string.Empty, "Invalid login attempt.");
return View(model);
}
}
ModelState.AddModelError(string.Empty, "Invalid login attempt.");
return View(model);
在chtml页面中,它完美无缺
@if (SignInManager.IsSignedIn(User)) {
if (User.IsInRole("Admin"))
{
// do something
}
}
我尝试使用警察或角色检查授权,但没有办法
[Authorize(Policy = "IsAdmin")]
[Authorize(UserRoles.AdminEndUser)]
public IActionResult Index()
{
return View();
}
但它不起作用我使用.net core 3.1,并且我还为 AuthorizationPolicyBuilder 添加了 3 个类助手来检查所需的策略和角色类型
解决方案
您无需创建保单即可检查Role
索赔。
您可以Authorize
像这样使用属性:
[Authorize(Roles = "Admin")]