我正在使用 Ionic Framework 开发一个应用程序,并为我的后端生成了一个 JHipster 项目。我的 JHipster 项目在额外的服务器上运行,并通过我的应用程序的 REST 请求进行调用。所以我现在的问题是处理 CORS 和 CSRF 配置。
我的 JHipster 项目有自己的前端,它在同一域上运行,并且在测试时我可以毫无问题地访问我的后端。但是,当我想从 Ionic 应用程序调用服务器上的后端时,我的 xsrf token 将无法正确更新,因此我无法访问我的后端。我已经尝试了不同堆栈溢出帖子中的几种解决方案,但没有一个对我有用。
例如:
到目前为止我做了什么:
- 我在 JHipster 项目的 SecurityConfiguration 中启用了 csrf
http
.csrf()
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
.and()
.addFilterBefore(corsFilter, UsernamePasswordAuthenticationFilter.class)
.exceptionHandling()
.authenticationEntryPoint(problemSupport)
.accessDeniedHandler(problemSupport)
- 添加了 CORS 配置
cors:
allowed-origins: 'http://localhost:8100, ionic://localhost, http://localhost'
allowed-methods: 'POST, GET, OPTIONS, DELETE, PUT, HEAD'
allowed-headers: 'Origin, X-Requested-With, Content-Type, Accept, x-auth-token, Authorization, X-CSRF-Token, x-xsrf-token, XSRF-TOKEN'
exposed-headers: 'Authorization,Link,X-Total-Count,XSRF-TOKEN, X-XSRF-TOKEN'
allow-credentials: true
max-age: 86400
- 编写了一个拦截器
@Injectable()
export class HttpXSRFInterceptor implements HttpInterceptor {
constructor(private tokenExtractor: HttpXsrfTokenExtractor, private csrfService:CSRFService, private $sessionStorage: SessionStorageService) {
}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const headerName = 'XSRF-TOKEN';
const respHeaderName = 'X-XSRF-TOKEN';
let token = this.tokenExtractor.getToken() as string;
if (token !== null && !req.headers.has(headerName)) {
req = req.clone({ headers: req.headers.set(respHeaderName, token) });
req.clone({
withCredentials: true
});
}
return next.handle(req);
}
}
- 在我的 app.module.ts 和拦截器中添加了 HttpClientXsrfModule
HttpClientXsrfModule.withOptions({
cookieName: 'XSRF-TOKEN',
headerName: 'X-XSRF-TOKEN',
}),
{
provide: HTTP_INTERCEPTORS,
useClass: HttpXSRFInterceptor,
multi: true
},
我的问题:
在浏览器中启动我的应用程序时,我没有获得 xsrf token ,但在发送发布请求后, token 被设置为 cookie。
例如,登录时,第一次尝试由于缺少 token 而失败,但第二次登录请求成功,因为现在 xsrf token 的响应 header 不再为空。此外,即使服务器响应的 header 中有新 token , token 也不会自行更新。
据我了解
我第一次获取 token 应该是在加载应用程序的起始页后立即进行
token 应在服务器(后端)每次响应后更新,更新后的 token 将用于下一个请求
因此我的问题是这两个问题都没有发生,而且我不知道如何解决它。
感谢任何帮助!
干杯
最佳答案
我是 JHipster 的 Ionic 的作者,所以希望我能帮助你。
首先,CSRF 不应该成为问题,除非您在同一端口上运行应用程序。根据我的经验,当您在单独的端口上运行它们时,您的客户端无法读取 cookie。至于 CORS,在本地运行时这对我来说不是问题。我相信这是因为 dev
配置文件的 CORS 设置是开放的。您可以尝试在 prod
配置文件中使用 dev
配置文件中的设置,看看是否有帮助?
仅供引用,它们是:
jhipster:
cors:
allowed-origins: '*'
allowed-methods: '*'
allowed-headers: '*'
exposed-headers: 'Authorization,Link,X-Total-Count'
allow-credentials: true
max-age: 1800
如果这有效,我会尝试将允许的来源更改为数组,或者只使用一个。如果在本地运行,http://localhost:8100
应该是您所需要的。
关于ionic-framework - CSRF token 未正确更新(Ionic + Spring Security),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61083132/