添加 Azure AD 身份验证时出现 CORS 错误
CORS error when adding Azure AD authentication
尝试将 Azure AD 身份验证添加到具有 .net core 2.1 后端的 Angular 7 webapp。
但是,我在请求期间收到 CORS 错误。
"Access to XMLHttpRequest at 'https://login.microsoftonline.com/.......' (redirected from 'https://localhost:5001/api/auth/login') from origin 'https://localhost:5001' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource."
所以我尝试在启动管道中添加一些 CORS 策略。
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 授权服务
login() {
const url = this.baseUrl + "api/auth/login";
this._http.get(url).subscribe(response => {
console.log(response);
});
}
还是我走错了路?我应该使用第三方 "ADAL" npm 包 (https://www.npmjs.com/package/adal-angular) 从客户端提取令牌,然后将令牌传递给服务器进行验证吗?
如果我导航到登录 URL,例如:localhost:5000/api/auth/login --> 我将转到 AAD 登录页面,并在身份验证成功时重定向回来。但是如果我从代码触发它,我会收到 CORS 错误。
你的做法有点不对。
您已经配置了 OIDC + Cookie,但想用 XHR 调用它。
典型的方法是:
- 在 API
上配置 JWT Bearer 令牌身份验证
- 在前端使用ADAL/MSAL对用户进行身份验证+为后端获取访问令牌
- 将访问令牌附加到 XHR,以便对它们进行身份验证
一些 samples/articles 可能有帮助:
- https://github.com/Azure-Samples/active-directory-angularjs-singlepageapp-dotnet-webapi
- https://github.com/AzureAD/microsoft-authentication-library-for-js/tree/dev/samples/MSALAngularDemoApp
- https://github.com/azure-samples/active-directory-dotnet-native-aspnetcore-v2
- https://joonasw.net/view/azure-ad-authentication-aspnet-core-api-part-1
- https://joonasw.net/view/azure-ad-authentication-aspnet-core-api-part-2
请记住,ADAL 只能与 AAD v1 终结点一起使用,而 MSAL 只能与 v2 终结点一起使用。
尝试将 Azure AD 身份验证添加到具有 .net core 2.1 后端的 Angular 7 webapp。
但是,我在请求期间收到 CORS 错误。
"Access to XMLHttpRequest at 'https://login.microsoftonline.com/.......' (redirected from 'https://localhost:5001/api/auth/login') from origin 'https://localhost:5001' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource."
所以我尝试在启动管道中添加一些 CORS 策略。
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 授权服务
login() {
const url = this.baseUrl + "api/auth/login";
this._http.get(url).subscribe(response => {
console.log(response);
});
}
还是我走错了路?我应该使用第三方 "ADAL" npm 包 (https://www.npmjs.com/package/adal-angular) 从客户端提取令牌,然后将令牌传递给服务器进行验证吗?
如果我导航到登录 URL,例如:localhost:5000/api/auth/login --> 我将转到 AAD 登录页面,并在身份验证成功时重定向回来。但是如果我从代码触发它,我会收到 CORS 错误。
你的做法有点不对。 您已经配置了 OIDC + Cookie,但想用 XHR 调用它。
典型的方法是:
- 在 API 上配置 JWT Bearer 令牌身份验证
- 在前端使用ADAL/MSAL对用户进行身份验证+为后端获取访问令牌
- 将访问令牌附加到 XHR,以便对它们进行身份验证
一些 samples/articles 可能有帮助:
- https://github.com/Azure-Samples/active-directory-angularjs-singlepageapp-dotnet-webapi
- https://github.com/AzureAD/microsoft-authentication-library-for-js/tree/dev/samples/MSALAngularDemoApp
- https://github.com/azure-samples/active-directory-dotnet-native-aspnetcore-v2
- https://joonasw.net/view/azure-ad-authentication-aspnet-core-api-part-1
- https://joonasw.net/view/azure-ad-authentication-aspnet-core-api-part-2
请记住,ADAL 只能与 AAD v1 终结点一起使用,而 MSAL 只能与 v2 终结点一起使用。