I have a problem while authenticating an user. Login works perfectly and I receive a token from API. I save it in JwtTokenService in my Angular App and while performing a request (ex. Delete) I add "Authorization" header with value "Bearer token" as I did before in PostMan. Request from client:
I get 302 status code and redirection to Account/Login even though I dont have such rout
Error in 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.
But GETs (which have [AllowAnonymous] attribute are working fine)
Request in postman works well. I think it's something messed up with my cookies. .Net Conf:
[Route("api/[controller]")]
[ApiController]
[Authorize]
[ExceptionHandlingFilter]
public class CarController : ControllerBase
{
[HttpDelete("{id}")]
public async Task<IActionResult> Delete(int id)
{
}
and Startup
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: System.InvalidOperationException: The AuthorizationPolicy named: 'Bearer' was not found.
Console error: 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
[EnableCors("SomePolicy")]
to your controller docs.microsoft.com/en-us/aspnet/core/security/…, Also from my understanding, Postman doesnt care about CORS – AndrewEapp.UseCors(...)
afterUseRouting
, but beforeUseAuthorization
– Tomas Chabada[Authorize]
to[Authorize(Policy = JwtBearerDefaults.AuthenticationScheme)]
– AndrewE