[英]authentication roles doesn't work .net core mvc
大家,我已經在我的應用程序中使用身份驗證在 .net 核心 MVC 中使用身份驗證一切正常,即使我檢查 User.IsInRole("Admin") 工作完美我嘗試使用的是檢查 controller 中的授權,但它不起作用即使用戶沒有權限打開頁面我也嘗試使用 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 核心 3.1 並且我還為 AuthorizationPolicyBuilder 添加了 3 個類助手來檢查所需的策略和角色類型
您無需創建策略即可檢查Role
聲明。
您可以像這樣使用Authorize
屬性:
[Authorize(Roles = "Admin")]
您也可以像這樣將它用於多個角色
[Authorize(Roles = "Admin,CustomerServices,etc")]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.