相关疑难解决方法(0)

在Web Api 2中授予刷新令牌时更新角色

我已经在Asp.Net Web Api 2中开发了一个认证机制,它具有授予刷新令牌的功能,基于Taiseer博客上的教程.

这是我的问题.假设以下情形:用户使用密码登录并获取刷新令牌和访问令牌.访问令牌实际上包括他所处的角色(因此他在应用程序中的权限).同时系统管理员将更改此人的角色,因此一旦他的访问令牌到期并且他想使用刷新令牌获取新的访问令牌,他的新访问令牌必须包括新更新的角色.

在我的"RefreshTokenProvider"类中,我使用"GrantResourceOwnerCredentials"方法中的以下代码从数据库中获取用户角色并将其添加到声明中:

var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));
        var y = roleManager.Roles.ToList();

        var id = new ClaimsIdentity(context.Options.AuthenticationType);
        id.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
        id.AddClaim(new Claim("sub", context.UserName));

        var roles2 = UserRoleManagerProvider.RoleManager().Roles.ToList();

        foreach (IdentityRole i in roles2)
        {
            if (roleIds.Contains(i.Id))
                id.AddClaim(new Claim(ClaimTypes.Role, i.Name));
        }
Run Code Online (Sandbox Code Playgroud)

这件作品很好(即使我相信应该有更好的方法吗?!)

但是,无法正常工作的部分是在"GrantRefreshToken"方法中,我们需要更新角色以便在新的访问令牌中反映它们:

var newId = new ClaimsIdentity(context.Ticket.Identity);

        // *** Add shit here....

        var userId = context.Ticket.Properties.Dictionary["userId"];
        IdentityUser user = UserRoleManagerProvider.UserManager().FindById(userId);

        foreach (Claim c in newId.Claims)
        {
            if (c.Type == ClaimTypes.Role) newId.RemoveClaim(c);
        }

        if …
Run Code Online (Sandbox Code Playgroud)

authentication oauth access-token asp.net-web-api2 asp.net-identity-2

6
推荐指数
1
解决办法
1714
查看次数