什麼是 rest-api-spring-boot-starter
rest-api-spring-boot-starter 適用於SpringBoot Web API 快速構建讓開發人員快速構建統一規範的業務RestFull API 不在去關心一些繁瑣。重複工作,而是把重點聚焦到業務。
動機
每次Web API常用功能都需要重新寫一遍。或者複製之前的項目代碼。於是我封裝了這麼一個stater
抽出SpringBoot Web API 每個項目必備需要重複寫的模塊,和必備功能。
並且擴展了我工作中用到的 所有工具庫。 解放雙手提高開發效率
推薦版本
- SpringBoot
SpringBoot 2.7.x
版本更新
目前最新版本1.6.2 支持功能如下:
- 支持一鍵配置自定義RestFull API 統一格式返回
- 支持RestFull API 錯誤國際化
- 支持全局異常處理,全局參數驗證處理
- 業務錯誤斷言工具封裝,遵循錯誤優先返回原則
- 封裝Redis key,value 操作工具類。統一key管理 spring cache緩存實現
- RestTemplate 封裝 POST,GET 請求工具
- 日誌集成。自定義日誌路徑,按照日誌等級分類,支持壓縮和文件大小分割。按時間顯示
- 工具庫集成 集成了lombok,hutool,commons-lang3,guava。不需要自己單個引入
- 集成mybatisPlus一鍵代碼生成
- 日誌記錄,服務監控,支持日誌鏈路查詢。自定義數據源
- OpenApi3文檔集成支持一鍵配置。支持多種文檔和自動配置
- 生成JWT標準Token和權限認證
- 接口限流,Ip城市回顯
- HttpUserAgent請求設備工具封裝
- RequestUtil參數解析封裝工具
- GitHub 地址
- gitee 地址
Web JWT Token 權限支持
JWT Web Token
可以輕鬆自定義生成自己JWT Web Token.和基於JWT 的userJwtToken
通過userJwtToken你可以輕鬆生成基於用户登錄認證的Token
@Autowired
private UserJwtToken userJwtToken;
@GetMapping("/login")
public Result login() {
UserEntry userEntry = new UserEntry();
userEntry.setUserId("2");
userEntry.setUsername("billy");
userEntry.setHobby("eat");
userJwtToken.rememberMe=true;
String token = userJwtToken.createdToken(userEntry.getUserId(), userEntry.getUsername(), userEntry);
return Result.buildSuccess(token);
}
解析token獲取用户信息
@GetMapping("/user")
public Result getUser() {
String token = "eyJhbGciOiJIUzI1NiIsInppcCI6IkRFRiJ9.eNqqViouTVKyUkrKzMmpVNJRyiwuBvKMgKyskkwoK7WiQMnK0MzC0tTUwsDEWEeptDi1SMmqGkx7pkBVgTh5ibmpSIZl5CclVQL5qYklSrW1AAAAAP__.8nWRs40LbRTIQBhJ8jVaANPcvsmX0zoLR66R-b2Uc4M";
String userName=userJwtToken.getUserName(token);
String userId= userJwtToken.getUserId(token);
UserEntry userEntry=userJwtToken.parseUserToken(token,UserEntry.class);
return Result.buildSuccess(userId);
}
自定義Token秘鑰和簽名配置
jwt:
secret: 123456 # 秘鑰 建議加密後秘鑰如md5 不要使用明文長度大於6位
expiration: 86400 # token 過期時間(單位秒 1天后過期)
token-header: Token #header token 名稱
remember-me-expiration: 604800 #記住我 token過期時間(單位秒 7天后過期)
user-sign: true # 是否自定義簽名。為true需要實現加密接口。和 配置 jwtCfg注入對應bean
自定義簽名認證和動態秘鑰授權需要實現UserSign接口配置UserJwtConfig配置類注入自定義簽名bean
package cn.soboys.superaide.config;
import cn.soboys.restapispringbootstarter.authorization.UserSign;
import io.jsonwebtoken.SignatureAlgorithm;
/**
* @author 公眾號 程序員三時
* @version 1.0
* @date 2023/7/16 00:20
* @webSite https://github.com/coder-amiao
*/
public class MyUserSign implements UserSign {
@Override
public SignatureAlgorithm sign() {
return SignatureAlgorithm.HS256;
}
@Override
public String AuthKey() {
return null;
}
}
AuthKey返回null時候會使用你在屬性文件配置的秘鑰。沒有會使用默認的
package cn.soboys.superaide.config;
import cn.soboys.restapispringbootstarter.authorization.*;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
/**
* @author 公眾號 程序員三時
* @version 1.0
* @date 2023/7/15 09:49
* @webSite https://github.com/coder-amiao
* 用户jwt token生成配置
*/
@Configuration
public class UserJwtConfig {
@Bean
public UserSign MyUserSign() {
return new MyUserSign();
}
@Bean
public UserJwtToken userJwtToken(UserSign MyUserSign) {
UserJwtToken userJwtToken = new UserJwtToken();
userJwtToken.setUserSign(MyUserSign);
return userJwtToken;
}
}
權限認證
基於JWT Web Token 也幫你封裝了權限登錄認證。 你只需要在屬性文件配置開啓即可。
jwt:
authorization:
has-authorization: true
includes-url: /user # 需要認證請求 多個用逗號隔開
excludes-url: /login,/register/** # 配置無需認證的
全局幫你自動處理Token過期異常。和錯誤異常你只需要在heard中配置你自己的Token就行
{
"success": false,
"code": "401",
"msg": "未授權 ",
"requestId": "9a3ytEtOX0UuojSaA2LD",
"timestamp": "2023-07-17 17:08:05",
"data": null
}
如果需要自定義自己認證授權邏輯,實現LoginAuthorization接口即可
並且在UserJwtConfig配置類中注入對應LoginAuthorization bean
如:
package cn.soboys.superaide.config;
import cn.soboys.restapispringbootstarter.Assert;
import cn.soboys.restapispringbootstarter.HttpStatus;
import cn.soboys.restapispringbootstarter.authorization.LoginAuthorization;
import cn.soboys.restapispringbootstarter.authorization.UserJwtToken;
import org.dromara.hutool.core.text.StrUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @author 公眾號 程序員三時
* @version 1.0
* @date 2023/7/16 11:00
* @webSite https://github.com/coder-amiao
*/
@Component
public class MyLoginAuthorization implements LoginAuthorization {
@Autowired
private UserJwtToken userJwtToken;
@Override
public Boolean authorization(HttpServletRequest request, HttpServletResponse response, Object handler) {
String token = request.getHeader("Token");
Assert.isFalse(StrUtil.isEmpty(token),HttpStatus.UNAUTHORIZED);
String userId = userJwtToken.getUserId(token); //驗證token有效合法性。
//其他數據庫 或者業務操作
return true;
}
}
在配置類中注入bean
package cn.soboys.superaide.config;
import cn.soboys.restapispringbootstarter.authorization.*;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
/**
* @author 公眾號 程序員三時
* @version 1.0
* @date 2023/7/15 09:49
* @webSite https://github.com/coder-amiao
* 用户jwt token生成配置
*/
@Configuration
public class UserJwtConfig {
@Bean
public UserSign MyUserSign() {
return new MyUserSign();
}
@Bean
@Primary
public LoginAuthorization loginAuthorizationSubject() {
return new MyLoginAuthorization();
}
@Bean
public UserJwtToken userJwtToken(UserSign MyUserSign) {
UserJwtToken userJwtToken = new UserJwtToken();
userJwtToken.setUserSign(MyUserSign);
return userJwtToken;
}
}
三方權限認證框架
基於JWT Web Token也可以很輕鬆集成Shiro 或者是。Spring Security等其他第三權限框架
當然後續版本我會把權限認證獨立出來一個完整輕量級權限框架項目。如:
通過註解@hasPerm,@hasRole,@hasAnyPerm,@hasAnyRoles
輕鬆實現相對複雜的權限認證。
後續更新
通用業務
在我們聚焦項目開發時候,總是會有一些相對公共獨立的第三方業務模塊。
如:三方登錄,三方支付,消息推送,資源上傳
後續我會持續集成。通用業務生態。 實現真的解放生產力。自由組合。
有任何編程問題。
關注公眾號,程序員三時 持續輸出優質內容 希望給你帶來一點啓發和幫助