I have an ASP.NET Core 3.1 API that uses JWT authentication, the API is intended to send resources to an Angular project. Some of the methods are protected by authentication with user log in. This works in Visual Studio debugging. But on IIS I only get 401 errors on any of these methods, even though the api returns the correct token upon logging in.
I don't know what I'm doing wrong, I actually have no idea what I'm doing at this point. Any help with the API and IIS will be very much appreciated.
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" });
}
}
Other Controller Example Method
[Authorize(Roles = "Admin")]
[HttpGet]
public IActionResult Get()
{
try
{
doStuff();
}
catch (Exception e)
{
return BadRequest(e);
}
return Ok();
}