代码之家  ›  专栏  ›  技术社区  ›  Diego Venâncio

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

  •  0
  • Diego Venâncio  · 技术社区  · 7 年前

    创建一个项目和工作良好,登录,注册等,但授权不与角色。创建和设置角色:

    但尝试访问时总是返回拒绝访问:

    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.
    

    enter image description here

    enter image description here

    AspNetUserRoles表

    enter image description here

    个人账户登录 .NET核心2.1

    更新时间:

    [异名] 公共类LoginModel:PageModel 专用只读SignInManager\u SignInManager; 专用只读ILogger\u 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 回复  |  直到 7 年前
        1
  •  2
  •   Kosala W    7 年前

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

    推荐文章