token 无效

This commit is contained in:
2022-09-22 14:16:30 +08:00
parent b623970db8
commit 2f149911ba
14 changed files with 118 additions and 59 deletions

View File

@@ -49,17 +49,6 @@ public class GlobalExceptionHandler {
return buildResponseEntity(ApiError.error(e.getMessage()));
}
/**
* BadCredentialsException
*/
// @ExceptionHandler(BadCredentialsException.class)
// public ResponseEntity<ApiError> badCredentialsException(BadCredentialsException e){
// // 打印堆栈信息
// String message = "坏的凭证".equals(e.getMessage()) ? "用户名或密码不正确" : e.getMessage();
// log.error(message);
// return buildResponseEntity(ApiError.error(message));
// }
/**
* token 无效的异常拦截
* @param e
@@ -67,9 +56,8 @@ public class GlobalExceptionHandler {
*/
@ExceptionHandler(value = NotLoginException.class)
public ResponseEntity<ApiError> notLoginException(Exception e) {
// e.printStackTrace();
log.error(ThrowableUtil.getStackTrace(e));
return buildResponseEntity(ApiError.error("Token "));
return buildResponseEntity(ApiError.error(401,"token "));
}

View File

@@ -4,6 +4,8 @@ import cn.dev33.satoken.stp.StpUtil;
import lombok.extern.slf4j.Slf4j;
import org.nl.utils.dto.CurrentUser;
import java.util.List;
/**
* @author: lyd
* @description: 获取当前用户的信息 - 前提下在登录之后将数据存储到session
@@ -56,4 +58,17 @@ public class SecurityUtils {
}
return 0L;
}
/**
* 获取当前用户权限
* @return 权限列表
*/
public static List<String> getCurrentUserPermissions() {
CurrentUser userInfo = (CurrentUser) StpUtil.getTokenSession().get("userInfo");
List<String> permissions = userInfo.getPermissions();
if (permissions.size() > 0) {
return permissions;
}
return null;
}
}

View File

@@ -5,6 +5,8 @@ import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import lombok.Data;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
/**
* @author: lyd
@@ -19,4 +21,6 @@ public class CurrentUser implements Serializable {
private String username;
private Object user;
private List<String> permissions = new ArrayList<>();
}

View File

@@ -99,17 +99,20 @@ public class AuthorizationController {
}
StpUtil.login(userDto.getId()); // 调用satoken登录
StpUtil.getSession().set("UserDto", userDto);
// 获取权限列表 - 登录查找权限
List<String> permissionList = roleService.getPermissionList(userDto.getId().toString());
// 保存用户信息到session - 登录输入,登出删除
CurrentUser user = new CurrentUser();
user.setId(userDto.getId());
user.setUsername(userDto.getUsername());
user.setUser(userDto);
user.setPermissions(permissionList);
StpUtil.getTokenSession().set("userInfo", user);
StpUtil.getSession().set("UserDto", userDto);
// 返回一个User
// 返回 token 与 用户信息
List<String> permissionList = roleService.getPermissionList(userDto.getId().toString());
JSONObject jsonObject = new JSONObject();
jsonObject.put("roles", permissionList);
jsonObject.put("user", userDto);
@@ -128,9 +131,8 @@ public class AuthorizationController {
@GetMapping(value = "/info")
public ResponseEntity<Object> getUserInfo() {
UserDto currentUser = (UserDto) SecurityUtils.getCurrentUser();
List<String> permissionList = roleService.getPermissionList(currentUser.getId().toString());
JSONObject jsonObject = new JSONObject();
jsonObject.put("roles", permissionList);
jsonObject.put("roles", SecurityUtils.getCurrentUserPermissions());
jsonObject.put("user", currentUser);
return ResponseEntity.ok(jsonObject);
}
@@ -159,7 +161,6 @@ public class AuthorizationController {
@ApiOperation("退出登录")
@AnonymousDeleteMapping(value = "/logout")
public ResponseEntity<Object> logout(HttpServletRequest request) {
StpUtil.getTokenSession().clear(); // 清除session数据
onlineUserService.logout(StpUtil.getTokenValue());
StpUtil.logout();
return new ResponseEntity<>(HttpStatus.OK);

View File

@@ -24,7 +24,7 @@ public class SaTokenConfigure implements WebMvcConfigurer {
return new StpLogicJwtForSimple();
}
String[] whitelist = new String[]{"/auth/login", "/auth/code", "/swagger-ui.html", "/swagger-resources/**",
String[] whitelist = new String[]{"/auth/login", "/auth/code","auth/logout", "/swagger-ui.html", "/swagger-resources/**",
"/webjars/**", "/*/api-docs", "/avatar/**", "/file/**", "/druid/**", "/favicon.ico",
"/*.html", "/**/*.html", "/**/*.css", "/**/*.js","/webSocket/**"};

View File

@@ -1,9 +1,7 @@
package org.nl.modules.security.satoken;
import cn.dev33.satoken.stp.StpInterface;
import cn.dev33.satoken.stp.StpUtil;
import org.nl.modules.system.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.nl.utils.SecurityUtils;
import org.springframework.stereotype.Component;
import java.util.List;
@@ -16,14 +14,23 @@ import java.util.List;
@Component
public class StpInterfaceImpl implements StpInterface {
@Autowired
private RoleService roleService;
/**
* 用户权限获取
* @param o login存入的值此处存放用户id
* @param s
* @return
*/
@Override
public List<String> getPermissionList(Object o, String s) {
return roleService.getPermissionList((String) StpUtil.getLoginId());
return SecurityUtils.getCurrentUserPermissions();
}
/**
* 角色权限获取 - 数据库没有设计角色code因此不推荐使用角色鉴权
* @param o
* @param s
* @return
*/
@Override
public List<String> getRoleList(Object o, String s) {
return null;

View File

@@ -0,0 +1,64 @@
## 关于satoken的提示
### 本系统采用两个session存放相关信息
1、其中tokenSession存放的是
提供公共模块使用获取是Object可以直接强转此实体.
主要使用在 SecurityUtils类上使用的key: userInfo
```java
@Data
public class CurrentUser implements Serializable {
@JsonSerialize(using = ToStringSerializer.class)
private Long id;
private String username;
private Object user;
private List<String> permissions = new ArrayList<>();
}
```
2、Session存放的是UserDto,提供业务模块使用使用的key: UserDto
```java
@Getter
@Setter
public class UserDto extends BaseDTO implements Serializable {
@JsonSerialize(using = ToStringSerializer.class)
private Long id;
private Set<RoleSmallDto> roles;
private Set<JobSmallDto> jobs;
private DeptSmallDto dept;
private Long deptId;
private String username;
private String nickName;
private String email;
private String phone;
private String gender;
private String avatarName;
private String avatarPath;
private String extId;
private String extuserId;
@JsonIgnore
private String password;
private Boolean enabled;
@JsonIgnore
private Boolean isAdmin = false;
private Date pwdResetTime;
}
```

View File

@@ -15,6 +15,7 @@
*/
package org.nl.modules.system.service.impl;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
@@ -30,6 +31,7 @@ import org.nl.modules.system.service.RoleService;
import org.nl.modules.system.service.dto.RoleDto;
import org.nl.modules.system.service.dto.RoleQueryCriteria;
import org.nl.modules.system.service.dto.RoleSmallDto;
import org.nl.modules.system.service.dto.UserDto;
import org.nl.modules.system.service.mapstruct.RoleMapper;
import org.nl.modules.system.service.mapstruct.RoleSmallMapper;
import org.nl.utils.*;
@@ -183,6 +185,11 @@ public class RoleServiceImpl implements RoleService {
@Cacheable(key = "'auth:' + #p0")
public List<String> getPermissionList(String id) {
List<String> permission = new LinkedList<>();
// 查看是否为管理员
UserDto user = (UserDto) StpUtil.getSession().get("UserDto");
if (user.getIsAdmin()) { // 是管理员
permission.add("admin");
}
HashMap<String, String> map = new HashMap<>();
map.put("flag", "1");
map.put("user_id", id);

View File

@@ -6,12 +6,12 @@ spring:
druid:
db-type: com.alibaba.druid.pool.DruidDataSource
driverClassName: net.sf.log4jdbc.sql.jdbcapi.DriverSpy
# url: jdbc:log4jdbc:mysql://${DB_HOST:47.111.78.178}:${DB_PORT:3306}/${DB_NAME:nladmin}?serverTimezone=Asia/Shanghai&characterEncoding=utf8&useSSL=false&useOldAliasMetadataBehavior=true
url: jdbc:log4jdbc:mysql://${DB_HOST:127.0.0.1}:${DB_PORT:3306}/${DB_NAME:nladmin}?serverTimezone=Asia/Shanghai&characterEncoding=utf8&useSSL=false&useOldAliasMetadataBehavior=true
# username: ${DB_USER:root}
url: jdbc:log4jdbc:mysql://${DB_HOST:47.111.78.178}:${DB_PORT:3306}/${DB_NAME:nladmin}?serverTimezone=Asia/Shanghai&characterEncoding=utf8&useSSL=false&useOldAliasMetadataBehavior=true
# url: jdbc:log4jdbc:mysql://${DB_HOST:127.0.0.1}:${DB_PORT:3306}/${DB_NAME:nladmin}?serverTimezone=Asia/Shanghai&characterEncoding=utf8&useSSL=false&useOldAliasMetadataBehavior=true
username: ${DB_USER:root}
# password: ${DB_PWD:P@ssw0rd}
password: ${DB_PWD:12356}
# username: ${DB_USER:root}
password: ${DB_PWD:P@ssw0rd}
# password: ${DB_PWD:12356}
# 初始连接数
initial-size: 5
# 最小连接数

View File

@@ -17,6 +17,7 @@ router.beforeEach((to, from, next) => {
}
NProgress.start()
if (getToken()) {
// debugger
// 已登录且要跳转的页面是登录页
if (to.path === '/login') {
next({ path: '/' })

View File

@@ -1,3 +0,0 @@
<template>
<router-view />
</template>

View File

@@ -1,15 +0,0 @@
<template>
<div style="padding:30px;">
<el-input v-model="input" placeholder="请输入内容" />
</div>
</template>
<script>
export default {
name: 'Test',
data() {
return {
input: ''
}
}
}
</script>

View File

@@ -1,5 +0,0 @@
<template>
<div style="padding:30px;">
<el-input v-model="input" placeholder="请输入内容2" />
</div>
</template>

View File

@@ -1,5 +0,0 @@
<template>
<div style="padding:30px;">
<el-alert :closable="false" title="二级菜单" />
</div>
</template>