我有一个使用JWT身份验证的ASP.NET Core 3.1 API,该API旨在将资源发送到Angular项目。 某些方法受用户登录身份验证的保护。这在Visual Studio调试中有效。但是在IIS上,即使api在登录后返回了正确的令牌,在这些方法中的任何一种上我都只会收到401错误。
我不知道我在做什么错,实际上我不知道我在做什么。对于API和IIS的任何帮助将不胜感激。
StartUp.cs
services.AddAuthentication(opt =>
{
opt.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
opt.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = "https://localhost:8080",
ValidAudience = "https://localhost:8080",
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("mySecretKey"))
};
});
appSettings.json
"iisSettings": {
"windowsAuthentication": true,
"anonymousAuthentication": false
}
UserController.cs
[HttpPost("login")]
public IActionResult Login([FromBody]User input)
{
if (input == null)
{
return BadRequest("Invalid client request");
}
var user = _context.Users.FirstOrDefault(ol => ol.Email == input.Email && ol.Password == input.Password);
if (user != null)
{
var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("mySecretKey"));
var signingCredentials = new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha256);
var claims = new List<Claim>
{
new Claim(ClaimTypes.Email, user.Email),
new Claim(ClaimTypes.Role, user.Admin ? "Admin" : "NormalUser")
};
var tokenOptions = new JwtSecurityToken(
issuer: "https://localhost:8080",
audience: "https://localhost:8080",
claims: claims,
expires: DateTime.Now.AddHours(2),
signingCredentials: signingCredentials
);
var tokenString = new JwtSecurityTokenHandler().WriteToken(tokenOptions);
return Ok(new { Token = tokenString });
}
else
{
return Ok(new { Token = "Unauthorized" });
}
}
其他控制器示例方法
[Authorize(Roles = "Admin")]
[HttpGet]
public IActionResult Get()
{
try
{
doStuff();
}
catch (Exception e)
{
return BadRequest(e);
}
return Ok();
}
答案 0 :(得分:0)
我的朋友发现了我的问题!令牌从未添加到请求的auth标头中。我所做的就是使用HTTP拦截器将令牌添加到每个请求中。真正的问题是,它在没有拦截器的情况下如何进行调试?
我想我们可以从中学到的是在运行StackOverflow之前先检查标头。
我在this question上使用了MartinAdámek的答案。