我花了很多时间在这个看起来很容易的事情上,但却找不到解决的办法。
创建一个项目和工作良好,登录,注册等,但授权不工作与角色。创建和设置角色:
但在尝试访问时总是返回拒绝访问:
public class _ConfigurationsController : Controller
{
[Authorize(Roles = "AdminApp")]
public IActionResult Index()
{
return View();
}
}
启动。。。
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?}");
});
}
在调试窗口中显示以下消息:
...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表
AspNetUsers表
AspNetUserRoles表
MVC-Scaffolding项目个人帐户登录。NET Core 2.1 VS 2017
已更新:
登录类-自动生成
[AllowAnonymous]公共类LoginModel:PageModel{private readonly SignInManager_SignInManager;private readonly 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 configureReservices(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