I have a project developed with Angular (frontend) localhost:4200, this project in a future will be in production, I commented this just in case if someone help me with the solution and keep this in mind, also have a webservice developed with asp.net core 6, in my .net project have enable the jwt authentication, everything works fine when I consume api´s(controllers) but I have an error when I try to consume an API developed in PHP, this api is already in production in a plesk server, the error in console is the next one : Access to XMLHttpRequest at 'php api location' from origin 'http://localhost:4200' has been blocked by CORS policy: Request header field authorization is not allowed by Access-Control-Allow-Headers in preflight response. This is my configuration program.cs
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
builder.Services.AddScoped<IUserService, UserService>();
builder.Services.AddCors(options =>
{
options.AddPolicy("AllowOrigin", builder =>
{
builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod();
});
});
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var appSettingsSection = builder.Configuration.GetSection("AppSettings");
builder.Services.Configure<AppSettings>(appSettingsSection);
var appSettings = appSettingsSection.Get<AppSettings>();
var llave = Encoding.ASCII.GetBytes(appSettings.Secreto);
builder.Services.AddAuthentication(d =>
{
d.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
d.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(d =>
{
d.RequireHttpsMetadata = false;
d.SaveToken = true;
d.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(llave),
ValidateIssuer = false,
ValidateAudience = false
};
});
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseCors("AllowOrigin");
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
It is important also to mention that I use local storage to save token when an user login in my application and have an interceptor and look like this:
@Injectable()
export class JwtInterceptor implements HttpInterceptor{
constructor( private apiauthService : ApiauthService ){}
intercept( request : HttpRequest<any>, next: HttpHandler ) : Observable<HttpEvent<any>>{
const usuario = this.apiauthService.usuarioData;
//console.log(usuario);
if (usuario) {
//console.log('entra');
request = request.clone({
setHeaders: {
Authorization: `Bearer ${usuario.token}`
}
});
}
//console.log(request);
return next.handle(request);
}
}
The php file have this configurations:
header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method");
And that is all, if someone have any idea to solve this problem.
request = request.clone({
setHeaders: {
Authorization: `Bearer ${usuario.token}`
}
});
Requests are being sent with an additional header named Authorization
.
Access-Control-Allow-Headers:
would need to have Authorization
added specifically for it to be allowed. With this config, Authorization
is simply an implicitly denied header.
Try adding it to the allowed headers block and see if it helps!
For similar examples have a look at:
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Headers#examples