Hello,
when I try to get window authenticated by .net 6 through angular, I get an error:
Access to XMLHttpRequest at ... from origin 'http://localhost:4200' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
What I have tried:
my code:
Angular:
<pre lang="TypeScript">
update(user: User) {
const headers = new HttpHeaders().set('Content-Type', 'application/json');
return this.httpClient.post(this.url + "/UpdateUser",JSON.stringify(user), {headers: headers, withCredentials: true})
}
HttpInterceptor:
<pre>import { Injectable } from '@angular/core';
import {
HttpEvent, HttpInterceptor, HttpHandler, HttpRequest
} from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable()
export class HttpRequestInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler):
Observable<HttpEvent<any>> {
req = req.clone({
withCredentials: true
});
return next.handle(req);
}
}
web api:
program.cs:
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddAuthorization(options =>
{
options.FallbackPolicy = options.DefaultPolicy;
});
builder.Services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseCors(x =>
x.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
Controller:
[HttpPost]
[Route("UpdateUser")]
public async Task<bool> UpdateUser(
[FromBody] User user)
{
IPrincipal p = HttpContext.User;
var userId = _httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value;
return await _service.UpdateUser(user.userID);
}
Appreciate for help