【问题标题】:ASP.NET Core Update HttpContext.UserASP.NET Core 更新 HttpContext.User
【发布时间】:2021-10-12 05:11:32
【问题描述】:

有谁知道使用 Firebase 身份验证时 HttpContext.User 在哪里设置?

我正在使用:Asp.NET Core 5.0FirebaseAdmin 2.2.0

在我的 startup.cs 我有这个:

FirebaseApp.Create(new AppOptions()
{
    Credential = GoogleCredential.FromFile("firebase_admin_sdk.json"),
});

var claims = new Dictionary<string, object>
{
    { ClaimTypes.Role, "User" }
};

我有这项服务,可以让我获取当前用户的详细信息:

using System.Security.Claims;
using System.Security.Principal;
using Microsoft.AspNetCore.Http;

public class UserResolverService
{
    public readonly IHttpContextAccessor _context;

    public UserResolverService(IHttpContextAccessor context)
    {
        _context = context;
    }

    public string GetGivenName()
    {
        return _context.HttpContext.User.FindFirst(ClaimTypes.GivenName).Value;
    }

    public string GetSurname()
    {
        return _context.HttpContext.User.FindFirst(ClaimTypes.Surname).Value;
    }

    public string GetNameIdentifier()
    {
        string nameIdentifier = _context.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value;
        return nameIdentifier;
    }

    public string GetEmails()
    {
        return _context.HttpContext.User.FindFirst("emails").Value;
    }
}

我就是这样使用它的:

public string _currentUserExternalId;

public override async Task<int> SaveChangesAsync(CancellationToken cancellationToken = default(CancellationToken))
{
    var user = await User.SingleOrDefaultAsync(x => x.Id == _currentUserExternalId);

    AddCreatedByOrUpdatedBy(user);

    return (await base.SaveChangesAsync(true, cancellationToken));
}

但是它让我知道了一个不再存在的老用户的详细信息,所以_currentUserExternalId 不是最新的。

这是HttpContext.User的值:

由于这是由 Firebase 神奇地设置的,我不确定在注册新用户后如何为当前用户更新它。有人知道吗?

我已找到此方法并将其添加到我的UserResolverService。我有一种感觉,这是手动破解,并且会有一种 Firebase 方式来执行此操作,因为它神奇地用旧用户填充了声明:

public void AddUpdateClaim(IPrincipal currentPrincipal, string key, string value)
{
    var identity = currentPrincipal.Identity as ClaimsIdentity;
    if (identity == null)
        return;

    // check for existing claim and remove it
    var existingClaim = identity.FindFirst(key);
    if (existingClaim != null)
        identity.RemoveClaim(existingClaim);

    // add new claim
    identity.AddClaim(new Claim(key, value));
}

编辑:我从 客户端 注册新用户、登录、退出等。所以也许如果我从后端做它会起作用。但这将是一个相当大的变化,因此最好避免这种情况。

【问题讨论】:

    标签: firebase asp.net-core firebase-authentication firebase-admin asp.net5


    【解决方案1】:

    它似乎由随请求发送的 JWT 访问令牌自动处理。用户有一个与其帐户关联的访问令牌,如果您随请求发送该访问令牌,则HttpContext.User 会自动填充正确的数据。我一定是在发送旧的 JWT。

    【讨论】: