【问题标题】:ASP NET MVC Core 2 Roles without database没有数据库的 ASP NET MVC Core 2 角色
【发布时间】:2017-11-20 15:55:26
【问题描述】:

我正在使用 Active Directory 来管理我的用户和他们各自的角色,这两个都被正确地恢复了。

然后我尝试通过ClaimsIdentity.AddClaim(new Claim(ClaimsType.Role, user.Role)); 分配角色,在调试时我可以看到角色已分配并且我没有收到任何错误。

在我的家庭控制器中,我在 About 的 IActionResult 上添加了 [Authorize(Roles = "Admin")],但是当我导航到 About 页面时,我被退回到登录页面。

用户被授权,因为我把[Authorize]放在了Contact上,登录后可以访问这个页面。

我错过了什么阻止正在使用的角色数据属性?

帐户控制器登录代码:

[AllowAnonymous]
    [HttpPost]
    public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null)
    {
        ViewData["ReturnUrl"] = returnUrl;

        if (ModelState.IsValid)
        {
            var usr = await AuthorisationCore.AuthenticateUser(model.Username, model.Password);

            if(usr.IsAuthenticated)
            {
                // setting up claims identity
                var claims = new List<Claim>
                {
                    new Claim(ClaimTypes.Name, usr.Username),
                };
                // adding role to the claim
                var identity = new ClaimsIdentity(claims, "cookie");
                identity.AddClaim(new Claim(ClaimTypes.Role, usr.Role));
                // new claim principal with the identity of the user input
                var principal = new ClaimsPrincipal(identity);
            await HttpContext.SignInAsync("SecurityCookie", principal, new AuthenticationProperties
            {
                IsPersistent = true,
                ExpiresUtc = DateTime.UtcNow.AddHours(1)
            });

            if (Url.IsLocalUrl(returnUrl))
            {
                return Redirect(returnUrl);
            }
            else
            {
                return RedirectToAction("Index", "Home");
            }
        }
    }
    return View();
}

启动代码:

public void ConfigureServices(IServiceCollection services)
{
    // data attributes like [AllowAnonymous]
    services.AddAuthorization();
    // allows for use of cookies and to add options to them
    services
        .AddAuthentication("SecurityCookie")
        .AddCookie("SecurityCookie", cfg =>
        {
            cfg.SlidingExpiration = true;
            cfg.LoginPath = "/Account/Login";
            cfg.AccessDeniedPath = "/Account/Login";
        });

    services.AddMvc();
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        app.UseBrowserLink();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
    }

    app.UseStaticFiles();

    app.UseAuthentication();

    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });
}

【问题讨论】:

  • 尝试从控制器中删除 [Authorize(Roles = "Admin")] 并检查代码中 ClaimsPrincipal 上的实际声明,看看是否有显着差异。
  • @serpent5 好的,谢谢你的建议,有什么需要特别注意的吗?
  • 我正在寻找声明本身的名称 - 您可能在声明转换方面遇到问题,因此 Authorize 属性触发的处理可能会比较两种不同的声明类型,例如.
  • @serpent5 谢谢,看了一下,它在 ClaimsPrincipal 中显示了正确的信息适当地。使用火狐
  • 在您的联系操作中,尝试添加User.Identity 并在调试模式下检查声明和角色

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


【解决方案1】:

你必须在启动Configure函数中同时使用app.UseAuthorization();app.UseAuthentication();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-28
    • 1970-01-01
    • 1970-01-01
    • 2010-11-21
    • 2021-10-10
    • 1970-01-01
    • 1970-01-01
    • 2018-11-17
    相关资源
    最近更新 更多