整合jwt

This commit is contained in:
2022-09-21 17:50:01 +08:00
parent 98deffce46
commit b623970db8
9 changed files with 79 additions and 114 deletions

View File

@@ -9,9 +9,11 @@
</parent>
<modelVersion>4.0.0</modelVersion>
<properties>
<hutool.version>5.3.4</hutool.version>
<hutool.version>5.7.14</hutool.version>
</properties>
<!--hutool 5.3.4-->
<artifactId>nladmin-common</artifactId>
<name>公共模块</name>

View File

@@ -15,6 +15,7 @@
*/
package org.nl.exception.handler;
import cn.dev33.satoken.exception.NotLoginException;
import lombok.extern.slf4j.Slf4j;
import org.nl.exception.BadRequestException;
import org.nl.exception.EntityExistException;
@@ -59,6 +60,19 @@ public class GlobalExceptionHandler {
// return buildResponseEntity(ApiError.error(message));
// }
/**
* token 无效的异常拦截
* @param e
* @return
*/
@ExceptionHandler(value = NotLoginException.class)
public ResponseEntity<ApiError> notLoginException(Exception e) {
// e.printStackTrace();
log.error(ThrowableUtil.getStackTrace(e));
return buildResponseEntity(ApiError.error("Token 无效"));
}
/**
* 处理自定义异常
*/

View File

@@ -1,74 +0,0 @@
///*
// * Copyright 2019-2020 Zheng Jie
// *
// * Licensed under the Apache License, Version 2.0 (the "License");
// * you may not use this file except in compliance with the License.
// * You may obtain a copy of the License at
// *
// * http://www.apache.org/licenses/LICENSE-2.0
// *
// * Unless required by applicable law or agreed to in writing, software
// * distributed under the License is distributed on an "AS IS" BASIS,
// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// * See the License for the specific language governing permissions and
// * limitations under the License.
// */
//package org.nl.modules.security.config.bean;
//
//import lombok.Data;
//import org.springframework.boot.context.properties.ConfigurationProperties;
//import org.springframework.context.annotation.Configuration;
//
///**
// * Jwt参数配置
// *
// * @author Zheng Jie
// * @date 2019年11月28日
// */
//@Data
//public class SecurityProperties {
//
// /**
// * Request Headers Authorization
// */
// private String header;
//
// /**
// * 令牌前缀,最后留个空格 Bearer
// */
// private String tokenStartWith;
//
// /**
// * 必须使用最少88位的Base64对该令牌进行编码
// */
// private String base64Secret;
//
// /**
// * 令牌过期时间 此处单位/毫秒
// */
// private Long tokenValidityInSeconds;
//
// /**
// * 在线用户 key根据 key 查询 redis 中在线用户的数据
// */
// private String onlineKey;
//
// /**
// * 验证码 key
// */
// private String codeKey;
//
// /**
// * token 续期检查
// */
// private Long detect;
//
// /**
// * 续期时间
// */
// private Long renew;
//
// public String getTokenStartWith() {
// return tokenStartWith + " ";
// }
//}

View File

@@ -119,7 +119,7 @@ public class AuthorizationController {
}};
// 保存在线信息
// onlineUserService.save(jwtUserDto, token, request);
onlineUserService.save(userDto, StpUtil.getTokenValue(), request);
return ResponseEntity.ok(authInfo);
}
@@ -160,7 +160,8 @@ public class AuthorizationController {
@AnonymousDeleteMapping(value = "/logout")
public ResponseEntity<Object> logout(HttpServletRequest request) {
StpUtil.getTokenSession().clear(); // 清除session数据
// onlineUserService.logout(tokenProvider.getToken(request));
onlineUserService.logout(StpUtil.getTokenValue());
StpUtil.logout();
return new ResponseEntity<>(HttpStatus.OK);
}
}

View File

@@ -1,19 +1,29 @@
package org.nl.modules.security.satoken;
import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.jwt.StpLogicJwtForSimple;
import cn.dev33.satoken.stp.StpLogic;
import cn.dev33.satoken.stp.StpUtil;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* @author: lyd
* @description: sa-token的配置
* @description: sa-token的配置路由拦截
* @Date: 2022-09-20
*/
//@Configuration
@Configuration
public class SaTokenConfigure implements WebMvcConfigurer {
// Sa-Token 整合 jwt (Simple 简单模式)
@Bean
public StpLogic getStpLogicJwt() {
return new StpLogicJwtForSimple();
}
String[] whitelist = new String[]{"/auth/login", "/auth/code", "/swagger-ui.html", "/swagger-resources/**",
"/webjars/**", "/*/api-docs", "/avatar/**", "/file/**", "/druid/**", "/favicon.ico",
"/*.html", "/**/*.html", "/**/*.css", "/**/*.js","/webSocket/**"};

View File

@@ -18,20 +18,16 @@ package org.nl.modules.security.service;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.nl.modules.security.service.dto.OnlineUserDto;
import org.nl.utils.EncryptUtils;
import org.nl.utils.FileUtil;
import org.nl.utils.PageUtil;
import org.nl.utils.RedisUtils;
import org.nl.modules.system.service.dto.UserDto;
import org.nl.utils.*;
import org.springframework.data.domain.Pageable;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.*;
/**
* @author Zheng Jie
@@ -44,34 +40,35 @@ public class OnlineUserService {
// private final SecurityProperties properties;
private final RedisUtils redisUtils;
// public OnlineUserService(SecurityProperties properties, RedisUtils redisUtils) {
// this.properties = properties;
// this.redisUtils = redisUtils;
// }
public OnlineUserService(RedisUtils redisUtils) {
this.redisUtils = redisUtils;
}
// public OnlineUserService(SecurityProperties properties, RedisUtils redisUtils) {
// this.properties = properties;
// this.redisUtils = redisUtils;
// }
/**
* 保存在线用户信息
* @param jwtUserDto /
* @param userDto /
* @param token /
* @param request /
*/
// public void save(UserDto userDto, String token, HttpServletRequest request){
// String dept = userDto.getUser().getDept().getName();
// String ip = StringUtils.getIp(request);
// String browser = StringUtils.getBrowser(request);
// // String address = StringUtils.getCityInfo(ip);
// String address = "局域网";
// OnlineUserDto onlineUserDto = null;
// try {
// onlineUserDto = new OnlineUserDto(userDto.getUsername(), userDto.getUser().getNickName(), dept, browser , ip, address, EncryptUtils.desEncrypt(token), new Date());
// } catch (Exception e) {
// log.error(e.getMessage(),e);
// }
// redisUtils.set(properties.getOnlineKey() + token, onlineUserDto, properties.getTokenValidityInSeconds()/1000);
// }
public void save(UserDto userDto, String token, HttpServletRequest request){
String dept = userDto.getDept().getName();
String ip = StringUtils.getIp(request);
String browser = StringUtils.getBrowser(request);
// String address = StringUtils.getCityInfo(ip);
String address = "局域网";
OnlineUserDto onlineUserDto = null;
try {
onlineUserDto = new OnlineUserDto(userDto.getUsername(), userDto.getNickName(), dept, browser , ip, address, EncryptUtils.desEncrypt(token), new Date());
} catch (Exception e) {
log.error(e.getMessage(),e);
}
redisUtils.set(token, onlineUserDto, 60*60*1000);
}
/**
* 查询全部数据
@@ -125,7 +122,7 @@ public class OnlineUserService {
*/
public void logout(String token) {
// String key = properties.getOnlineKey() + token;
// redisUtils.del(key);
redisUtils.del(token);
}
/**

View File

@@ -15,24 +15,30 @@
*/
package org.nl.modules.system.service.impl;
import cn.hutool.core.date.BetweenFormater;
import cn.hutool.core.date.BetweenFormatter;
import cn.hutool.core.date.DateUtil;
import org.nl.modules.system.service.MonitorService;
import org.nl.utils.ElAdminConstant;
import org.nl.utils.FileUtil;
import org.nl.utils.StringUtils;
import org.springframework.stereotype.Service;
import oshi.SystemInfo;
import oshi.hardware.*;
import oshi.hardware.CentralProcessor;
import oshi.hardware.GlobalMemory;
import oshi.hardware.HardwareAbstractionLayer;
import oshi.hardware.VirtualMemory;
import oshi.software.os.FileSystem;
import oshi.software.os.OSFileStore;
import oshi.software.os.OperatingSystem;
import oshi.util.FormatUtil;
import oshi.util.Util;
import java.lang.management.ManagementFactory;
import java.text.DecimalFormat;
import java.util.*;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* @author Zheng Jie
@@ -172,8 +178,8 @@ public class MonitorServiceImpl implements MonitorService {
// jvm 运行时间
long time = ManagementFactory.getRuntimeMXBean().getStartTime();
Date date = new Date(time);
// 计算项目运行时间
String formatBetween = DateUtil.formatBetween(date, new Date(),BetweenFormater.Level.HOUR);
// 计算项目运行时间 5.4.3:BetweenFormater, 5.7.14改名为BetweenFormatter
String formatBetween = DateUtil.formatBetween(date, new Date(), BetweenFormatter.Level.HOUR);
// 系统信息
systemInfo.put("os", os.toString());
systemInfo.put("day", formatBetween);

View File

@@ -148,5 +148,6 @@ sa-token:
token-style: random-128
# 是否输出操作日志
is-log: false
jwt-secret-key: opsjajisdnnca0sdkksdfaaasdfwwq
# token 前缀
# token-prefix: Bearer

10
pom.xml
View File

@@ -38,6 +38,7 @@
<druid.version>1.1.22</druid.version>
<commons-pool2.version>2.5.0</commons-pool2.version>
<mapstruct.version>1.3.1.Final</mapstruct.version>
<sa-token.version>1.31.0</sa-token.version>
</properties>
<dependencies>
@@ -69,8 +70,15 @@
<dependency>
<groupId>cn.dev33</groupId>
<artifactId>sa-token-spring-boot-starter</artifactId>
<version>1.31.0</version>
<version>${sa-token.version}</version>
</dependency>
<!-- Sa-Token 整合 jwt -->
<dependency>
<groupId>cn.dev33</groupId>
<artifactId>sa-token-jwt</artifactId>
<version>${sa-token.version}</version>
</dependency>
<!-- spring boot 缓存 -->
<dependency>