此问题可能是由于CSRF令牌未正确添加到Angular 11的HTTP header中所导致的。为了解决此问题,您可以遵循以下步骤:
1.确保在Angular 11中导入HttpClientModule。例如:
import { HttpClientModule } from '@angular/common/http';
@NgModule({ imports: [ HttpClientModule ] })
2.在Spring Boot后端中启用CSRF保护。例如,在你的配置文件中添加以下代码:
@Override protected void configure(HttpSecurity http) throws Exception { http.csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()); }
3.在Angular 11的服务中添加CSRF header。例如:
import { HttpClient, HttpHeaders } from '@angular/common/http';
@Injectable({ providedIn: 'root' }) export class MyService { private csrfToken = '';
constructor(private http: HttpClient) {}
postData(data: any) {
const headers = new HttpHeaders({
'X-CSRF-TOKEN': this.csrfToken
'Content-Type': 'application/json'
});
return this.http.post('/api/endpoint', data, {headers});
}
}
4.在Angular 11的组件中获取CSRF token并保存到服务中。例如:
import { HttpClient } from '@angular/common/http';
@Component({ selector: 'app-my-component', templateUrl: './my-component.component.html', styleUrls: ['./my-component.component.css'] }) export class MyComponent implements OnInit { constructor(private http: HttpClient, private myService: MyService) {}
ngOnInit() {
this.http.get('/api/csrf-token', {withCredentials: true}).subscribe((data: {token: string}) => {
this.myService.setCsrfToken(data.token);
});
}
}
5.确保您的Angular 11应用程序在与Spring Boot后端部署在同一服务器上时,使用相同的域名和协议,以确保Cookie可以在两个应用程序之间共享。
以上是解决“Angular 11 + Spring Boot POST header CSRF token not working”的方法。