我正在尝试使用ASP.NET Core实现一个非常简单的JWT承载认证实现 . 我从控制器返回一个响应,如下所示:
var identity = new ClaimsIdentity();
identity.AddClaim(new Claim(ClaimTypes.Name, applicationUser.UserName));
var jwt = new JwtSecurityToken(
_jwtOptions.Issuer,
_jwtOptions.Audience,
identity.Claims,
_jwtOptions.NotBefore,
_jwtOptions.Expiration,
_jwtOptions.SigningCredentials);
var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);
return new JObject(
new JProperty("access_token", encodedJwt),
new JProperty("token_type", "bearer"),
new JProperty("expires_in", (int)_jwtOptions.ValidFor.TotalSeconds),
new JProperty(".issued", DateTimeOffset.UtcNow.ToString())
);
我有传入请求的Jwt中间件:
app.UseJwtBearerAuthentication(new JwtBearerOptions
{
AutomaticAuthenticate = true,
AutomaticChallenge = true,
TokenValidationParameters = tokenValidationParameters
});
这似乎有助于使用authorize属性保护资源,但声明永远不会出现 .
[Authorize]
public async Task<IActionResult> Get()
{
var user = ClaimsPrincipal.Current.Claims; // Nothing here
3 回答
您不能在ASP.NET Core应用程序中使用
ClaimsPricipal.Current
,因为它不是由运行时设置的 . 您可以阅读https://github.com/aspnet/Security/issues/322以获取更多信息 .相反,请考虑使用由
ControllerBase
公开的User
属性 .访问
User.Claims
而不是ClaimsPrinciple.Current.Claims
.From Introduction to Identity at docs.asp.net:
来自MVC存储库的Here is the relevant source code:
作为ASP.NET Core 2.0的一部分,您可以像上面描述的Shaun一样阅读JWT声明 . 如果您只是在寻找用户ID(请确保您已使用“Sub”声明名称将其添加为声明的一部分),那么您可以根据您的使用情况使用以下两个示例来阅读:
Read User ID Claim:
Read Other Claims: