SpringBoot 前後端動靜分離+叢集 遇到的第一個問題:跨域session共享
阿新 • • 發佈:2019-01-06
後臺服務要實現高可用,需要做相關的配置改變,其中比較重要的問題是session共享
原專案中,使用了自定義token放在Request Header中來鑑定使用者的身份
但前後端分離畢竟是使用了驗證碼,有跨域問題,還是需要cookie攜帶才能解決
但是要實現叢集,就必須實現session共享
因為專案中正好在用了Redis,所以選擇了Rdis快取 + Spring Session來實現
maven依賴
<!--redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
<!-- spring session的依賴 -->
<dependency> <groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
</dependency>
redis連線引數
#redis
spring.redis.host=xx.xx.xx.xx
spring.redis.port=6379
spring.redis.password=xxxx
前端ajax全域性設定xhrFields: {
withCredentials: true
}
後端SpringBootpublic class AuthApplication {
public static void main(String[] args) {
SpringApplication.run(AuthApplication.class, args);
}
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
@Override
public void addCorsMappings(CorsRegistry registry) {
//全域性支援CORS(跨源請求)
registry.addMapping("/**")
//允許任意來源
.allowedOrigins("*")
.allowedMethods("PUT", "DELETE","OPTIONS", "GET", "POST")
.allowedHeaders("*")
.exposedHeaders("access-control-allow-headers",
"access-control-allow-methods",
"access-control-allow-origin",
"access-control-max-age",
"X-Frame-Options")
.allowCredentials(CrossOrigin.DEFAULT_ALLOW_CREDENTIALS)//允許Cookie跨域
.maxAge(3600);
}
};
}
}
此時,可以傳送自定義的cookie資訊了,但是沒看到session被傳送到伺服器,
此時的情況時:
Response Headers
Set-Cookie:SESSION=4bbd2abd-4aa0-42d9-a8f4-d6b212a83b7e;path=/;Secure;HttpOnly
注意到了這後面的HttpOnly 不太明白其中的意思 查詢如下文章中
Secure 可選
一個帶有安全屬性的 cookie 只有在請求使用SSL和HTTPS協議的時候才會被髮送到伺服器。然而,保密或敏感資訊永遠不要在 HTTP cookie 中儲存或傳輸,因為整個機制從本質上來說都是不安全的,比如前述協議並不意味著所有的資訊都是經過加密的。
注意:非安全站點(http:)已經不能再在 cookie 中設定 secure 指令了(在Chrome 52+ and Firefox 52+ 中新引入的限制)。
HttpOnly 可選
設定了 HttpOnly 屬性的 cookie 不能使用 JavaScript 經由 Document.cookie 屬性、XMLHttpRequest 和 Request APIs 進行訪問,以防範跨站指令碼攻擊(XSS)。
一開始嘗試關閉掉這兩個配置,但似乎沒起作用,可能我引數用錯了
等於要使用Https協議,由於測試的時候一直是使用http。。。哎!
因為專案早就使用了阿里雲證書,開啟了Https,所以此處略過
更換成Https協議後,每次傳送的cookie中終於看到攜帶了session了(本地cookie中也看到了儲存的session)