Asp 网络核心和 Firebase 身份验证

时间:2021-03-18 08:55:27

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

在我的 asp net core 5 (api) 中,我将 firebase 身份验证与此中间件集成:

public void ConfigureServices(IServiceCollection services)
{
   services
    .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.Authority = "https://securetoken.google.com/my-project-id";
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidIssuer = "https://securetoken.google.com/my-project-id",
            ValidateAudience = true,
            ValidAudience = "my-project-id",
            ValidateLifetime = true
        };
    });
  services.AddControllers();
}

我已按照本教程进行操作:https://blog.markvincze.com/secure-an-asp-net-core-api-with-firebase/

它有效:将 [Authorize] 添加到控制器,我需要传递不记名令牌。 现在,在控制器操作中,我需要获取经过身份验证的当前用户 ID 和电子邮件。

如何从 firebase(通过 firebase 进行身份验证的用户)获取用户 ID 和用户电子邮件?

1 个答案:

答案 0 :(得分:0)

据我所知,在用户成功登录后,asp.net 核心会将令牌中的声明写入用户声明属性中。然后你可以从控制器或其他类中的 httpcontextaccessor 中读取它。

更多细节,您可以参考以下代码:

在 Startup ConfigureServices 方法中添加以下代码

        services.AddHttpContextAccessor(); 

在控制器中添加以下代码以获取声明:

    private readonly ILogger<HomeController> _logger;
    private readonly IHttpContextAccessor httpContextAccessor;

    public HomeController(ILogger<HomeController> logger, IHttpContextAccessor _httpContextAccessor)
    {
        _logger = logger;
        httpContextAccessor = _httpContextAccessor;
    }

    public IActionResult Index()
    {
        var re=  httpContextAccessor.HttpContext.User.Claims.ToList();

        re.Select(x => x.Type == "Here type in the type of the claims like Email or else" ).FirstOrDefault();

     
        return View();
    }