Click here to Skip to main content
15,886,873 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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:
TypeScript
<pre>import { Injectable } from '@angular/core';
import {
  HttpEvent, HttpInterceptor, HttpHandler, HttpRequest
} from '@angular/common/http';
import { Observable } from 'rxjs';
/** Inject With Credentials into the request */
@Injectable()
export class HttpRequestInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler):
    Observable<HttpEvent<any>> {
    
      // console.log("interceptor: " + req.url);
      req = req.clone({
        withCredentials: true
      });
      
      return next.handle(req);
  }
}


web api:
program.cs:
C#
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

builder.Services.AddAuthorization(options =>
{
    // By default, all incoming requests will be authorized according to the default policy.
    options.FallbackPolicy = options.DefaultPolicy;
});
builder.Services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}



app.UseCors(x => //x.SetIsOriginAllowed(x => x.StartsWith("http:\\localhost:4200"))
    x.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();

app.MapControllers();


Controller:
C#
[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
Posted
Updated 30-Apr-23 1:29am

1 solution

This was released on YouTube 26minutes ago, it may help: Understanding CORS with ASP.NET Core C# - YouTube[^]. Anton is very good.
 
Share this answer
 
Comments
Member 15992206 1-May-23 2:58am    
Thank you very much, it helped a lot

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900