CORS error al agregar autenticación de Azure AD
Intentando agregar la autenticación de Azure AD a una aplicación web Angular 7 con un backend .net core 2.1.
Sin embargo, recibo el error CORS durante la solicitud.
"Acceso a XMLHttpRequest en 'https: //login.microsoftonline.com ....... '(redirigido desde'https: // localhost: 5001 / api / auth / login ') de origen'https: // localhost: 5001 'ha sido bloqueado por la política CORS: No hay encabezado' Access-Control-Allow-Origin 'presente en el recurso solicitado. "
Así que intenté agregar alguna política CORS en la tubería de inicio.
Startup.cs
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(config => config
.AddPolicy("SiteCorsPolicy", builder => builder
.AllowAnyHeader()
.AllowAnyMethod()
.AllowAnyOrigin()
.AllowCredentials()
)
); // <--- CORS policy - allow all for now
services.AddAuthentication(options =>
{
options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
})
.AddOpenIdConnect(options =>
{
options.Authority = "https://login.microsoftonline.com/MY_AD_DOMAIN.onmicrosoft.com"; // ad domain
options.ClientId = "my_client_id"; // client guid
options.ResponseType = OpenIdConnectResponseType.IdToken;
options.CallbackPath = "/auth/signin-callback";
options.SignedOutRedirectUri = "https://localhost:5000";
options.TokenValidationParameters.NameClaimType = "name";
}).AddCookie();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
// In production, the Angular files will be served from this directory
services.AddSpaStaticFiles(configuration =>
{
configuration.RootPath = "ClientApp/dist";
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseCors("SiteCorsPolicy"); // <--- CORS policy
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseSpaStaticFiles();
app.UseAuthentication();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller}/{action=Index}/{id?}");
});
app.UseSpa(spa =>
{
spa.Options.SourcePath = "ClientApp";
if (env.IsDevelopment())
{
spa.UseAngularCliServer(npmScript: "start");
}
});
}
}
angular auth service
login() {
const url = this.baseUrl + "api/auth/login";
this._http.get(url).subscribe(response => {
console.log(response);
});
}
¿O voy por el camino equivocado? ¿Debo usar algún paquete npm "ADAL" de tercer pary https: //www.npmjs.com/package/adal-angula) para extraer el token del lado del cliente y luego pasar el token al servidor para su validación?
Si navego a la URL de inicio de sesión, por ejemplo: localhost: 5000 / api / auth / login -> Me dirijo a la página de inicio de sesión de AAD y me redirigen nuevamente a una autenticación exitosa. Pero si lo disparo desde el código, obtengo el error CORS.