授权(角色 = "Admin")总是 return 访问被拒绝
Authorize(Roles = "Admin") always return ACCESS DENIED
我花了很多时间在这个看似简单但找不到解决方案的事情上。
创建项目并运行良好,登录、注册等。但授权不适用于角色。创建和设置角色:
但总是return尝试访问时拒绝访问:
public class _ConfigurationsController : Controller
{
[Authorize(Roles = "AdminApp")]
public IActionResult Index()
{
return View();
}
}
Startup.cs
...
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("MyConnection")));
services.AddDbContext<Scaffolding_AutoGer_Context>(options =>
options.UseSqlServer(Configuration.GetConnectionString("MyConnection")));
services.AddDefaultIdentity<IdentityUser>()
.AddRoles<IdentityRole>()
.AddRoleManager<RoleManager<IdentityRole>>()
.AddDefaultTokenProviders()
.AddEntityFrameworkStores<ApplicationDbContext>();
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider serviceProvider)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseAuthentication();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
在调试中 windows 显示此消息:
...Authorization.DefaultAuthorizationService:Information: Authorization failed.
...: Authorization failed for the request at filter 'Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter'.
...: Executing ForbidResult with authentication schemes ().
...Authentication.Cookies.CookieAuthenticationHandler:Information: AuthenticationScheme: Identity.Application was forbidden.
AspNetRoles Table
AspNetUsers Table
AspNetUserRoles Table
MVC - 脚手架项目
个人账户登录
.NET 核心 2.1
对比 2017
更新:
登录class - 自动生成
[允许匿名]
public class 登录模型:页面模型
{
私有只读 SignInManager _signInManager;
私人只读 ILogger _logger;
public LoginModel(SignInManager<IdentityUser> signInManager, ILogger<LoginModel> logger)
{
_signInManager = signInManager;
_logger = logger;
}
[BindProperty]
public InputModel Input { get; set; }
public IList<AuthenticationScheme> ExternalLogins { get; set; }
public string ReturnUrl { get; set; }
[TempData]
public string ErrorMessage { get; set; }
public class InputModel
{
[Required]
[EmailAddress]
public string Email { get; set; }
[Required]
[DataType(DataType.Password)]
public string Password { get; set; }
[Display(Name = "Memorizar?")]
public bool RememberMe { get; set; }
}
public async Task OnGetAsync(string returnUrl = null)
{
if (!string.IsNullOrEmpty(ErrorMessage))
{
ModelState.AddModelError(string.Empty, ErrorMessage);
}
returnUrl = returnUrl ?? Url.Content("~/");
// Clear the existing external cookie to ensure a clean login process
await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme);
ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
ReturnUrl = returnUrl;
}
public async Task<IActionResult> OnPostAsync(string returnUrl = null)
{
returnUrl = returnUrl ?? Url.Content("~/");
if (ModelState.IsValid)
{
// This doesn't count login failures towards account lockout
// To enable password failures to trigger account lockout, set lockoutOnFailure: true
var result = await _signInManager.PasswordSignInAsync(Input.Email, Input.Password, Input.RememberMe, lockoutOnFailure: true);
if (result.Succeeded)
{
_logger.LogInformation("Usuário logado .");
return LocalRedirect(returnUrl);
}
if (result.RequiresTwoFactor)
{
return RedirectToPage("./LoginWith2fa", new { ReturnUrl = returnUrl, RememberMe = Input.RememberMe });
}
if (result.IsLockedOut)
{
_logger.LogWarning("Conta bloqueada!");
return RedirectToPage("./Lockout");
}
else
{
ModelState.AddModelError(string.Empty, "Login inválido.");
return Page();
}
}
// If we got this far, something failed, redisplay form
return Page();
}
}
我认为您的问题与未配置策略有关。
在 public void ConfigureServices(IServiceCollection services)
中指定这些。
services.AddAuthorization(options =>
options.AddPolicy("AdminApp",
policy => policy.RequireClaim("Manager")));
更多信息请点击此处。 https://docs.microsoft.com/en-us/aspnet/core/security/authorization/claims?view=aspnetcore-2.2
我花了很多时间在这个看似简单但找不到解决方案的事情上。
创建项目并运行良好,登录、注册等。但授权不适用于角色。创建和设置角色:
但总是return尝试访问时拒绝访问:
public class _ConfigurationsController : Controller
{
[Authorize(Roles = "AdminApp")]
public IActionResult Index()
{
return View();
}
}
Startup.cs ...
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("MyConnection")));
services.AddDbContext<Scaffolding_AutoGer_Context>(options =>
options.UseSqlServer(Configuration.GetConnectionString("MyConnection")));
services.AddDefaultIdentity<IdentityUser>()
.AddRoles<IdentityRole>()
.AddRoleManager<RoleManager<IdentityRole>>()
.AddDefaultTokenProviders()
.AddEntityFrameworkStores<ApplicationDbContext>();
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider serviceProvider)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseAuthentication();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
在调试中 windows 显示此消息:
...Authorization.DefaultAuthorizationService:Information: Authorization failed.
...: Authorization failed for the request at filter 'Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter'.
...: Executing ForbidResult with authentication schemes ().
...Authentication.Cookies.CookieAuthenticationHandler:Information: AuthenticationScheme: Identity.Application was forbidden.
AspNetRoles Table
AspNetUsers Table
AspNetUserRoles Table
MVC - 脚手架项目 个人账户登录 .NET 核心 2.1 对比 2017
更新:
登录class - 自动生成
[允许匿名] public class 登录模型:页面模型 { 私有只读 SignInManager _signInManager; 私人只读 ILogger _logger;
public LoginModel(SignInManager<IdentityUser> signInManager, ILogger<LoginModel> logger)
{
_signInManager = signInManager;
_logger = logger;
}
[BindProperty]
public InputModel Input { get; set; }
public IList<AuthenticationScheme> ExternalLogins { get; set; }
public string ReturnUrl { get; set; }
[TempData]
public string ErrorMessage { get; set; }
public class InputModel
{
[Required]
[EmailAddress]
public string Email { get; set; }
[Required]
[DataType(DataType.Password)]
public string Password { get; set; }
[Display(Name = "Memorizar?")]
public bool RememberMe { get; set; }
}
public async Task OnGetAsync(string returnUrl = null)
{
if (!string.IsNullOrEmpty(ErrorMessage))
{
ModelState.AddModelError(string.Empty, ErrorMessage);
}
returnUrl = returnUrl ?? Url.Content("~/");
// Clear the existing external cookie to ensure a clean login process
await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme);
ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
ReturnUrl = returnUrl;
}
public async Task<IActionResult> OnPostAsync(string returnUrl = null)
{
returnUrl = returnUrl ?? Url.Content("~/");
if (ModelState.IsValid)
{
// This doesn't count login failures towards account lockout
// To enable password failures to trigger account lockout, set lockoutOnFailure: true
var result = await _signInManager.PasswordSignInAsync(Input.Email, Input.Password, Input.RememberMe, lockoutOnFailure: true);
if (result.Succeeded)
{
_logger.LogInformation("Usuário logado .");
return LocalRedirect(returnUrl);
}
if (result.RequiresTwoFactor)
{
return RedirectToPage("./LoginWith2fa", new { ReturnUrl = returnUrl, RememberMe = Input.RememberMe });
}
if (result.IsLockedOut)
{
_logger.LogWarning("Conta bloqueada!");
return RedirectToPage("./Lockout");
}
else
{
ModelState.AddModelError(string.Empty, "Login inválido.");
return Page();
}
}
// If we got this far, something failed, redisplay form
return Page();
}
}
我认为您的问题与未配置策略有关。
在 public void ConfigureServices(IServiceCollection services)
中指定这些。
services.AddAuthorization(options =>
options.AddPolicy("AdminApp",
policy => policy.RequireClaim("Manager")));
更多信息请点击此处。 https://docs.microsoft.com/en-us/aspnet/core/security/authorization/claims?view=aspnetcore-2.2