尝试将Azure身份验证添加到带有.net核心2.1后端的Range7webapp中。
但是,在请求期间,我会得到CORS错误。
“访问XMLHttpRequest at‘https://login.microsoftonline.com/.’(从‘https://localhost:5001/api/auth/login’重定向)源'https://localhost:5001‘已被CORS策略阻止:请求的资源上不存在’访问-控制-允许-原产地‘标头。”
所以我尝试在启动管道中添加一些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");
}
});
}
}
角服务
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错误。
发布于 2018-11-19 22:47:57
你的方法有点不对。您已经配置了OIDC + Cookies,但希望用XHR调用它。
典型的做法是:
一些样本/文章可能有助于:
请记住,ADAL只能用于AAD v1端点,MSAL只能用于v2端点。
https://stackoverflow.com/questions/53378607
复制相似问题