前言
之前看到satoken(文档),感觉很方便。之前我用shiro+redis+jwt(或者session)遇到的一些问题,用这个感觉都不是问题,很轻易就能解决,比如:多端登录可以不用写realm、移动端保持长期登录、token自动刷新、超过系统空闲时间重新登录等。 功能还是比较全面的,下面主要是会写一些比较常用的。
一、大概需求
web登录,有个闲置时间设置:1 30分钟未发送请求,重新登录,0 无限制。 角色菜单权限控制。
一、框架搭建
1、引入依赖、yml文件
<properties>
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<spring-boot.version>2.5.6</spring-boot.version>
<sa-token-version>1.29.0</sa-token-version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<exclusions>
<exclusion>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-to-slf4j</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.11</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.3</version>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.7.22</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.9</version>
<exclusions>
<exclusion>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
</exclusion>
<exclusion>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>cn.dev33</groupId>
<artifactId>sa-token-spring-boot-starter</artifactId>
<version>${sa-token-version}</version>
</dependency>
<dependency>
<groupId>cn.dev33</groupId>
<artifactId>sa-token-dao-redis-jackson</artifactId>
<version>${sa-token-version}</version>
</dependency>
<dependency>
<groupId>cn.dev33</groupId>
<artifactId>sa-token-alone-redis</artifactId>
<version>${sa-token-version}</version>
</dependency>
</dependencies>
server:
port: 8081
spring:
datasource:
url: jdbc:mysql://127.0.0.1:3306/satoken_db?useUnicode=true&characterEncoding=utf8&allowMultiQueries=true&useSSL=false&serverTimezone=GMT%2B8&allowPublicKeyRetrieval=true
username: root
password: root
type: com.zaxxer.hikari.HikariDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
redis:
host: "127.0.0.1"
port: 6379
timeout: 10s
password: 123456
database: 0
lettuce:
pool:
max-active: -1
max-wait: -1
max-idle: 16
min-idle: 8
main:
allow-bean-definition-overriding: true
servlet:
multipart:
max-file-size: -1
max-request-size: -1
aop:
auto: true
sa-token:
token-name: sa-token-authorization
timeout: 3600
token-style: random-32
is-read-head: true
auto-renew: true
activity-timeout: 1800
is-concurrent: true
alone-redis:
database: 0
host: 127.0.0.1
port: 6379
password: 123456
timeout: 10s
mybatis-plus:
mapper-locations: classpath:mapper/*/*.xml
type-aliases-package: com.entity.sys,;com.common.base
global-config:
db-config:
id-type: auto
field-strategy: NOT_EMPTY
db-type: MYSQL
configuration:
map-underscore-to-camel-case: true
call-setters-on-nulls: true
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
2、Config 和 Interceptor
@Configuration
@EnableWebMvc
public class GlobalCorsConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
String path = System.getProperty("user.dir") + "\\upload\\";
registry.addResourceHandler("/upload/**")
.addResourceLocations("file:"+path).addResourceLocations("classpath:/resources/");
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginInterceptor()).addPathPatterns("/**")
.excludePathPatterns("/sys/login","/sys/getCode","/sys/getKey","/api/favicon.ico","/upload/**");
}
@Bean
public CorsFilter corsFilter() {
CorsConfiguration config = new CorsConfiguration();
config.addAllowedOriginPattern("*");
config.setAllowCredentials(true);
config.addAllowedHeader("*");
config.addAllowedMethod("*");
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOriginPatterns("*")
.allowCredentials(true)
.allowedMethods("GET", "POST", "DELETE", "PUT")
.maxAge(3600)
.exposedHeaders();
}
}
LoginInterceptor 登录拦截
public class LoginInterceptor implements HandlerInterceptor {
private void delCache(String tokenValue,String loginId){
RedisUtil redisUtil= SpringUtil.getBean(RedisUtil.class);
String lastActivity = BaseConstant.cachePrefix+"last-activity:"+tokenValue;
String session = BaseConstant.cachePrefix+"session:"+loginId;
String token = BaseConstant.tokenCachePrefix+tokenValue;
if (redisUtil.hasKey(lastActivity)){
redisUtil.del(lastActivity);
}
if (redisUtil.hasKey(session)){
redisUtil.del(session);
}
if (redisUtil.hasKey(token)){
redisUtil.del(token);
}
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)throws Exception {
response.setHeader("Access-Control-Allow-Origin", (request).getHeader("Origin"));
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json");
String tokenValue = StpUtil.getTokenValue();
if (!StpUtil.isLogin()){
ResultVo resultVo = new ResultVo();
resultVo.setCode(1003);
resultVo.setMessage("用户未登录,请进行登录");
response.getWriter().write(JSONUtil.toJsonStr(resultVo));
String loginId = (String) StpUtil.getLoginIdByToken(tokenValue);
delCache(tokenValue,loginId);
return false;
}
long tokenTimeout = StpUtil.getTokenTimeout();
if (tokenTimeout != -1){
SaTokenDao saTokenDao = SaManager.getSaTokenDao();
saTokenDao.updateSessionTimeout(StpUtil.getSession().getId(),3600);
saTokenDao.updateTimeout(BaseConstant.tokenCachePrefix+tokenValue,3600);
saTokenDao.updateTimeout(BaseConstant.cachePrefix+"last-activity:"+tokenValue,3600);
}
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
}
}
PermissionInterface 权限验证
@Component
public class PermissionInterface implements StpInterface {
@Resource
private SysMenuService sysMenuService;
@Override
public List<String> getPermissionList(Object loginId, String loginType) {
List<String> list = new ArrayList<String>();
for (String roleId : getRoleList(loginId, loginType)) {
SysQuery queryVo = new SysQuery();
queryVo.setId(roleId);
List<SysMenu> menuList = sysMenuService.selectPermsByRoleId(queryVo);
List<String> collect = menuList.stream().map(SysMenu::getPerms).collect(Collectors.toList());
list.addAll(collect);
}
return list;
}
@Override
public List<String> getRoleList(Object loginId, String loginType) {
List<String> list = new ArrayList<>();
SysUser user = (SysUser) StpUtil.getSession().get("user");
list.add(user.getRoleId());
return list;
}
}
3、SysLoginController登录
@RestController
@RequestMapping("/sys")
public class SysLoginController {
@Resource
private SysSafeService sysSafeService;
@Resource
private SysUserService sysUserService;
@Resource
private RedisUtil redisUtil;
private int ERROR_COUNT = 3;
@PostMapping("/login")
public ResultVo login(String userName, String password, String code, HttpServletRequest request){
try {
code = code.toUpperCase();
Object verCode = redisUtil.get(BaseConstant.verCode+code);
if (null == verCode) {
return ResultUtil.error("验证码已失效,请重新输入");
}
String verCodeStr = verCode.toString();
if (verCodeStr == null || StrUtil.isEmpty(code) || !verCodeStr.equalsIgnoreCase(code)) {
return ResultUtil.error("验证码错误");
}else if (!redisUtil.hasKey(BaseConstant.verCode+code)) {
return ResultUtil.error("验证码已过期,请重新输入");
}else {
redisUtil.del(BaseConstant.verCode+code);
}
userName = RSAUtil.decrypt(userName);
password = RSAUtil.decrypt(password);
SysSafe safe = sysSafeService.list().get(0);
SysUser user = passwordErrorNum(userName, password,safe);
StpUtil.login(user.getId());
String tokenValue = StpUtil.getTokenValue();
int i = safe.getIdleTimeSetting();
if (i==0){
SaTokenDao saTokenDao = SaManager.getSaTokenDao();
SaTokenConfig config = SaManager.getConfig();
saTokenDao.updateSessionTimeout(StpUtil.getSession().getId(),-1);
saTokenDao.updateTimeout(BaseConstant.tokenCachePrefix+tokenValue ,-1);
saTokenDao.updateTimeout(BaseConstant.cachePrefix+"last-activity:"+tokenValue ,-1);
config.setActivityTimeout(-1);
}
StpUtil.getSession().set("user",user);
return ResultUtil.success(tokenValue);
} catch (ExceptionVo e) {
return ResultUtil.error(e.getCode(),e.getMessage());
}catch (Exception e) {
e.printStackTrace();
return ResultUtil.error("未知异常");
}
}
@PostMapping("/test")
public ResultVo test(){
Map<String,Object> map = new HashMap<>();
SaSession session = StpUtil.getSession();
map.put("user",session.get("user"));
map.put("permission",StpUtil.getPermissionList());
map.put("tokenInfo",StpUtil.getTokenInfo());
return ResultUtil.success(map);
}
@GetMapping(value = "/getCode")
public void getCode(HttpServletResponse response) {
try {
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
response.setContentType("image/jpeg");
RandomGenerator randomGenerator = new RandomGenerator(BaseConstant.captcha, 4);
LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(100, 42,4,50);
lineCaptcha.setGenerator(randomGenerator);
BufferedImage image = lineCaptcha.getImage();
OutputStream out = response.getOutputStream();
redisUtil.set(BaseConstant.verCode+lineCaptcha.getCode(), lineCaptcha.getCode(), 60);
ImageIO.write(image, "png", out);
} catch (Exception e) {
e.printStackTrace();
}
}
@DeleteMapping("/logout")
public ResultVo logout(HttpServletRequest request){
StpUtil.logout();
return ResultUtil.success("退出登录成功");
}
@GetMapping("/getKey")
public ResultVo getKey() {
String publicKey = RSAUtil.getPublicKey();
System.out.println(publicKey);
return ResultUtil.success(publicKey);
}
private boolean lockedUser(long currentTime,String userName){
boolean flag = false;
if (redisUtil.hasKey(BaseConstant.ERROR_COUNT+userName)){
long loginTime = Long.parseLong(redisUtil.hget(BaseConstant.ERROR_COUNT+userName, "loginTime").toString());
int i = Integer.parseInt(redisUtil.hget(BaseConstant.ERROR_COUNT+userName,"errorNum").toString());
if (i >= ERROR_COUNT && currentTime < loginTime){
Duration between = LocalDateTimeUtil.between(LocalDateTimeUtil.of(currentTime), LocalDateTimeUtil.of(loginTime));
throw new ExceptionVo(1004,"账号锁定中,还没到允许登录的时间,请"+between.toMinutes()+"分钟后再尝试");
}else{
flag = true;
}
}
return flag;
}
private SysUser passwordErrorNum(String userName,String password,SysSafe sysSafe) throws InvalidKeySpecException, NoSuchAlgorithmException {
SysUser user = sysUserService.getUserByName(userName);
if (null == user){
throw new ExceptionVo(1001,"用户不存在");
}
boolean authenticate = EncryptionUtil.authenticate(password, user.getPassword(), user.getSalt());
if (authenticate) {
redisUtil.del(BaseConstant.ERROR_COUNT+userName);
} else {
long currentTime = System.currentTimeMillis();
boolean flag = lockedUser(currentTime, userName);
String str = "15";
long timeStamp = System.currentTimeMillis()+900000;
if (sysSafe.getPwdLoginLimit()==1){
ERROR_COUNT = 5;
str = "30";
timeStamp = System.currentTimeMillis()+1800000;
}
if (redisUtil.hasKey(BaseConstant.ERROR_COUNT+userName)){
int i = Integer.parseInt(redisUtil.hget(BaseConstant.ERROR_COUNT+userName,"errorNum").toString());
if (flag && i==ERROR_COUNT){
redisUtil.hset(BaseConstant.ERROR_COUNT+userName,"errorNum",1);
}else {
redisUtil.hincr(BaseConstant.ERROR_COUNT+userName,"errorNum",1);
}
redisUtil.hset(BaseConstant.ERROR_COUNT+userName,"loginTime",timeStamp);
}else {
Map<String,Object> map = new HashMap<>();
map.put("errorNum",1);
map.put("loginTime",timeStamp);
redisUtil.hmset(BaseConstant.ERROR_COUNT+userName, map, -1);
}
int i = Integer.parseInt(redisUtil.hget(BaseConstant.ERROR_COUNT+userName,"errorNum").toString());
if (i==ERROR_COUNT){
throw new ExceptionVo(1004,"您的密码已错误"+ERROR_COUNT+"次,现已被锁定,请"+str+"分钟后再尝试");
}
throw new ExceptionVo(1000,"密码错误,总登录次数"+ERROR_COUNT+"次,剩余次数: " + (ERROR_COUNT-i));
}
return user;
}
}
4、RSAUtil 非对称加密、解密工具类
import org.apache.tomcat.util.codec.binary.Base64;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
public class RSAUtil {
private static final KeyPair keyPair = initKey();
private static KeyPair initKey() {
try {
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
generator.initialize(1024, new SecureRandom());
return generator.generateKeyPair();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static String getPublicKey() {
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
return new String(Base64.encodeBase64(publicKey.getEncoded()));
}
public static String encrypt(String str) {
byte[] decoded = Base64.decodeBase64(getPublicKey());
RSAPublicKey pubKey;
String outStr = null;
try {
pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
outStr = Base64.encodeBase64String(cipher.doFinal(str.getBytes(StandardCharsets.UTF_8)));
} catch (InvalidKeySpecException | BadPaddingException | IllegalBlockSizeException | InvalidKeyException | NoSuchPaddingException | NoSuchAlgorithmException e) {
e.printStackTrace();
}
return outStr;
}
public static String decrypt(String str) {
byte[] inputByte = Base64.decodeBase64(str.getBytes(StandardCharsets.UTF_8));
PrivateKey privateKey = keyPair.getPrivate();
byte[] decoded = privateKey.getEncoded();
RSAPrivateKey priKey;
Cipher cipher;
String outStr = null;
try {
priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded));
cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, priKey);
outStr = new String(cipher.doFinal(inputByte));
} catch (InvalidKeySpecException | NoSuchAlgorithmException | NoSuchPaddingException | BadPaddingException | IllegalBlockSizeException | InvalidKeyException e) {
e.printStackTrace();
}
return outStr;
}
}
5、EncryptionUtil 密码盐值加密工具类
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import java.math.BigInteger;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
public class EncryptionUtil {
public static final String PBKDF2_ALGORITHM = "PBKDF2WithHmacSHA1";
public static final int SALT_BYTE_SIZE = 16;
public static final int HASH_BIT_SIZE = 64;
public static final int PBKDF2_ITERATIONS = 1000;
public static boolean authenticate(String attemptedPassword, String encryptedPassword, String salt) throws NoSuchAlgorithmException, InvalidKeySpecException {
String encryptedAttemptedPassword = getEncryptedPassword(attemptedPassword, salt);
return encryptedAttemptedPassword.equals(encryptedPassword);
}
public static String getEncryptedPassword(String password, String salt) throws NoSuchAlgorithmException, InvalidKeySpecException {
KeySpec spec = new PBEKeySpec(password.toCharArray(), fromHex(salt), PBKDF2_ITERATIONS, HASH_BIT_SIZE);
SecretKeyFactory f = SecretKeyFactory.getInstance(PBKDF2_ALGORITHM);
return toHex(f.generateSecret(spec).getEncoded());
}
public static String generateSalt() throws NoSuchAlgorithmException {
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
byte[] salt = new byte[SALT_BYTE_SIZE];
random.nextBytes(salt);
return toHex(salt);
}
private static byte[] fromHex(String hex) {
byte[] binary = new byte[hex.length() / 2];
for (int i = 0; i < binary.length; i++) {
binary[i] = (byte) Integer.parseInt(hex.substring(2 * i, 2 * i + 2), 16);
}
return binary;
}
private static String toHex(byte[] array) {
BigInteger bi = new BigInteger(1, array);
String hex = bi.toString(16);
int paddingLength = (array.length * 2) - hex.length();
if (paddingLength > 0) return String.format("%0" + paddingLength + "d", 0) + hex;
else return hex;
}
}
|