springboot+security後端與前端需要注意的withCredentials設定

1。如果security的配置中使用了sessionManagement()會話管理,如下:

springboot+security後端與前端需要注意的withCredentials設定

2。則前端的axios需要開啟withCredentials為true的設定。如果不設定或者設定為false,登入成功後,其他介面會報“還沒登入”方面的錯誤(302的錯誤)。

說明:

withCredentials:跨域請求是否提供憑據資訊(cookie、HTTP認證及客戶端SSL證明等)

springboot+security後端與前端需要注意的withCredentials設定

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)。如下:

springboot+security後端與前端需要注意的withCredentials設定

5。還要注意後端配置時,要使用allowedOriginPatterns(),而不是allowedOrigin(),否則也會報跨域問題。

6。登入之後,怎樣獲取使用者的資訊資料呢

可以從SecurityContextHolder上下文的持有者中獲取上下文,再獲取登入認證的實體,從而拿到儲存使用者資訊的Principal物件。

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

springboot+security後端與前端需要注意的withCredentials設定