Spring?Boot?集成并開發(fā)?Sa-token示例詳解
1 Spring Boot集成Sa-token
1.1 前言
Sa-token是一款高可用的權限認證框架,他帶我們用最簡化的配置完成用 spring security 需要進行大量配置的才能完成的工作。
Sa-Token 是一個輕量級 Java 權限認證框架,主要解決:登錄認證、權限認證、單點登錄、OAuth2.0、分布式Session會話、微服務網(wǎng)關鑒權 等一系列權限相關問題。
官網(wǎng):https://sa-token.dev33.cn/
源碼:https://gitee.com/dromara/sa-token
1.2 集成Sa-token
在我們的基礎開發(fā)版本中,我們只需要引入最基礎依賴,現(xiàn)在的最新官方版本為:1.30.0 建議使用最新版本,如果在你的maven 倉庫中沒有該版本,需要替換maven 的鏡像源,請參考
<!-- Sa-Token 權限認證, 在線文檔:http://sa-token.dev33.cn/ --> <dependency> <groupId>cn.dev33</groupId> <artifactId>sa-token-spring-boot-starter</artifactId> <version>1.30.0</version> </dependency>
配置依賴后需要配置spring boot本地自定義配置
# Sa-Token 配置 sa-token: # token名稱 (同時也是cookie名稱) token-name: satoken # token有效期,單位s 默認30天, -1代表永不過期 timeout: 2592000 # token臨時有效期 (指定時間內無操作就視為token過期) 單位: 秒 activity-timeout: -1 # 是否允許同一賬號并發(fā)登錄 (為true時允許一起登錄, 為false時新登錄擠掉舊登錄) is-concurrent: true # 在多人登錄同一賬號時,是否共用一個token (為true時所有登錄共用一個token, 為false時每次登錄新建一個token) is-share: true # token風格 token-style: uuid # 是否輸出操作日志 is-log: false
按該配置,配置完成后即可完成基礎的引入,這里主要配置token 的過期和作用范圍。
token:服務端生成的一串加密字符串、以作客戶端進行請求的一個“令牌”。. 當用戶第一次使用賬號密碼成功進行登錄后,服務器便生成一個Token及Token失效時間并將此返回給客戶端,若成功登陸,以后客戶端只需在有效時間內帶上這個Token前來請求數(shù)據(jù)即可,無需再次帶上用戶名和密碼。
1.3 基礎使用
校驗是否成功引入可在啟動類下添加該語句
@SpringBootApplication @EnableScheduling public class CretApplication { public static void main(String[] args) { SpringApplication.run(CretApplication.class, args); System.out.println("啟動成功:Sa-Token配置如下:" + SaManager.getConfig()); } }
當控制臺輸出我們的配置內容時,證明sa-token 的依賴已經(jīng)引入,觀察輸出就會發(fā)現(xiàn)sa-token 已經(jīng)為我們初始化了很多的配置,接下的使用就會非常的簡單!
啟動成功:Sa-Token配置如下:SaTokenConfig [tokenName=satoken, timeout=2592000, activityTimeout=-1, isConcurrent=true, isShare=true, maxLoginCount=12, isReadBody=true, isReadHead=true, isReadCookie=true, tokenStyle=uuid, dataRefreshPeriod=30, tokenSessionCheckLogin=true, autoRenew=true, tokenPrefix=null, isPrint=true, isLog=false, jwtSecretKey=null, idTokenTimeout=86400, basic=, currDomain=null, checkIdToken=false, cookie=SaCookieConfig [domain=null, path=null, secure=false, httpOnly=false, sameSite=null]]
作為一個權限校驗開發(fā)框架,他的第一個動作便是針對我們的登錄操作,在登錄的時候便需要開始使用sa-token里面很強大的一個類‘ StpUtil.class’
// 會話登錄:參數(shù)填寫要登錄的賬號id,建議的數(shù)據(jù)類型:long | int | String, 不可以傳入復雜類型,如:User、Admin 等等 StpUtil.login(Object id); // 當前會話注銷登錄 StpUtil.logout(); // 獲取當前會話是否已經(jīng)登錄,返回true=已登錄,false=未登錄 StpUtil.isLogin(); // 檢驗當前會話是否已經(jīng)登錄, 如果未登錄,則拋出異常:`NotLoginException` StpUtil.checkLogin();
只需要通過簡單的一句登錄,sa-token便已經(jīng)為我們生成好權限校驗的系列組件。如果你覺得這種代碼方式的開發(fā)太繁瑣,不是那么的清晰知道當前的權限,進行簡單的校驗,就可以開啟注解方式的校驗。注解式校驗的配置如下:
@Configuration public class SaTokenConfig implements WebMvcConfigurer { // 注冊Sa-Token的注解攔截器,打開注解式鑒權功能 @Override public void addInterceptors(InterceptorRegistry registry) { // 注冊注解攔截器,并排除不需要注解鑒權的接口地址 (與登錄攔截器無關) registry.addInterceptor(new SaAnnotationInterceptor()).addPathPatterns("/**"); } }
在開啟攔截器后,我們即可實現(xiàn)注解式開發(fā),像之前使用spring 注解一般。
// 檢驗當前會話是否已經(jīng)登錄 StpUtil.checkLogin(); //檢驗當前會話是否已經(jīng)登錄 @SaCheckLogin
這里的注解可直接放在一個接口上,這樣當一個請求進來的時候sa-token 的攔截器會先從請求中獲取自己注入 的標識 sa-token ,這個sa-token 里面包含了系列參數(shù)來保證登錄的安全正確性。
2 Spring Boot開發(fā)Sa-token
上一部分我們介紹了如何通過sa-token 實現(xiàn)最基礎的登錄認證,在開發(fā)過程中我們會對sa-token 的一系列功能進行使用,慕歌將就自己的項目向大家展示sa-token 的一些功能,如登錄校驗、登錄檢測、封禁用戶,token 校驗,多租戶模式等功能
2.1 導入maven依賴
<!-- Sa-Token 整合 Redis (使用 jdk 默認序列化方式) --> <dependency> <groupId>cn.dev33</groupId> <artifactId>sa-token-dao-redis</artifactId> <version>1.30.0</version> </dependency> <!-- redis 緩存操作 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <!--連接池依賴--> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-pool2</artifactId> </dependency>
2.2 權限校驗
在進行登錄驗證的同時,進行權限校驗也是重要的一環(huán),sa-token通過攔截器,為我們的權限校驗進行了拓展,讓我們可以在全局工程中隨處進行權限控制。并且依賴于上一節(jié)介紹的注解式開發(fā),使得整個校驗過程更加的簡潔,明了。
/** * 注入權限組 */ @Component public class StpInterfaceImpl implements StpInterface { //權限 @Autowired AdminPowerMapper adminPowerMapper; //角色 @Autowired AdminRolesMapper adminRolesMapperl; /** * 用戶權限 * @param loginId 登錄id * @param s * @return */ @Override public List<String> getPermissionList(Object loginId, String s) { //獲得登錄的用戶id 對應權限 List<String> userPermissions = adminPowerMapper.getUserPermissions(loginId); System.out.println("permiassion - list : "+userPermissions); return userPermissions; } /** * 用戶角色 * @param loginId 登錄id * @param s * @return */ @Override public List<String> getRoleList(Object loginId, String s) { //獲得登錄的用戶id 對應角色 List<String> userRoles = adminRolesMapperl.getUserRole(loginId); System.out.println("role - list : "+userRoles); return userRoles; } }
在我的開發(fā)中,引入了兩層控制,角色表,權限表,進行細顆粒的權限控制,更好保證數(shù)據(jù)見的隔離。附上我的角色表于權限表的設計源碼:
create table cf_admin_power ( id int unsigned auto_increment comment '權限id' primary key, code varchar(32) not null comment '權限碼', name char(32) not null comment '權限名', level char(32) not null comment '等級', icon varchar(255) null comment '圖標', is_show tinyint unsigned default 1 not null comment '是否顯示(0:否,1:是)', status tinyint unsigned default 1 not null comment '狀態(tài)(1:可用,2:停用,3:已刪除)', create_time datetime not null comment '創(chuàng)建時間', update_time datetime not null comment '更新時間' ) comment '權限表 ' collate = utf8_unicode_ci; -- auto-generated definition create table cf_admin_roles ( id int unsigned auto_increment comment '角色id' primary key, name char(32) not null comment '角色名稱', role_info char(32) null comment '角色描述', is_super tinyint unsigned default 0 not null comment '是超級管理員(1:是,0:否)', status tinyint unsigned default 1 not null comment '狀態(tài)(1:可用,2:停用,3:已刪除)', create_time datetime null comment '創(chuàng)建時間', update_time datetime null comment '更新時間' ) comment '角色組表' collate = utf8_unicode_ci;
在為用戶注入權限后,權限的校驗就變得簡單起來了,只需要簡單的注解,調用即可校驗權限。就在這樣的一個校驗注解,就可以實現(xiàn)用戶角色,用戶權限的檢查
// 角色認證:必須具有指定角色才能進入該方法 @SaCheckRole("super-admin") // 權限認證:必須具有指定權限才能進入該方法 @SaCheckPermission("user-add") //三個權限并列,滿足一個則通過 @SaCheckPermission(value = {"user-add", "user-all", "user-delete"}, mode = SaMode.OR) //同時滿足角色和權限,通過 @SaCheckPermission(value = "user-add", orRole = "admin")
2.3 token
框架為我們提供了多種token生成方式,以及token 的校驗規(guī)則,將一個用戶標記為登錄狀態(tài)后,該用戶就進入sa-token 中進行統(tǒng)一管理。在配置redis 后,即可實現(xiàn)到重啟數(shù)據(jù)不丟失,而且保證分布式環(huán)境下多節(jié)點的會話一致性。
//登錄 StpUtil.login(user.getId()); // 踢下線 StpUtil.kickout(adminUser.getId()); //凍結 StpUtil.disable(adminUser.getId(), -1); // 獲取 Token 相關參數(shù) SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
在前后臺的開發(fā)中,我們可以將登錄信息回傳,即可實現(xiàn)前端通過token 建立訪問,前后端分離。前端可將登錄后返回的token 保存,之后每次進行數(shù)據(jù)訪問時攜帶token ,后端便可以對請求者的權限信息校驗。
//回傳數(shù)據(jù) "data":{11 items "tokenName":"satoken" "tokenValue":"6046ddd3-71cd-4509-b9ca-b842790bda72" "isLogin":true "loginId":"1002" "loginType":"login" "tokenTimeout":2592000 "sessionTimeout":2591999 "tokenSessionTimeout":-2 "tokenActivityTimeout":-1 "loginDevice":"default-device" "tag":NULL } //redis 緩存數(shù)據(jù) satoken:login:token:6046ddd3-71cd-4509-b9ca-b842790bda72
2.4 多租戶模式
在我的開發(fā)中,分官網(wǎng)用戶和后臺用戶,他們是完全不同的兩組數(shù)據(jù),具有各自獨立的權限,這時候需要使用到多租戶模式,對不同的用戶組維護各自的權限。sa-token為我們實現(xiàn)了一種簡單的方式,對不同的組加上對應的標簽。之后實現(xiàn)sa-token 的校驗模式,便可同標準使用方式一樣,對自己的用戶組校驗。
public class StpAdminUtil { //權限組 類型 admin public static final String TYPE = "admin"; //底層logic 靜態(tài)類 public static StpLogic stpLogic = new StpLogic("admin"); public StpAdminUtil() { } public static String getLoginType() { return stpLogic.getLoginType(); } public static void setStpLogic(StpLogic stpLogic) { cn.dev33.satoken.stp.StpUtil.stpLogic = stpLogic; SaManager.putStpLogic(stpLogic); } } /** * 聚合接口 */ @Configuration public class SaMultiConfig { @Autowired public void rewriteSaStrategy() { // 重寫Sa-Token的注解處理器,增加注解合并功能 SaStrategy.me.getAnnotation = (element, annotationClass) -> { return AnnotatedElementUtils.getMergedAnnotation(element, annotationClass); }; } } /** * 登錄認證(User版):只有登錄之后才能進入該方法 * <p> 可標注在函數(shù)、類上(效果等同于標注在此類的所有方法上) */ @SaCheckLogin(type = "admin") @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.METHOD, ElementType.TYPE}) public @interface SaAdminCheckLogin { }
到此這篇關于Spring Boot 集成并開發(fā) Sa-token的文章就介紹到這了,更多相關Spring Boot 集成 Sa-token內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Mybatis實現(xiàn)數(shù)據(jù)的增刪改查實例(CRUD)
本篇文章主要介紹了Mybatis實現(xiàn)數(shù)據(jù)的增刪改查實例(CRUD),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-05-05java使用xstream實現(xiàn)xml文件和對象之間的相互轉換
xml是一個用途比較廣泛的文件類型,在java里也自帶解析xml的包,但是本文使用的是xstream來實現(xiàn)xml和對象之間的相互轉換,xstream是一個第三方開源框架,使用起來比較方便,對java?xml和對象轉換相關知識感興趣的朋友一起看看吧2023-09-09SpringBoot使用Redis單機版過期鍵監(jiān)聽事件的實現(xiàn)示例
在緩存的使用場景中經(jīng)常需要使用到過期事件,本文主要介紹了SpringBoot使用Redis單機版過期鍵監(jiān)聽事件的實現(xiàn)示例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2024-07-07