繁体   English   中英

使用Firebase和Identity的ASP.NET Core API身份验证

[英]ASP.NET Core API authentication using Firebase and Identity

我有一个将使用Firebase jwt令牌身份验证的API。

Startup.cs我注册了Identity

        services.AddIdentity<ApplicationUser, IdentityRole>(config => {

            config.User.RequireUniqueEmail = true;

            config.Password.RequireNonAlphanumeric = false;

            config.Cookies.ApplicationCookie.AutomaticChallenge = false;

        })
        .AddEntityFrameworkStores<DatabaseContext>()
        .AddDefaultTokenProviders();

并添加了Jwt令牌中间件:

        app.UseJwtBearerAuthentication(new JwtBearerOptions
        {
            AutomaticAuthenticate = true,
            IncludeErrorDetails = true,
            Authority = "https://securetoken.google.com/[my-project-id]",
            TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuer = true,
                ValidIssuer = "https://securetoken.google.com/[my-project-id]",
                ValidateAudience = true,
                ValidAudience = "[my-project-id]",
                ValidateLifetime = true,
            },
        });

我正在使用[Authorize]保护我的路线,并且一切正常。 HttpContext.User.Identity.Authenticated属性设置为true ,但User对象上的其他所有内容均为null,名称,电子邮件等。

有什么方法可以将令牌中间件生成的用户链接到数据库中的用户? 从我的控制器访问此信息的最佳方法是什么?

我曾经遇到过类似的问题,并且能够从“ HttpContext.User.Claims”获取用户电子邮件

确保您根据Json字符串生成POCO类。

------------------控制器代码---------------------

    [HttpGet("GetAll")]
    public IEnumerable<string> GetAll()
    {
        var user = HttpContext.User;
        var claims = ((System.Security.Claims.ClaimsIdentity)user.Identity).Claims;
        var items = claims.ToList();
        var jsonstr = items.Last().Value;

        FirebaseIdentity fb = (FirebaseIdentity)JsonConvert.DeserializeObject(jsonstr, typeof(FirebaseIdentity));
        //**** get the user email address here ***
        var useremail = fb.identities.email[0];

        return new string[] { "value1", "value2" };
    }

------------------模型类---------------------

[Serializable, JsonObject]
public class FirebaseIdentity
{
    [JsonProperty("identities")]
    public Identities identities { get; set; }
    [JsonProperty("sign_in_provider")]
    public string sign_in_provider { get; set; }
}

[Serializable, JsonObject]
public class Identities
{
    [JsonProperty("email")]
    public List<string> email { get; set; }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM