4

我不确定我是否在这里遗漏了什么。即使用户具有某些角色,默认User.IsInRole()情况下也不起作用。

我没有自己的角色存储实现。我假设默认的应该可以工作。Startup.cs为了让角色发挥作用,我需要做些什么特别的事情吗?我正在使用 mvc 6 beta 2 默认模板。

4

2 回答 2

3

如果我添加这样的角色,User.IsInRole()则不起作用:

await UserManager.AddToRoleAsync(user, "Admin");

但如果我这样做,它确实有效:

await UserManager.AddClaimAsync(user, claim: new Claim(ClaimTypes.Role.ToString(), "Admin"));

于 2015-02-06T08:13:40.680 回答
0

看起来您正在使用带有最新 ASP.NET 5 内容的 Asp.NET Identity。我正在使用相同的(当前使用 RC1)。我有一个类似的问题,经过一番挖掘,我找到了使用SignInManager'sRefreshSignInAsync()方法的解决方案。

请注意,为了获得一个实例,UserManagerSignInManager使用依赖注入,所以我的控制器的构造函数如下所示:

public MyController(
    UserManager<ApplicationUser> userManager,
    SignInManager<ApplicationUser> signInManager)
{
    _userManager = userManager;
    _signInManager = signInManager;
}

我的要求是,如果经过身份验证的用户访问了特定的控制器方法,那么如果该用户还没有该角色,则该角色将被添加到该用户,并且需要立即生效。(随后对控制器和视图的调用User.IsInRole("TheRole")需要返回 true,而无需用户注销并重新登录)。

这是动作:

    [AllowAnonymous]
    public async Task<IActionResult> CreateProfile()
    {
        if (User == null || User.Identity == null || !User.Identity.IsAuthenticated)
        {
            return RedirectToAction("RegisterOrSignIn", "Account");
        }
        else
        {
            if (!User.IsInRole("TheRole"))
            {
                ApplicationUser applicationUser =
                    await _userManager.FindByIdAsync(User.GetUserId());
                await _userManager.AddToRoleAsync(applicationUser, "TheRole");
                await _signInManager.RefreshSignInAsync(applicationUser);
            }
            return RedirectToAction("Index");
        }
    }

注意你需要

using System.Security.Claims;

对于GetUserId()扩展方法。

所以我学到的最重要的事情是使用UserManager'sAddToRoleAsyncSignInManager's RefreshSignInAsync。第一个向 AspNetUserRoles 表添加一行。第二个刷新cookie,浏览器的下一个请求将显示用户在角色中。

顺便说一句,我添加了一个名为EnsureRoles()Startup.cs 的方法。我在调用app.UseIdentity()in之后立即调用它Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)。所以,这里有一个片段Configure()

    ...

    // Add cookie-based authentication to the request pipeline.
    app.UseIdentity();

#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
    // Ensure roles are in DB - OK not to await this for now
    EnsureRoles(app, loggerFactory);
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed

    ...

这是EnsureRoles()

private async Task EnsureRoles(IApplicationBuilder app, ILoggerFactory loggerFactory)
{
    ILogger logger = loggerFactory.CreateLogger<Startup>();
    RoleManager<IdentityRole> roleManager = app.ApplicationServices.GetService<RoleManager<IdentityRole>>();

    string[] roleNames = { "TheRole", "AnotherRole" };

    foreach (string roleName in roleNames)
    {
        bool roleExists = await roleManager.RoleExistsAsync(roleName);
        if (!roleExists)
        {
            logger.LogInformation(String.Format("!roleExists for roleName {0}", roleName));
            IdentityRole identityRole = new IdentityRole(roleName);
            IdentityResult identityResult = await roleManager.CreateAsync(identityRole);
            if (!identityResult.Succeeded)
            {
                logger.LogCritical(
                    String.Format(
                        "!identityResult.Succeeded after 
                         roleManager.CreateAsync(identityRole) for 
                         identityRole with roleName {0}",
                        roleName));
                foreach (var error in identityResult.Errors)
                {
                    logger.LogCritical(
                        String.Format(
                            "identityResult.Error.Description: {0}", 
                            error.Description));
                    logger.LogCritical(
                        String.Format(
                            "identityResult.Error.Code: {0}", 
                         error.Code));
                }
            }
        }
    }
}
于 2015-12-16T01:19:40.880 回答