有谁知道使用 Firebase Auth 时
HttpContext.User
在哪里设置?
我正在使用:ASP.NET Core 5.0、FirebaseAdmin 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));
}
编辑:我从客户端注册新用户、登录、注销等。所以也许如果我从后端做它会起作用。但这将是一个相当大的变化,因此理想情况下希望避免这种情况。
它似乎是由随请求发送的 JWT 访问令牌自动处理的。用户拥有与其帐户关联的访问令牌,如果您随请求发送该访问令牌,则
HttpContext.User
会自动填充正确的数据。我一定是发送了旧的 JWT。