我有一个将使用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 Token中间件:
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; }
}