优秀的编程知识分享平台

网站首页 > 技术文章 正文

springboot+security后端与前端需要注意的withCredentials设置

nanyue 2025-01-21 20:25:34 技术文章 7 ℃

1.如果security的配置中使用了sessionManagement()会话管理,如下:

2.则前端的axios需要开启withCredentials为true的设置。如果不设置或者设置为false,登录成功后,其他接口会报“还没登录”方面的错误(302的错误)。

说明:
withCredentials:跨域请求是否提供凭据信息(cookie、HTTP认证及客户端SSL证明等)

3.如果后端不配置allowCredentials(true)。接口就会报错。如下:

Access to XMLHttpRequest at 'http://localhost:8080/login' from origin 'http://localhost:8090' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

4.所有后端需要在跨域的配置地方,配置allowCredentials(true)。如下:

5.还要注意后端配置时,要使用allowedOriginPatterns(),而不是allowedOrigin(),否则也会报跨域问题。

6.登录之后,怎样获取用户的信息数据呢

可以从SecurityContextHolder上下文的持有者中获取上下文,再获取登录认证的实体,从而拿到保存用户信息的Principal对象。

Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();

最近发表
标签列表