Spring boot,Spring Seesion,redis實現登錄驗證及共享session及接口權限管理
項目git地址:https://github.com/xubaodian/httpsecurity.git
代碼的細節就不展示了,需要的可以直接去git下載該項目,介紹下項目的創建過程,中間穿插一些代碼和思路講解,
使大家可根據這個可以自己一步一步創建工程。
項目創建過程如下:
1、首先創建spring boot項目,添加thymeleaf模板支持。
現在,spring boot就是web工程了,支持rest接口,html頁面處理,
如果不知道怎麼創建spring boot,先學習一下。
2、安裝redis
linux安裝就不解釋了,windows的官方網站沒有可用包,下面是resdis windows版下載地址:
https://github.com/ServiceStack/redis-windows
下載後啓動redis-server.exe,即可啓動redis,沒有配置的話,默認啓動端口是6379。
3、添加spring-session 和redis的依賴, 和redis配置。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
</dependency>
<dependency>
<groupId>io.lettuce</groupId>
<artifactId>lettuce-core</artifactId>
<version>5.1.3.RELEASE</version>
</dependency>
在application.properties文件加入如下redis配置:
# Redis服務地址.
spring.redis.host=localhost
# Redis服務端口號.
spring.redis.port=6379
# Session存儲類型.
spring.session.store-type=redis
# session有效期設置
server.servlet.session.timeout=600s
# Sessions flush mode.
spring.session.redis.flush-mode=ON_SAVE
# 存儲session key的命名空間
spring.session.redis.namespace=spring:session
修改服務端口號,啓動兩個該項目,兩個項目之間session都存儲在redis中,是共享的。
4、登錄驗證和權限管理
可以通過驗證token的方式,判斷用戶是否登錄。加入我們有登錄接口如下(這是一段僞代碼):
@PostMapping(value = "/login")
public @ResponseBody AjaxReult login(HttpServletRequest req, HttpServletResponse res,
@Param("username") String username, @Param("password") String password) {
//驗證username和password,通過則發放token
if(通過) {
//token寫入session
req.getSession().setAttribute("token", "這是token字符串");
} else {
//返回失敗信息
}
}
添加spring boot過濾器(filter),此過濾驗證所有請求,在過濾器中獲取token,判斷用戶是否登錄。
當然有一部分請求不需要登錄的,這部分直接放行。
項目中的:LogonFilter類就是filter,驗證登錄和權限的。
5、權限認證
可以發放token,判斷是否登錄,當然也可以發放一個權限字符串,判斷用戶是否登錄,工程裏有詳細的註釋,建議大家把工程下載下來,
看下代碼,並啓動工程。整個流程自然就清楚了。
如有疑問,可留言給我,或發郵件至[email protected]。歡迎大家一起來討論學習。