首页 文章

承载令牌认证和密码更改

提问于
浏览
1

现在我正在学习Web API中的owin bearer token身份验证阶段 . 该代码使用基于令牌和cookie的身份验证实现 . 代码是

public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {
        try
        {

              using (UserManager<ApplicationUser> userManager = userManagerFactory())
                {

                    ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password);


                    if (user == null || user.IsDeleted)
                    {
                        context.SetError("invalid_grant", "The user name or password is incorrect.");
                        return;
                    }

                    ClaimsIdentity oAuthIdentity = await userManager.CreateIdentityAsync(user,
                        context.Options.AuthenticationType);
                    ClaimsIdentity cookiesIdentity = await userManager.CreateIdentityAsync(user,
                        CookieAuthenticationDefaults.AuthenticationType);

                    var roleName = await GetRoleName(user.Roles.First().RoleId);

                    AuthenticationProperties properties = CreateProperties(user.UserName, roleName);
                    AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
                    context.Validated(ticket);
                    context.Request.Context.Authentication.SignIn(cookiesIdentity);
                }

        }
        catch (Exception ex)
        {

            throw ex;
        }
    }

        public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            // Resource owner password credentials does not provide a client ID.
            if (context.ClientId == null)
            {
                context.Validated();
            }

            return Task.FromResult<object>(null);
        }

        public override Task ValidateClientRedirectUri(OAuthValidateClientRedirectUriContext context)
        {
            if (context.ClientId == _publicClientId)
            {
                Uri expectedRootUri = new Uri(context.Request.Uri, "/");

                if (expectedRootUri.AbsoluteUri == context.RedirectUri)
                {
                    context.Validated();
                }
            }

            return Task.FromResult<object>(null);
        }

该代码由同事实施,我有一些疑问 .

  • 令牌身份验证基于生成的令牌 . 我为我的用户生成了一个令牌,其角色是“管理员” . 现在我可以访问受限操作,因为用户具有“管理员”角色 . 但之后我将角色更改为同一个旧用户的“用户” . 现在使用相同的旧令牌,即使他现在不在“管理员”中,我也可以访问该资源 . 实际上我读了一些文章,这是用额外的自定义逻辑实现的 . 没关系

  • 现在我将用户密码更改为其他密码 . 现在,我可以使用相同的旧令牌访问资源 . 我认为这也不好,即使我也创造了短暂的代币 .

有人请指导逮捕这个或我错过了什么?当我使用“授权” Headers 调用操作时,实际调用哪种方法

1 回答

  • 0

    好吧,没有“直接”方式来撤销授予的访问权限或“注销” . 如果用户拥有令牌,则他可以访问受保护的服务器资源,直到令牌过期 . 间接通道是为数据库中授予用户的每个令牌存储token_id,并对每次调用进行数据库检查,这是我不推荐的 .

    因此,在某些情况下,最好将刷新令牌与访问令牌一起使用 . 因此,您发布短期访问令牌(15)分钟,并使用刷新令牌获取新的访问令牌 . 这里的好处是刷新令牌可以从后端系统中撤销,因此可以控制它们 .

    查看我的帖子,了解如何启用OAuth refresh tokens in ASP.NET Web API

相关问题