获取用户信息并跳转

This commit is contained in:
Bunny 2023-12-27 16:16:31 +08:00
parent 3f0d6c7d60
commit 503bd0db69
14 changed files with 250 additions and 31 deletions

View File

@ -2,6 +2,13 @@
<profile version="1.0">
<option name="myName" value="Project Default" />
<inspection_tool class="Deprecation" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="IncorrectHttpHeaderInspection" enabled="true" level="WARNING" enabled_by_default="true">
<option name="customHeaders">
<set>
<option value="token" />
</set>
</option>
</inspection_tool>
<inspection_tool class="RawUseOfParameterizedType" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="ThrowablePrintStackTrace" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="UNCHECKED_WARNING" enabled="false" level="WARNING" enabled_by_default="false" />

View File

@ -5,7 +5,20 @@
</component>
<component name="ChangeListManager">
<list default="true" id="6ee93b58-a7e0-45a0-9e98-4c363b192afb" name="Changes" comment="获取用户信息-未测试">
<change afterPath="$PROJECT_DIR$/spzx-common/common-service/src/main/java/cn/bunny/anno/EnableUserLoginAuthInterceptor.java" afterDir="false" />
<change afterPath="$PROJECT_DIR$/spzx-common/common-service/src/main/java/cn/bunny/config/UserWebMvcConfiguration.java" afterDir="false" />
<change afterPath="$PROJECT_DIR$/spzx-common/common-service/src/main/java/cn/bunny/interceptor/UserLoginAuthInterceptor.java" afterDir="false" />
<change afterPath="$PROJECT_DIR$/spzx-server-gateway/src/main/java/cn/bunny/getway/filter/AuthGlobalFilter.java" afterDir="false" />
<change beforePath="$PROJECT_DIR$/.idea/inspectionProfiles/Project_Default.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/inspectionProfiles/Project_Default.xml" afterDir="false" />
<change beforePath="$PROJECT_DIR$/.idea/workspace.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/workspace.xml" afterDir="false" />
<change beforePath="$PROJECT_DIR$/spzx-common/common-service/pom.xml" beforeDir="false" afterPath="$PROJECT_DIR$/spzx-common/common-service/pom.xml" afterDir="false" />
<change beforePath="$PROJECT_DIR$/spzx-common/common-util/src/main/java/cn/bunny/common/AuthContextUtil.java" beforeDir="false" afterPath="$PROJECT_DIR$/spzx-common/common-util/src/main/java/cn/bunny/common/AuthContextUtil.java" afterDir="false" />
<change beforePath="$PROJECT_DIR$/spzx-server-gateway/pom.xml" beforeDir="false" afterPath="$PROJECT_DIR$/spzx-server-gateway/pom.xml" afterDir="false" />
<change beforePath="$PROJECT_DIR$/spzx-server-gateway/src/main/resources/application-dev.yml" beforeDir="false" afterPath="$PROJECT_DIR$/spzx-server-gateway/src/main/resources/application-dev.yml" afterDir="false" />
<change beforePath="$PROJECT_DIR$/spzx-service/service-product/src/main/resources/application-dev.yml" beforeDir="false" afterPath="$PROJECT_DIR$/spzx-service/service-product/src/main/resources/application-dev.yml" afterDir="false" />
<change beforePath="$PROJECT_DIR$/spzx-service/service-user/src/main/java/cn/bunny/user/User.java" beforeDir="false" afterPath="$PROJECT_DIR$/spzx-service/service-user/src/main/java/cn/bunny/user/User.java" afterDir="false" />
<change beforePath="$PROJECT_DIR$/spzx-service/service-user/src/main/java/cn/bunny/user/service/impl/UserinfoServiceImpl.java" beforeDir="false" afterPath="$PROJECT_DIR$/spzx-service/service-user/src/main/java/cn/bunny/user/service/impl/UserinfoServiceImpl.java" afterDir="false" />
<change beforePath="$PROJECT_DIR$/spzx-service/service-user/src/main/resources/application-dev.yml" beforeDir="false" afterPath="$PROJECT_DIR$/spzx-service/service-user/src/main/resources/application-dev.yml" afterDir="false" />
</list>
<option name="SHOW_DIALOG" value="false" />
<option name="HIGHLIGHT_CONFLICTS" value="true" />
@ -16,8 +29,8 @@
<option name="RECENT_TEMPLATES">
<list>
<option value="Interface" />
<option value="Class" />
<option value="mybatis-mapper" />
<option value="Class" />
</list>
</option>
</component>
@ -79,7 +92,7 @@
"project.structure.proportion": "0.15",
"project.structure.side.proportion": "0.2",
"rearrange.code.on.save": "true",
"settings.editor.selected.configurable": "actions.on.save",
"settings.editor.selected.configurable": "preferences.pluginManager",
"vue.rearranger.settings.migration": "true"
},
"keyToStringList": {
@ -113,19 +126,6 @@
</option>
</component>
<component name="RunManager" selected="Spring Boot.User">
<configuration name="MangerApplication" type="SpringBootApplicationConfigurationType" factoryName="Spring Boot" temporary="true" nameIsGenerated="true">
<module name="spzx-manager" />
<option name="SPRING_BOOT_MAIN_CLASS" value="cn.bunny.MangerApplication" />
<extension name="coverage">
<pattern>
<option name="PATTERN" value="cn.bunny.*" />
<option name="ENABLED" value="true" />
</pattern>
</extension>
<method v="2">
<option name="Make" enabled="true" />
</method>
</configuration>
<configuration name="ProductApplication" type="SpringBootApplicationConfigurationType" factoryName="Spring Boot" temporary="true" nameIsGenerated="true">
<module name="service-product" />
<option name="SPRING_BOOT_MAIN_CLASS" value="cn.bunny.web.product.ProductApplication" />
@ -168,9 +168,8 @@
<recent_temporary>
<list>
<item itemvalue="Spring Boot.User" />
<item itemvalue="Spring Boot.ServerGetWayApplication" />
<item itemvalue="Spring Boot.MangerApplication" />
<item itemvalue="Spring Boot.ProductApplication" />
<item itemvalue="Spring Boot.ServerGetWayApplication" />
</list>
</recent_temporary>
</component>
@ -184,7 +183,8 @@
<updated>1703487755445</updated>
<workItem from="1703487757122" duration="903000" />
<workItem from="1703488670206" duration="5932000" />
<workItem from="1703549556395" duration="26380000" />
<workItem from="1703549556395" duration="26425000" />
<workItem from="1703654409796" duration="8864000" />
</task>
<task id="LOCAL-00001" summary="前端接口初始化;显示商品页面">
<option name="closed" value="true" />
@ -282,12 +282,39 @@
<option name="project" value="LOCAL" />
<updated>1703581022155</updated>
</task>
<option name="localTasksCounter" value="13" />
<task id="LOCAL-00013" summary="获取用户信息-未测试">
<option name="closed" value="true" />
<created>1703581032554</created>
<option name="number" value="00013" />
<option name="presentableId" value="LOCAL-00013" />
<option name="project" value="LOCAL" />
<updated>1703581032554</updated>
</task>
<task id="LOCAL-00014" summary="获取用户信息-未测试">
<option name="closed" value="true" />
<created>1703581061973</created>
<option name="number" value="00014" />
<option name="presentableId" value="LOCAL-00014" />
<option name="project" value="LOCAL" />
<updated>1703581061973</updated>
</task>
<option name="localTasksCounter" value="15" />
<servers />
</component>
<component name="TypeScriptGeneratedFilesManager">
<option name="version" value="3" />
</component>
<component name="Vcs.Log.Tabs.Properties">
<option name="TAB_STATES">
<map>
<entry key="MAIN">
<value>
<State />
</value>
</entry>
</map>
</option>
</component>
<component name="VcsManagerConfiguration">
<MESSAGE value="前端接口初始化;显示商品页面" />
<MESSAGE value="解决跨域;修改MySQL语法错误;获取分类树形数据" />

View File

@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
@ -44,6 +44,23 @@
<artifactId>spring-boot-starter-data-redis</artifactId>
<scope>provided</scope>
</dependency>
<!-- spring boot web开发所需要的起步依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<scope>provided</scope>
</dependency>
<!-- openfeign依赖 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,16 @@
package cn.bunny.anno;
import cn.bunny.config.UserWebMvcConfiguration;
import cn.bunny.interceptor.UserLoginAuthInterceptor;
import org.springframework.context.annotation.Import;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(value = RetentionPolicy.RUNTIME)
@Target(value = ElementType.TYPE)
@Import(value = {UserLoginAuthInterceptor.class, UserWebMvcConfiguration.class})
public @interface EnableUserLoginAuthInterceptor {
}

View File

@ -0,0 +1,17 @@
package cn.bunny.config;
import cn.bunny.interceptor.UserLoginAuthInterceptor;
import jakarta.annotation.Resource;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
public class UserWebMvcConfiguration implements WebMvcConfigurer {
@Resource
private UserLoginAuthInterceptor userLoginAuthInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(userLoginAuthInterceptor)
.addPathPatterns("/api/**");
}
}

View File

@ -0,0 +1,24 @@
package cn.bunny.interceptor;
import cn.bunny.common.AuthContextUtil;
import cn.bunny.common.spzx.model.entity.user.UserInfo;
import com.alibaba.fastjson.JSON;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;
public class UserLoginAuthInterceptor implements HandlerInterceptor {
@Resource
private RedisTemplate redisTemplate;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// 如果token不为空那么此时验证token的合法性
String userInfoJSON = (String) redisTemplate.opsForValue().get("user:spzx:" + request.getHeader("token"));
AuthContextUtil.setUserInfo(JSON.parseObject(userInfoJSON, UserInfo.class));
return true;
}
}

View File

@ -1,8 +1,10 @@
package cn.bunny.common;
import cn.bunny.common.spzx.model.entity.system.SysUser;
import cn.bunny.common.spzx.model.entity.user.UserInfo;
public class AuthContextUtil {
private static final ThreadLocal<UserInfo> userInfoThreadLocal = new ThreadLocal<>();
// 创建一个ThreadLocal对象
private static final ThreadLocal<SysUser> threadLocal = new ThreadLocal<>();
@ -21,4 +23,19 @@ public class AuthContextUtil {
public static void remove() {
threadLocal.remove();
}
// 定义获取数据的方法
public static UserInfo getUserInfo() {
return userInfoThreadLocal.get();
}
// 定义存储数据的静态方法
public static void setUserInfo(UserInfo userInfo) {
userInfoThreadLocal.set(userInfo);
}
// 删除数据的方法
public static void removeUserInfo() {
userInfoThreadLocal.remove();
}
}

View File

@ -1,4 +1,4 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
@ -19,6 +19,10 @@
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>

View File

@ -0,0 +1,85 @@
package cn.bunny.getway.filter;
import cn.bunny.common.spzx.model.entity.user.UserInfo;
import cn.bunny.common.spzx.model.vo.common.Result;
import cn.bunny.common.spzx.model.vo.common.ResultCodeEnum;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import java.nio.charset.StandardCharsets;
import java.util.List;
@Slf4j
@Component
public class AuthGlobalFilter implements GlobalFilter, Ordered {
@Resource
private RedisTemplate redisTemplate;
private AntPathMatcher antPathMatcher;
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
// 获取当前请求路径
ServerHttpRequest request = exchange.getRequest();
String path = request.getURI().getPath();
// 判断路径是否满足 /api/**/auth/**
if (antPathMatcher.match("/api/**/auth/**", path)) {
// 登录校验
UserInfo userInfo = this.getUserinfo(request);
if (userInfo == null) {
ServerHttpResponse response = exchange.getResponse();
return out(response, ResultCodeEnum.LOGIN_AUTH);
}
}
return chain.filter(exchange);
}
@Override
public int getOrder() {
return 0;
}
private UserInfo getUserinfo(ServerHttpRequest request) {
String token = "";
List<String> tokenList = request.getHeaders().get("token");
if (tokenList != null) {
token = tokenList.get(0);
}
if (StringUtils.hasText(token)) {
String userJson = (String) redisTemplate.opsForValue().get("user:spzx" + token);
if (StringUtils.hasText(userJson)) {
return null;
} else {
return JSON.parseObject(userJson, UserInfo.class);
}
}
return null;
}
private Mono<Void> out(ServerHttpResponse response, ResultCodeEnum resultCodeEnum) {
Result result = Result.build(null, resultCodeEnum);
byte[] bits = JSONObject.toJSONString(result).getBytes(StandardCharsets.UTF_8);
DataBuffer buffer = response.bufferFactory().wrap(bits);
// 指定编码否则在浏览器中会中文乱码
response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
return response.writeWith(Mono.just(buffer));
}
}

View File

@ -6,7 +6,7 @@ spring:
cloud:
nacos:
discovery:
server-addr: 192.168.2.156:8848
server-addr: 192.168.2.82:8848
gateway:
discovery:
locator:
@ -37,7 +37,10 @@ spring:
url: jdbc:mysql://60.204.230.80:3306/db_spzx?characterEncoding=utf-8&useSSL=false&allowPublicKeyRetrieval=true
username: root
password: "02120212"
data:
redis:
host: 192.168.2.82
port: 6379
mybatis:
config-location: classpath:mybatis-config.xml
mapper-locations: classpath:/mapper/*/*.xml

View File

@ -7,7 +7,7 @@ spring:
cloud:
nacos:
discovery:
server-addr: 192.168.2.156:8848
server-addr: 192.168.2.82:8848
datasource:
type: com.zaxxer.hikari.HikariDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
@ -17,7 +17,7 @@ spring:
data:
redis:
port: 6379
host: 192.168.2.156
host: 192.168.2.82
mybatis:
config-location: classpath:mybatis-config.xml

View File

@ -1,11 +1,13 @@
package cn.bunny.user;
import cn.bunny.anno.EnableUserLoginAuthInterceptor;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
@SpringBootApplication
@ComponentScan(basePackages = {"cn.bunny"})
@EnableUserLoginAuthInterceptor
public class User {
public static void main(String[] args) {
SpringApplication.run(User.class, args);

View File

@ -9,12 +9,12 @@ import cn.bunny.common.spzx.model.vo.h5.UserInfoVo;
import cn.bunny.user.mapper.UserinfoMapper;
import cn.bunny.user.service.UserinfoService;
import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.common.utils.StringUtils;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
@ -31,13 +31,13 @@ public class UserinfoServiceImpl implements UserinfoService {
public UserInfoVo getCurrentUserInfo(String token) {
// 从Redis根据token获取用户信息
String userJson = (String) redisTemplate.opsForValue().get("user:spzx" + token);
if (StringUtils.hasText(userJson)) {
if (!StringUtils.hasText(userJson)) {
throw new BunnyException(ResultCodeEnum.LOGIN_ERROR);
}
UserInfo userinfo = JSON.parseObject(userJson, UserInfo.class);
UserInfoVo userInfoVo = new UserInfoVo();
assert userinfo != null;
UserInfoVo userInfoVo = new UserInfoVo();
BeanUtils.copyProperties(userinfo, userInfoVo);
return userInfoVo;

View File

@ -7,7 +7,7 @@ spring:
cloud:
nacos:
discovery:
server-addr: 192.168.2.156:8848
server-addr: 192.168.2.82:8848
datasource:
@ -19,7 +19,7 @@ spring:
data:
redis:
port: 6379
host: 192.168.2.156
host: 192.168.2.82
mybatis:
config-location: classpath:mybatis-config.xml