在使用 Angular 19(后端使用 ASP.NET Core 8)的应用程序中,我已将 Core 模块配置为在应用程序初始化时从后端获取 XSRF cookie :
import { inject, NgModule, provideAppInitializer } from '@angular/core';
import { CommonModule } from '@angular/common';
import { provideHttpClient, withInterceptors, withXsrfConfiguration } from '@angular/common/http';
import { tokenInterceptor } from './interceptors/token.interceptor';
import { AuthenticationService } from './services/authentication.service';
export function appInitilizerCheckTokenValidity(): Promise<void> {
const authService = inject(AuthenticationService);
return authService.checkTokenValidity().then(
_isValid => {},
() => {}
);
}
export function appInitilizerGetXsrfToken(): Promise<any> {
const authService = inject(AuthenticationService);
return authService.xsrfToken().then(
_ => {},
() => {}
)
}
@NgModule({
declarations: [],
imports: [
CommonModule
],
providers: [
provideAppInitializer(() => appInitilizerCheckTokenValidity()),
provideAppInitializer(() => appInitilizerGetXsrfToken()),
provideHttpClient(withXsrfConfiguration({cookieName: 'XSRF-TOKEN', headerName: 'X-XSRF-TOKEN'})),
]
})
export class CoreModule { }
xsrfToken()
API 如下所示:
xsrfToken(): Promise<any> {
let url = `${this.baseXsrfUrl}/xsrf`;
return firstValueFrom(this.http.get<{elment:any}>(url, {withCredentials: true})));
}
我后端的 API 如下所示:
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace AmazixWeb.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class XsrfController : ControllerBase
{
[HttpGet("xsrf")]
public IActionResult XSRFToken()
{
var csrfToken = Guid.NewGuid().ToString();
Response.Cookies.Append("XSRF-TOKEN", csrfToken, new CookieOptions
{
HttpOnly = false,
SameSite = SameSiteMode.None,
Secure = true
});
return Ok();
}
}
}
初始化时,收集 XSRF cookie 的 get 请求工作正常,我收到这种响应,其中在 cookie 中添加了 xsrf 令牌:
此时 Angular 应该获取 XSRF-TOKEN cookie 并将其放置在 POST、PUT 或 DELETE 请求的每个标头中(标头名称:X-XSRF-TOKEN) 但是,当我发出新的 POST 请求(例如登录的 POST 请求)时,X-XSRF-TOKEN cookie 存在,但其标头丢失。请参阅下面的示例:
我不知道为什么 X-XSRF-TOKEN 标头没有自动添加到 POST 标头中。有人可以帮我吗?
感谢之前的评论,我终于找到了解决方案:从绝对 url 中移动基本 url :
apiUrl: 'https://localhost:7139/api'
到相对网址:
apiUrl: '//localhost:7139/api'