![](/img/trans.png)
[英]Authorization by a Claim of a Role on Web API using JWT Token- Asp.net Core Identity
[英]ASP.NET Core Web API: JWT token does not set "HttpContext User"
我的应用程序中有一个 JWT 令牌实现,并且我实现了 Google 登录。 但是现在,没有设置HttpContext.User
声明。
这是我的startup.cs
:
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
}).AddGoogle(options =>
{
options.ClientId = CLIENT_ID
options.ClientSecret = SECRET
options.SaveTokens = true;
})
.AddJwtBearer(options =>
{
options.SaveToken = true;
options.RequireHttpsMetadata = false;
options.TokenValidationParameters = new TokenValidationParameters()
{
ValidateIssuer = true,
ValidateAudience = true,
ValidAudience = Configuration["JWT:ValidAudience"],
ValidIssuer = Configuration["JWT:ValidIssuer"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JWT:Secret"]))
};
options.Events = new JwtBearerEvents
{
OnMessageReceived = context =>
{
context.Token = context.Request.Cookies[CookieAuthenticationDefaults.AuthenticationScheme];
context.HttpContext.User = context.Principal;
return Task.CompletedTask;
},
};
}).AddCookie(CookieAuthenticationDefaults.AuthenticationScheme);
我这样登录:
Microsoft.AspNetCore.Identity.SignInResult result = await _signInManager.PasswordSignInAsync(Email, Password, false, true);
这就是我创建 JWT 令牌的方式:
var authClaims = new List<Claim>
{
new Claim(ClaimTypes.Email, user.UserName),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
new Claim(ClaimTypes.Name, user.FirstName)
};
var authSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(["JWT:Secret"]));
var token = new JwtSecurityToken(
issuer: ["JWT:ValidIssuer"],
audience: ["JWT:ValidAudience"],
expires: DateTime.UtcNow.AddHours(1),
claims: authClaims,
signingCredentials: new SigningCredentials(authSigningKey, SecurityAlgorithms.HmacSha256)
);
通常,它设置HttpContext.User
和声明,我可以检查
var userEmail = HttpContext.User.FindFirst(ClaimTypes.Email).Value
但现在,这将返回 null。
你知道为什么吗?
我终于得到了解决方案。 我只是添加await _signInManager.SignInAsync(user, false,"JwtBearer");
并解决了。 谢谢!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.