.net core 如何在使用Azure AD身份验证请求API时修复CORS错误
此项目的目标是使用.NET Core 2.2使用Azure Active Directory对用户进行身份验证 我通过直接在浏览器中发出请求来对用户进行身份验证。 例如,如果我从浏览器调用“”,则没有问题 但如果我从角度项目调用它,我会得到以下错误:.net core 如何在使用Azure AD身份验证请求API时修复CORS错误,.net-core,azure-active-directory,.net Core,Azure Active Directory,此项目的目标是使用.NET Core 2.2使用Azure Active Directory对用户进行身份验证 我通过直接在浏览器中发出请求来对用户进行身份验证。 例如,如果我从浏览器调用“”,则没有问题 但如果我从角度项目调用它,我会得到以下错误: Access to XMLHttpRequest at 'https://login.microsoftonline.com/{tenant_id}/oauth2/authorize?client_id={client_id}2&redir
Access to XMLHttpRequest at 'https://login.microsoftonline.com/{tenant_id}/oauth2/authorize?client_id={client_id}2&redirect_uri=https%3A%2F%2Flocalhost%3A44353%2Fsignin-oidc&response_type=id_token&scope=openid%20profile&response_mode=form_post&nonce={nonce}'
(redirected from 'https://localhost:44353/api/azureauth/me') from origin 'null' has been blocked by CORS policy:
Response to preflight request doesn't pass access control check:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
这是我的Startup.cs:
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
.AddAzureAD(options => Configuration.Bind("AzureAd", options));
services.Configure<OpenIdConnectOptions>(AzureADDefaults.OpenIdScheme, options =>
{
options.Authority = options.Authority + "/v2.0/";
options.TokenValidationParameters.ValidateIssuer = false;
});
services.AddMvc(options =>
{
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
options.Filters.Add(new AuthorizeFilter(policy));
});
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder => builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials()
);
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseAuthentication();
app.UseMvc();
app.UseCors("CorsPolicy");
}
以下是Angular中调用.NET核心API的服务:
import { Injectable, Inject } from '@angular/core';
import { map } from 'rxjs/operators';
import { HttpHeaders, HttpClient } from '@angular/common/http';
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': '',
'Access-Control-Allow-Credentials': '*',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': '*'
})
};
@Injectable({
providedIn: 'root'
})
export class AzureAuthService {
private baseUrl = 'https://localhost:44353/api/azureauth';
constructor(protected http: HttpClient) {
}
public me() {
return this.http.get(`${this.baseUrl}`, httpOptions).
pipe(
map((data) => {
return data;
}, (err) => {
console.log('An error occured', err);
})
);
}
}
我不理解这个问题,因为我知道我允许Angular的查询和.NET核心API中的CORS管理中的所有源代码和方法
我提到该项目是一个Azure广告示例项目,其核心是ASP.NET()
感谢您的回答正如建议的那样,您需要一个Active Directory身份验证库(如ADAL或MSAL)来执行身份验证过程
注册客户机应用程序并启用OAuth2隐式授权,使其能够访问API。请参阅此代码示例项目:。您可能需要查看作为“受众”提供的信息 打开appsettings.json
抓取Angular应用程序收到的承载令牌,并将其粘贴到jwt.io的表单中。
对于观众,请在此处输入“aud”下的值。
对于发卡机构,请在此处输入“iss”下的值。
此处有更多信息(步骤7):
希望能有所帮助。OpenID Connect+cookie身份验证(您在这里使用)并不真正适合API。相反,您应该实现JWT承载令牌身份验证,并让前端处理身份验证和令牌获取,例如MSAL.js。我更喜欢这种解决方案。我有选择的余地吗?还是我的问题没有解决方案?我在Angular应用程序中成功地获得了一个带有MSAL的令牌。但当我把它发送到.NET核心应用程序时,我总是得到401。在日志中,我得到:AzureADJwtBearer未经过身份验证。失败消息:IDX10214:观众验证失败
[Route("api/[controller]"), EnableCors("CorsPolicy")]
[ApiController]
public class AzureAuthController
{
public IActionResult Me()
{
return new JsonResult("ok");
}
}
import { Injectable, Inject } from '@angular/core';
import { map } from 'rxjs/operators';
import { HttpHeaders, HttpClient } from '@angular/common/http';
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': '',
'Access-Control-Allow-Credentials': '*',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': '*'
})
};
@Injectable({
providedIn: 'root'
})
export class AzureAuthService {
private baseUrl = 'https://localhost:44353/api/azureauth';
constructor(protected http: HttpClient) {
}
public me() {
return this.http.get(`${this.baseUrl}`, httpOptions).
pipe(
map((data) => {
return data;
}, (err) => {
console.log('An error occured', err);
})
);
}
}