【Spring Security OAuth2筆記系列】- Spring Social第三方登錄 - 集羣session管理

集羣session管理

spring Security 是基於session的安全框架。所以就會有這個問題

// 該項目用來做瀏覽器端的所以需要有session
    // 提供集羣環境下的session管理,也沒有被管理到,需要自己添加
    //如果在啓動的時候報錯,可以通過配置 yml文件中 spring: session: store-type: none
    compile('org.springframework.session:spring-session:1.3.3.RELEASE')

org.springframework.boot.autoconfigure.session.StoreType 標識支持的類型,
上面設置成none其實就是使用原生j2ee單機服務器session這種模式

爲上面使用redis?

  1. 所有請求都要使用session
  2. 有過期時間,Redis天生支持

依賴:特別注意:spring-session:1.3.3.RELEASE在高版本的spring boot autoconfig中已經不支持了;
需要分開引用下面的包

// 該項目用來做瀏覽器端的所以需要有session
// 提供集羣環境下的session管理,也沒有被管理到,需要自己添加
//如果在啓動的時候報錯,可以通過配置 yml文件中 spring: session: store-type: none
//    compile('org.springframework.session:spring-session:1.3.3.RELEASE')
compile('org.springframework.session:spring-session-core')
compile('org.springframework.session:spring-session-data-redis')

開始改造

依賴添加之後,更改配置文件

spring:
  session:
    store-type: redis

訪問登錄頁面:/imocc-signIn.html; 發現驗證碼圖片無法顯示,報錯了。沒有序列化

// 相關報錯序列化問題的地方都記得修改
public class ImageCode extends ValidateCode implements Serializable{
    private static final long serialVersionUID = -703011095085705839L;
    private BufferedImage image;  // 看這裏,是一個複雜的圖片對象

怎麼處理這個圖片對象呢?考慮在存和取的地方下功夫

cn.mrcode.imooc.springsecurity.securitycore.validate.code.impl.AbstractValidateCodeProcessor#save

private void save(ServletWebRequest request, C validateCode) {
    // 不保存圖片對象到redis session中,無法序列化
    // 因爲在驗證的時候不需要圖片對象
    ValidateCode code = new ValidateCode(validateCode.getCode(), validateCode.getExpireTime());
    sessionStrategy.setAttribute(request, getSessionKey(), code);
}

測試

  1. 啓動兩個不同端口的項目
  2. 在同一個瀏覽器中
  3. 其中一個端口先登錄 :localhost:80
  4. 然後新開一個頁面直接打開另外一個端口訪問 localhost:80/user/me

之前配置的所有功能正常,只是在session失效只允許一個登錄這個功能,可能會有一點點的延遲

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章