我在Microsoft.AspNetCore.Authentication.JwtBearer
中使用ASP.Net Core Web Api
库进行jwt身份验证。当我请求令牌时,它工作正常,我得到一个令牌。
但是当我向安全Action
发送请求时,我会收到401状态代码。
在我的Startup
班级中:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory,IOptionsSnapshot<SiteSettings> siteSettings)
{
var jwtOption = siteSettings.Value.JwtOption;
var tokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidIssuer = jwtOption.Issuer,
ValidateAudience = true,
ValidAudience = jwtOption.Audience,
ValidateIssuerSigningKey = true,
IssuerSigningKey = _signingKey,
RequireExpirationTime = false,
ValidateLifetime = false,
ClockSkew = TimeSpan.Zero
};
app.UseMvc();
app.UseApiCustomIdentityServices();
app.UseJwtBearerAuthentication(new JwtBearerOptions
{
AutomaticAuthenticate = true,
AutomaticChallenge = true,
Audience = jwtOption.Audience,
Authority = jwtOption.Audience,
RequireHttpsMetadata = false,
TokenValidationParameters = tokenValidationParameters
});
}
我的TokenController
:
public class TokenController : Controller
{
private readonly IUserManager _userManager;
private readonly IJwtService _jwtService;
private readonly IOptionsSnapshot<SiteSettings> _siteSettings;
private readonly JsonSerializerSettings _serializerSettings;
public TokenController(
IUserManager userManager,
IJwtService jwtService,
IOptionsSnapshot<SiteSettings> siteSettings
)
{
_userManager = userManager;
_jwtService = jwtService;
_siteSettings = siteSettings;
_serializerSettings = new JsonSerializerSettings
{
Formatting = Formatting.Indented
};
}
[HttpPost]
public async Task<IActionResult> Post([FromBody]LoginViewModel model)
{
if (!ModelState.IsValid)
return BadRequest();
var identity = await GetClaimsIdentity(model.Username, model.Password);
if (identity == null)
{
return BadRequest();
}
var response = new
{
id = identity.Claims.Single(c => c.Type == "id").Value,
auth_token = await _jwtService.GenerateEncodedToken(model.Username, identity),
expires_in = (int)_siteSettings.Value.JwtOption.ValidFor.TotalSeconds
};
var json = JsonConvert.SerializeObject(response, _serializerSettings);
return new OkObjectResult(json);
}
private async Task<ClaimsIdentity> GetClaimsIdentity(string userName, string password)
{
if (!string.IsNullOrEmpty(userName) && !string.IsNullOrEmpty(password))
{
var userToVerify = await _userManager.FindByNameAsync(userName);
if (userToVerify != null)
{
if (await _userManager.CheckPasswordAsync(userToVerify, password))
{
return await Task.FromResult(_jwtService.GenerateClaimsIdentity(userName, userToVerify.Id.ToString()));
}
}
}
return await Task.FromResult<ClaimsIdentity>(null);
}
出了什么问题?