如何在IdentityServer4中进行多步登录?

2023-11-24

我们使用 IdentityServer3、隐式授权并且登录由多个屏幕组成。在 IdentityServer3 中,内置了对此类多步骤登录工作流程的支持(例如接受 EULA、双因素登录等),该功能称为“部分登录“甚至还有一个例子:https://github.com/IdentityServer/IdentityServer3.Samples/tree/master/source/CustomUserService/CustomUserService

我们最近升级到了 AspNetCore 和 IdentityServer4,想知道如何实现同样的目标?也就是说,在第一步中检查用户名和密码,如果正确,则将其安全存储(例如在加密的 cookie 中)以供下一步使用。


我们的解决方案是复制 IdentityServer3 的部分登录:使用自定义 cookie 在步骤之间保留数据。

首先,我们需要注册自定义 cookie 身份验证(在 Startup.Configure 中)

app.UseCookieAuthentication(new CookieAuthenticationOptions
{
    AuthenticationScheme = "my-partial",
    AutomaticAuthenticate = false,
    AutomaticChallenge = false
});
  1. 登录工作流程的第一步/入口点应映射到GET /account/login(从 IdentityServer4 开始1.0.0-rc2).

  2. 第二步,发送并验证凭据后,我们将用户名(以及最终的任何其他数据)保存到 cookie 中。

Code:

var claims = new []
{
    new Claim("my-user", username),
    new Claim("some-attribute", someAttribute)
};

await HttpContext.Authentication
    .SignInAsync("my-partial", new ClaimsPrincipal(new ClaimsIdentity(claims)));

重要的: 避免使用POST /account/login作为第二步。因为无论您的结果如何,IdentityServer 的中间件都会将您重定向回授权端点(从 RC2 开始)。只需选择任何其他路径即可。

  1. At your last step, key parts
    • 我们从 cookie 中读取持久化数据
    • 删除部分cookie
    • 登录“真实”用户
    • 重定向到 returnUrl (这已作为查询参数添加到第一步。不要忘记发送它)

In code

var partialUser = await HttpContext.Authentication.AuthenticateAsync("my-partial");
var username = partialUser?.Claims.FirstOrDefault(c => c.Type == "dr-user")?.Value;

var claims = new [] { /* Your custom claims */};

await HttpContext.Authentication
    .SignOutAsync("my-partial");

await HttpContext.Authentication
    .SignInAsync(username, username, claims);

return Redirect(returnUrl);

此外,您可能想要验证输入,例如返回第一步,如果没有部分 cookie 等。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在IdentityServer4中进行多步登录? 的相关文章

随机推荐