HttpContext.SignInAsync 之后获取当前 HttpRequest 中的 AuthenticationProperties

2024-03-21

我正在使用 ASP.net Core MVC。在登录过程中,在 POST 控制器操作中,我将 HttpContext.SignInAsync 与包含 JWT 访问令牌的 AuthenticationProperties 结合使用。在同一个 HttpRequest 中,我无法重新获取这些属性来获取创建的访问令牌。

...
var claimsPrincipal = CreateClaimsPrincipal("userName");

var accessToken = new AuthenticationToken()
{
    Name = OpenIdConnectParameterNames.AccessToken,
    Value = TOKEN_VALUE
};
AuthenticationToken[] tokens = { accessToken };

var authenticationProperties = new AuthenticationProperties();
authenticationProperties.StoreTokens(tokens);
authenticationProperties.IsPersistent = true;

// Here we sign in the user
await HttpContext.SignInAsync(claimsPrincipal, authenticationProperties);

// Afterwards, we cannot access the access token either from
var tokenValueFromGetTokenAsync = HttpContext.GetTokenAsync(OpenIdConnectParameterNames.AccessToken)
// Or with
var result = await HttpContext.AuthenticateAsync();
var tokenValueFromAuthenticateAsync = result.Properties.GetTokenValue(OpenIdConnectParameterNames.AccessToken);

有没有办法设置当前http请求的AuthenticationProperties? 我知道我可以设置 ClaimsPrincipal

HttpContext.user = claimsPrincipal

但是我可以用 AuthenticationProperties 做类似的事情吗?就像是

// I made that part up, would be cool though
HttpContext.Authentication.Properties = authenticationProperties

我将一个超级简单的代码示例上传到github:

GitHub 代码示例 https://github.com/CurlyFire/TestGetAuthenticationProperties.git

检查用 HttpPost 属性修饰的 SecurityController Login 方法。


For AuthenticationProperties,尝试通过以下方式保存它options.Events.OnSignedIn like

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(options =>
    {
        options.LoginPath = new PathString("/Security/Login");
        options.Events.OnSignedIn = context => {
            var httpContext = context.HttpContext;
            httpContext.Items["Properties"] = context.Properties;
            httpContext.Features.Set(context.Properties);
            return Task.CompletedTask;
        };
    });

然后通过检索

public async Task<IActionResult> Login(LoginModel model)
{
    if (ModelState.IsValid)
    {
        var claimsPrincipal = CreateClaimsPrincipal(model.Name);
        var authenticationProperties = CreateAuthenticationProperties();

        await HttpContext.SignInAsync(claimsPrincipal, authenticationProperties);

        HttpContext.User = claimsPrincipal;

        var properties1 = HttpContext.Features.Get<AuthenticationProperties>();
        var properties2 = HttpContext.Items["Properties"];           

        return RedirectToAction(nameof(HomeController.Index), nameof(HomeController));
    }
    else
    {
        return View(model);
    }
}

另一种选择是,您可以考虑添加一个新方法,用于检索属性,例如:

    public async Task<IActionResult> Login(LoginModel model)
    {
        if (ModelState.IsValid)
        {
            var claimsPrincipal = CreateClaimsPrincipal(model.Name);
            var authenticationProperties = CreateAuthenticationProperties();

            await HttpContext.SignInAsync(claimsPrincipal, authenticationProperties);

            return RedirectToAction(nameof(CheckProperties));
        }
        else
        {
            return View(model);
        }
    }

    public async Task<IActionResult> CheckProperties()
    {
        await FetchTokenAndVerify();
        return RedirectToAction(nameof(HomeController.Index), nameof(HomeController));
    }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

HttpContext.SignInAsync 之后获取当前 HttpRequest 中的 AuthenticationProperties 的相关文章

随机推荐