没有数据库的ASP NET MVC Core 2角色 [英] ASP NET MVC Core 2 Roles without database

查看:66
本文介绍了没有数据库的ASP NET MVC Core 2角色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Active Directory管理我的用户及其各自的角色,这两个角色都已正确带回.

I'm using Active Directory to manage my users and their respective roles, both of these are correctly brought back.

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

I am then trying to assign the roles through ClaimsIdentity.AddClaim(new Claim(ClaimsType.Role, user.Role)); when debugging I can see that the role is assigned and I don't get any errors.

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

In my home controller I've added [Authorize(Roles = "Admin")] on the IActionResult of About, but when I navigate to the About page I'm thrown back to the login.

该用户已获得授权,因为我在联系人上放置了[Authorize],并且登录后可以访问此页面.

The user is authorized, as I put [Authorize] on Contact and can access this page after login.

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

What have I missed that's stopping the roles data attribute being used?

帐户控制器登录代码:

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

推荐答案

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

You must use both app.UseAuthorization(); and app.UseAuthentication(); in the startup Configure function

这篇关于没有数据库的ASP NET MVC Core 2角色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆