ASP .NET Core API with Angular and Windows Auth - 预检请求
ASP .NET Core API with Angular and Windows Auth - Preflight Requests
我最近的任务是使用 ASP.NET Core 3.0 API 和 Angular 8.
创建公司的内部网站
为了对用户进行授权,我设置了 API 项目 Windows 身份验证并将其包含在 Startup.cs
中
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(IISDefaults.AuthenticationScheme);
services.AddCors(options =>
{
options.AddPolicy("FrontEndPolicy",
builder => builder.WithOrigins("http://localhost:4200")
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
});
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DevConnection")));
AddScopedServices(services);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseCors("FrontEndPolicy");
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
我在 Postman 中测试了基本 API 调用,一切正常,所以我设置了 CORS,创建了 Angular 项目并在那里继续。创建的拦截器将凭据添加到我的请求中:
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
req = req.clone({
withCredentials: true,
});
return next.handle(req);
}
然后执行简单的 GET 方法(它 return 当前用户):
getUser() {
return this.http.get
(environment.apiUrlCoreUserHttp,
{ observe: 'response' });}
这工作正常并且 returns 所需数据(用户名):
GET Method Test
对结果很满意,我决定测试 POST 方法,因此再次创建了简单的方法,它应该 return 向控制台发送消息:
API 项目:
[HttpPost]
[Route("{siteName}/post")]
public ActionResult<string> PostForm()
{
return User.Identity.Name == null ? $"Posted data as Anonymous user" : $"Posted data as {User.Identity.Name}";
}
在Angular中:
post() {
var body = {};
return this.http.post(environment.apiUrlCoreHttp + "dynamicsites/cheesestore/post",
body,
{responseType: 'text'}).subscribe(res => console.log(JSON.stringify(res)));}
然而,响应状态代码是 401:
Response Value
POST Headers
我假设给出的错误是响应中的预检请求存在问题 headers。
然后我决定在没有打开身份验证的情况下测试 post 方法,结果是肯定的,我在控制台中得到了所需的数据:
POST Headers without Auth
我假设我在打开身份验证时出现错误的原因是选项预检请求中缺少特定响应 headers 即:
Access-Control-Allow-Headers:content-type
Access-Control-Allow-Methods:POST
Access-Control-Allow-Origin:http://localhost:4200
在之前的请求中丢失了。我试图找到一个相关的解决方案,但没有任何运气。有人遇到 Windows Authentication/CORS 场景的问题吗?我必须承认它非常模糊,因为 GET 工作得很好而且 POST 如果在尝试从前端访问数据时打开身份验证则根本不会。
我想我会分享我是如何设法解决这个问题的,以防有人需要它。
唯一需要做的是在 StartUp.cs 的 Web API 项目中:
public void Configure(IApplicationBuilder app, IHostingEnvironment env) {
app.UseCors(option => option.WithOrigins
("http://localhost:4200")
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());}
这让我可以从我的 angular 应用程序中获取 post 数据。
我最近的任务是使用 ASP.NET Core 3.0 API 和 Angular 8.
创建公司的内部网站为了对用户进行授权,我设置了 API 项目 Windows 身份验证并将其包含在 Startup.cs
中 public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(IISDefaults.AuthenticationScheme);
services.AddCors(options =>
{
options.AddPolicy("FrontEndPolicy",
builder => builder.WithOrigins("http://localhost:4200")
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
});
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DevConnection")));
AddScopedServices(services);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseCors("FrontEndPolicy");
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
我在 Postman 中测试了基本 API 调用,一切正常,所以我设置了 CORS,创建了 Angular 项目并在那里继续。创建的拦截器将凭据添加到我的请求中:
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
req = req.clone({
withCredentials: true,
});
return next.handle(req);
}
然后执行简单的 GET 方法(它 return 当前用户):
getUser() {
return this.http.get
(environment.apiUrlCoreUserHttp,
{ observe: 'response' });}
这工作正常并且 returns 所需数据(用户名):
GET Method Test
对结果很满意,我决定测试 POST 方法,因此再次创建了简单的方法,它应该 return 向控制台发送消息:
API 项目:
[HttpPost]
[Route("{siteName}/post")]
public ActionResult<string> PostForm()
{
return User.Identity.Name == null ? $"Posted data as Anonymous user" : $"Posted data as {User.Identity.Name}";
}
在Angular中:
post() {
var body = {};
return this.http.post(environment.apiUrlCoreHttp + "dynamicsites/cheesestore/post",
body,
{responseType: 'text'}).subscribe(res => console.log(JSON.stringify(res)));}
然而,响应状态代码是 401:
Response Value
POST Headers
我假设给出的错误是响应中的预检请求存在问题 headers。 然后我决定在没有打开身份验证的情况下测试 post 方法,结果是肯定的,我在控制台中得到了所需的数据:
POST Headers without Auth
我假设我在打开身份验证时出现错误的原因是选项预检请求中缺少特定响应 headers 即:
Access-Control-Allow-Headers:content-type Access-Control-Allow-Methods:POST Access-Control-Allow-Origin:http://localhost:4200
在之前的请求中丢失了。我试图找到一个相关的解决方案,但没有任何运气。有人遇到 Windows Authentication/CORS 场景的问题吗?我必须承认它非常模糊,因为 GET 工作得很好而且 POST 如果在尝试从前端访问数据时打开身份验证则根本不会。
我想我会分享我是如何设法解决这个问题的,以防有人需要它。
唯一需要做的是在 StartUp.cs 的 Web API 项目中:
public void Configure(IApplicationBuilder app, IHostingEnvironment env) {
app.UseCors(option => option.WithOrigins
("http://localhost:4200")
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());}
这让我可以从我的 angular 应用程序中获取 post 数据。