Firebase - 验证 api 请求在 .net 5 中是否具有有效的 id 令牌

Ben*_*ins 3 c# firebase-authentication asp.net5 firebase-admin .net-5

我正在使用 flutter 应用程序中的 firebase auth,该应用程序从前端获取 jwt,如下所示:

accessToken = await user!.getIdToken(true);
Run Code Online (Sandbox Code Playgroud)

现在我希望我的 .net 5 AspNetCore 后端应用程序验证 id 令牌。

我将 firebase admin SDK 添加到我的 .net 应用程序中,如下所示:

startup.cs

FirebaseApp.Create();
Run Code Online (Sandbox Code Playgroud)

Firebase文档显示了如何验证 id 令牌:

FirebaseToken decodedToken = await FirebaseAuth.DefaultInstance
    .VerifyIdTokenAsync(idToken);
string uid = decodedToken.Uid;
Run Code Online (Sandbox Code Playgroud)

但是这段代码去哪里了呢?我不想为我的 AspNetCore 应用程序中的每个控制器端点手动执行此操作。这可以作为中间件在每个 api 请求上自动发生吗?

编辑:Eeek 我什至不认为 Firebase Admin 是我想要的。我只想验证使用 Firebase Auth for Flutter 在客户端上创建的 jwt id 令牌,以尽可能最 firebasey 的方式。它不适用于管理员,适用于普通用户。我以为 Firebase Admin 就是这样。我应该朝什么方向发展?我在网上找到了各种关于不同策略的文章,所以很困惑哪一个是正确的。这足够了吗?https://dominique-k.medium.com/using-firebase-jwt-tokens-in-asp-net-core-net-5-834c43d4aa00它看起来不是很火,而且似乎过于简化?我认为下面 Dharmaraj 的答案是最火爆的方式,但我不确定从哪里idToken获取值(如何从请求标头获取?否则它只是空)。

Ben*_*ins 6

我基本上遵循了非 Firebase 内容的SO 答案和 Firebase 内容的本教程,这一切都有效,我可以通过 ExtendedContext.userResolverService 和 id 访问用户、访问令牌、声明、一切令牌在我所有使用 的 Web 控制器端点中进行了验证[Authorize]

由于我的所有控制器中都有 id 令牌,因此我也可以从任何控制器手动调用它,但这不是必需的。

FirebaseToken decodedToken = await FirebaseAuth.DefaultInstance
    .VerifyIdTokenAsync(idToken);
string uid = decodedToken.Uid;
Run Code Online (Sandbox Code Playgroud)

userResolverService.cs:

using System.Security.Claims;
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()
    {
        return _context.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value;
    }

    public string GetEmails()
    {
        return _context.HttpContext.User.FindFirst("emails").Value;
    }
}
Run Code Online (Sandbox Code Playgroud)

扩展 DataContext(通过组合):

namespace Vepo.DataContext {
    public class ExtendedVepoContext
    {
        public VepoContext _context;
        public UserResolverService _userResolverService;

        public ExtendedVepoContext(VepoContext context, UserResolverService userService)
        {
            _context = context;
            _userResolverService = userService;
            _context._currentUserExternalId = _userResolverService.GetNameIdentifier();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

启动.cs:

public void ConfigureServices(IServiceCollection services)
        {
            ....

        services.AddHttpContextAccessor();

        services.AddTransient<UserResolverService>();

        services.AddTransient<ExtendedVepoContext>();

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

            services
                .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddJwtBearer(options =>
                {
                    options.Authority = "https://securetoken.google.com/my-firebase-app-id";
                    options.TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidateIssuer = true,
                        ValidIssuer = "https://securetoken.google.com/my-firebase-app-id",
                        ValidateAudience = true,
                        ValidAudience = "my-firebase-app-id",
                        ValidateLifetime = true
                    };
                });
Run Code Online (Sandbox Code Playgroud)

还有startup.cs:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env, VepoContext context, ISearchIndexService searchIndexService)
{ ....

    app.UseAuthentication();
    app.UseAuthorization();
Run Code Online (Sandbox Code Playgroud)

然后将 auth 添加到控制器端点中,如下所示:

[HttpPost]
[Authorize]
public async Task<ActionResult<GroceryItemGroceryStore>> PostGroceryItemGroceryStore(GroceryItemGroceryStore groceryItemGroceryStore)
{...
Run Code Online (Sandbox Code Playgroud)

您可以更进一步,在每次保存时与用户一起执行一些操作,例如添加元数据:

要保存并添加元数据的实体:

public interface IDomainEntity<TId>
{
    TId Id { get; set; }    
    DateTime SysStartTime { get; set; }
    DateTime SysEndTime { get; set; }
    string CreatedById { get; set; }
    User CreatedBy { get; set; }
    string UpdatedById { get; set; }
    User UpdatedBy { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我的数据上下文:

public class VepoContext : DbContext
{
    public VepoContext(DbContextOptions<VepoContext> options)
        : base(options)
    {
    }

        public DbSet<User> User { get; set; }

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

            AddCreatedByOrUpdatedBy(user);

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

        public override int SaveChanges()
        {
            var user = User.Single(x => x.Id == _currentUserExternalId);

            AddCreatedByOrUpdatedBy(user);

            return base.SaveChanges();
        }

        public void AddCreatedByOrUpdatedBy(User user)
        {
            foreach (var changedEntity in ChangeTracker.Entries())
            {
                if (changedEntity.Entity is IDomainEntity<int> entity)
                {
                    switch (changedEntity.State)
                    {
                        case EntityState.Added:
                            entity.CreatedBy = user;
                            entity.UpdatedBy = user;
                            break;
                        case EntityState.Modified:
                            Entry(entity).Reference(x => x.CreatedBy).IsModified = false;
                            entity.UpdatedBy = user;
                            break;
                    }
                }
            }
        }
Run Code Online (Sandbox Code Playgroud)