Authorize(Roles =“ Admin”)始终返回拒绝访问

时间:2019-08-14 00:22:54

标签: c# asp.net asp.net-mvc asp.net-identity

我花了很多时间看似简单但找不到解决方案的东西。

创建一个项目并正常工作,登录,注册等。但是授权不适用于角色。创建和设置角色:

但是尝试访问时始终返回“拒绝访问”:

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?}");
    });
}

在调试窗口中显示以下消息:

...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表

enter image description here

AspNetUsers表

enter image description here

AspNetUserRoles表

enter image description here

MVC-脚手架项目 个人账户登录 .NET Core 2.1 VS 2017

已更新:

登录类-自动生成

[AllowAnonymous] 公共类LoginModel:PageModel {     私有只读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();
}

}

1 个答案:

答案 0 :(得分:1)

我认为您的问题与未配置策略有关。 在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