在Startup.cs文件中添加以下代码来启用XSRF保护:
services.AddAntiforgery(options =>
{
options.HeaderName = "X-XSRF-TOKEN";
options.Cookie.Name = "XSRF-TOKEN";
options.Cookie.HttpOnly = false;
options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
});
在Angular应用程序中导入HttpClientXsrfModule,并将withCredentials选项设置为true:
import { HttpClientModule, HttpClientXsrfModule } from '@angular/common/http';
@NgModule({
imports: [
HttpClientModule,
HttpClientXsrfModule.withOptions({
cookieName: 'XSRF-TOKEN',
headerName: 'X-XSRF-TOKEN',
withCredentials: true // <== 这里设置为true
})
],
// other configurations...
})
export class AppModule { }
然后在每个需要进行HTTP请求的服务或组件中使用HttpClient的get,post,put或delete方法,并传递自定义标头“X-XSRF-TOKEN”来验证令牌:
import { HttpClient, HttpHeaders } from '@angular/common/http';
export class SomeService {
private httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'X-XSRF-TOKEN': this.getCookie('XSRF-TOKEN') // 根据需要获取和设置
})
};
constructor(private http: HttpClient) { }
someMethod() {
return this.http.get(url, this.httpOptions);
}
}
在ASP.NET Core应用程序中的Startup.cs文件中配置Cors,以允许从Angular应用程序发出的跨域请求:
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy("AllowAllOrigins",
builder =>
{
builder
.WithOrigins("http://localhost:4200") // 根据需要添加允许的源
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials();
});
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseCors("AllowAllOrigins");
// other middleware configurations...
}
然后,在Angular应用程序中设置请求URI为ASP.NET Core应用程序