Encountering an issue with user authentication. Login is successful and I receive a token from the API, which I save in JwtTokenService within my Angular App. When making a request (e.g. Delete), I add the "Authorization" header with the value "Bearer token", as I did previously in Postman. The client's request:
https://i.sstatic.net/BIaCX.png
However, I am receiving a 302 status code and being redirected to Account/Login even though such a route does not exist.
https://i.sstatic.net/U8a5b.png
Error message displayed in the console:
Access to XMLHttpRequest at 'https://localhost:44332/api/car/2' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Interestingly, GET requests (which have [AllowAnonymous] attribute) are working fine.
The request in Postman functions properly, leading me to believe there may be an issue related to cookies.
.Net Conf details:
[Route("api/[controller]")]
[ApiController]
[Authorize]
[ExceptionHandlingFilter]
public class CarController : ControllerBase
{
[HttpDelete("{id}")]
public async Task<IActionResult> Delete(int id)
{
}
Startup configuration snippet:
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder => builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
});
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = configuration["Jwt:Issuer"],
ValidAudience = configuration["Jwt:Issuer"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["Jwt:Key"]))
};
options.Events = new JwtBearerEvents
{
OnMessageReceived = context =>
{
var accessToken = context.Request.Query["access_token"];
// If the request is for our hub...
var path = context.HttpContext.Request.Path;
if (!string.IsNullOrEmpty(accessToken) &&
(path.StartsWithSegments("/chat")))
{
// Read the token out of the query string
context.Token = accessToken;
}
return Task.CompletedTask;
}
};
});
app.UseCors("CorsPolicy");
EDIT1:
[HttpDelete("{id}")]
[Authorize(Policy = JwtBearerDefaults.AuthenticationScheme)]
public async Task<IActionResult> Delete(int id)
{
Error reported: System.InvalidOperationException: The AuthorizationPolicy named: 'Bearer' was not found.
Additional console error given below:
Access to XMLHttpRequest at 'https://localhost:44332/api/car/2' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. zone-evergreen.js:2845 DELETE https://localhost:44332/api/car/2 net::ERR_FAILED