完成jwt拦截器和从token中获取当前登录的用户id
目前除登录以外的所有操作都会经过拦截器,可以在WebConfig中设置拦截器忽略的接口 获取用户id不需要手动输入了,直接通过UserContext获取当前登录的用户id 为动态删除,动态修改等我负责的功能添加身份验证,用户id不匹配则会跳出异常
This commit is contained in:
31
src/main/java/com/bao/dating/config/WebConfig.java
Normal file
31
src/main/java/com/bao/dating/config/WebConfig.java
Normal file
@@ -0,0 +1,31 @@
|
|||||||
|
package com.bao.dating.config;
|
||||||
|
|
||||||
|
|
||||||
|
import com.bao.dating.interceptor.TokenInterceptor;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
|
||||||
|
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||||
|
|
||||||
|
@Configuration
|
||||||
|
public class WebConfig implements WebMvcConfigurer {
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private TokenInterceptor tokenInterceptor;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 添加拦截器到Spring MVC配置中
|
||||||
|
* @param registry 拦截器注册中心
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
public void addInterceptors(InterceptorRegistry registry) {
|
||||||
|
//注册自定义拦截器对象
|
||||||
|
registry.addInterceptor(tokenInterceptor)
|
||||||
|
// 拦截所有请求
|
||||||
|
.addPathPatterns("/**")
|
||||||
|
// 忽略的接口
|
||||||
|
.excludePathPatterns(
|
||||||
|
"/user/login"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
33
src/main/java/com/bao/dating/context/UserContext.java
Normal file
33
src/main/java/com/bao/dating/context/UserContext.java
Normal file
@@ -0,0 +1,33 @@
|
|||||||
|
package com.bao.dating.context;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 用户上下文类
|
||||||
|
* @author lenovo
|
||||||
|
*/
|
||||||
|
public class UserContext {
|
||||||
|
|
||||||
|
private static final ThreadLocal<Long> userHolder = new ThreadLocal<>();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 设置当前线程的用户ID
|
||||||
|
* @param userId 用户ID
|
||||||
|
*/
|
||||||
|
public static void setUserId(Long userId) {
|
||||||
|
userHolder.set(userId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取当前线程的用户ID
|
||||||
|
* @return 当前用户ID,如果未设置则返回null
|
||||||
|
*/
|
||||||
|
public static Long getUserId() {
|
||||||
|
return userHolder.get();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 清除当前线程的用户ID
|
||||||
|
*/
|
||||||
|
public static void clear() {
|
||||||
|
userHolder.remove();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -34,13 +34,12 @@ public class PostController {
|
|||||||
/**
|
/**
|
||||||
* 发布动态接口 - JSON格式请求
|
* 发布动态接口 - JSON格式请求
|
||||||
* @param postDTO 动态信息
|
* @param postDTO 动态信息
|
||||||
* @param userId 用户ID
|
|
||||||
* @return 发布的动态对象
|
* @return 发布的动态对象
|
||||||
*/
|
*/
|
||||||
@PostMapping(consumes = "application/json")
|
@PostMapping(consumes = "application/json")
|
||||||
public Result<Post> createPostJson(@RequestBody PostRequestDTO postDTO, @RequestParam Long userId) {
|
public Result<Post> createPostJson(@RequestBody PostRequestDTO postDTO) {
|
||||||
// 调用 Service 层处理发布动态业务逻辑
|
// 调用 Service 层处理发布动态业务逻辑
|
||||||
Post result = postService.createPost(userId, postDTO);
|
Post result = postService.createPost(postDTO);
|
||||||
return Result.success(ResultCode.SUCCESS_REVIEW, "动态发布成功,等待审核。", result);
|
return Result.success(ResultCode.SUCCESS_REVIEW, "动态发布成功,等待审核。", result);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,70 @@
|
|||||||
|
package com.bao.dating.interceptor;
|
||||||
|
|
||||||
|
import javax.servlet.http.HttpServletRequest;
|
||||||
|
import javax.servlet.http.HttpServletResponse;
|
||||||
|
|
||||||
|
import com.bao.dating.context.UserContext;
|
||||||
|
import com.bao.dating.util.JwtUtil;
|
||||||
|
import io.jsonwebtoken.Claims;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
import org.springframework.web.method.HandlerMethod;
|
||||||
|
import org.springframework.web.servlet.HandlerInterceptor;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* HttpToken拦截器类
|
||||||
|
* 用于拦截请求并验证JWT token的有效性,同时从token中解析用户信息
|
||||||
|
*/
|
||||||
|
@Slf4j
|
||||||
|
@Component
|
||||||
|
public class TokenInterceptor implements HandlerInterceptor {
|
||||||
|
/**
|
||||||
|
* 在请求处理之前进行拦截
|
||||||
|
* 从请求头或URL参数中获取token,验证其有效性,并将用户ID保存到ThreadLocal中
|
||||||
|
* @param request HTTP请求对象
|
||||||
|
* @param response HTTP响应对象
|
||||||
|
* @param handler 处理器
|
||||||
|
* @return 验证通过返回true,否则返回false
|
||||||
|
* @throws Exception 异常
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
|
||||||
|
|
||||||
|
//判断当前拦截到的是Controller的方法还是其他资源
|
||||||
|
if (!(handler instanceof HandlerMethod)) {
|
||||||
|
//当前拦截到的不是动态方法,直接放行
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
// 从 header 获取 token
|
||||||
|
String token = request.getHeader("token");
|
||||||
|
|
||||||
|
try {
|
||||||
|
log.info("jwt校验:{}", token);
|
||||||
|
// 解析 token
|
||||||
|
String userId = JwtUtil.getSubjectFromToken(token);
|
||||||
|
log.info("用户:{}", userId);
|
||||||
|
// 保存 userId 到 ThreadLocal
|
||||||
|
UserContext.setUserId(Long.valueOf(userId));
|
||||||
|
return true;
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("Token 校验失败: {}", e.getMessage());
|
||||||
|
response.setStatus(401);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 在请求完成之后执行清理工作
|
||||||
|
* 清除保存在ThreadLocal中的用户ID,防止内存泄漏
|
||||||
|
* @param request HTTP请求对象
|
||||||
|
* @param response HTTP响应对象
|
||||||
|
* @param handler 处理器
|
||||||
|
* @param ex 异常对象
|
||||||
|
* @throws Exception 异常
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
|
||||||
|
UserContext.clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -17,11 +17,10 @@ public interface PostService {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* 创建动态
|
* 创建动态
|
||||||
* @param userId 用户ID
|
|
||||||
* @param postRequestDTO 动态数据传输对象
|
* @param postRequestDTO 动态数据传输对象
|
||||||
* @return 创建的动态对象
|
* @return 创建的动态对象
|
||||||
*/
|
*/
|
||||||
Post createPost(Long userId, PostRequestDTO postRequestDTO);
|
Post createPost(PostRequestDTO postRequestDTO);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 批量删除动态
|
* 批量删除动态
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ package com.bao.dating.service.impl;
|
|||||||
|
|
||||||
import com.bao.dating.common.aliyun.GreenImageScan;
|
import com.bao.dating.common.aliyun.GreenImageScan;
|
||||||
import com.bao.dating.common.aliyun.GreenTextScan;
|
import com.bao.dating.common.aliyun.GreenTextScan;
|
||||||
|
import com.bao.dating.context.UserContext;
|
||||||
import com.bao.dating.mapper.PostMapper;
|
import com.bao.dating.mapper.PostMapper;
|
||||||
import com.bao.dating.pojo.dto.PostRequestDTO;
|
import com.bao.dating.pojo.dto.PostRequestDTO;
|
||||||
import com.bao.dating.pojo.entity.Post;
|
import com.bao.dating.pojo.entity.Post;
|
||||||
@@ -85,15 +86,15 @@ public class PostServiceImpl implements PostService {
|
|||||||
/**
|
/**
|
||||||
* 创建动态
|
* 创建动态
|
||||||
*
|
*
|
||||||
* @param userId 用户ID
|
|
||||||
* @param postRequestDTO 动态数据传输对象
|
* @param postRequestDTO 动态数据传输对象
|
||||||
* @return 创建的动态对象
|
* @return 创建的动态对象
|
||||||
*/
|
*/
|
||||||
@Override
|
@Override
|
||||||
public Post createPost(Long userId, PostRequestDTO postRequestDTO) {
|
public Post createPost(PostRequestDTO postRequestDTO) {
|
||||||
|
|
||||||
// 创建动态对象
|
// 创建动态对象
|
||||||
Post post = new Post();
|
Post post = new Post();
|
||||||
|
Long userId = UserContext.getUserId();
|
||||||
post.setUserId(userId);
|
post.setUserId(userId);
|
||||||
post.setContent(postRequestDTO.getContent());
|
post.setContent(postRequestDTO.getContent());
|
||||||
post.setTags(postRequestDTO.getTags());
|
post.setTags(postRequestDTO.getTags());
|
||||||
@@ -165,6 +166,20 @@ public class PostServiceImpl implements PostService {
|
|||||||
@Override
|
@Override
|
||||||
@Transactional(rollbackFor = Exception.class)
|
@Transactional(rollbackFor = Exception.class)
|
||||||
public int deletePostById(List<Long> postIds) {
|
public int deletePostById(List<Long> postIds) {
|
||||||
|
// 判断用户权限
|
||||||
|
Long userId = UserContext.getUserId();
|
||||||
|
|
||||||
|
// 遍历所有要删除的帖子ID,验证权限
|
||||||
|
for (Long postId : postIds) {
|
||||||
|
Post post = postMapper.selectById(postId);
|
||||||
|
if (post == null) {
|
||||||
|
throw new RuntimeException("动态不存在");
|
||||||
|
}
|
||||||
|
// 验证用户权限
|
||||||
|
if (post.getUserId() == null || !post.getUserId().equals(userId)) {
|
||||||
|
throw new RuntimeException("无权限删除此动态");
|
||||||
|
}
|
||||||
|
}
|
||||||
// 批量删除动态
|
// 批量删除动态
|
||||||
return postMapper.deletePostByIds(postIds);
|
return postMapper.deletePostByIds(postIds);
|
||||||
}
|
}
|
||||||
@@ -177,11 +192,15 @@ public class PostServiceImpl implements PostService {
|
|||||||
*/
|
*/
|
||||||
@Override
|
@Override
|
||||||
public PostEditVO getPostForEdit(Long postId) {
|
public PostEditVO getPostForEdit(Long postId) {
|
||||||
|
|
||||||
Post post = postMapper.selectById(postId);
|
Post post = postMapper.selectById(postId);
|
||||||
if (post == null) {
|
if (post == null) {
|
||||||
throw new RuntimeException("动态不存在");
|
throw new RuntimeException("动态不存在");
|
||||||
}
|
}
|
||||||
|
// 判断用户权限
|
||||||
|
Long userId = UserContext.getUserId();
|
||||||
|
if (post.getUserId() == null || !post.getUserId().equals(userId)){
|
||||||
|
throw new RuntimeException("无权限查看此动态");
|
||||||
|
}
|
||||||
PostEditVO postEditVO = new PostEditVO();
|
PostEditVO postEditVO = new PostEditVO();
|
||||||
BeanUtils.copyProperties(post, postEditVO);
|
BeanUtils.copyProperties(post, postEditVO);
|
||||||
return postEditVO;
|
return postEditVO;
|
||||||
@@ -200,6 +219,11 @@ public class PostServiceImpl implements PostService {
|
|||||||
if (post == null) {
|
if (post == null) {
|
||||||
throw new RuntimeException("动态不存在");
|
throw new RuntimeException("动态不存在");
|
||||||
}
|
}
|
||||||
|
// 判断用户权限
|
||||||
|
Long userId = UserContext.getUserId();
|
||||||
|
if (post.getUserId() == null || !post.getUserId().equals(userId)){
|
||||||
|
throw new RuntimeException("无权限修改此动态");
|
||||||
|
}
|
||||||
post.setContent(postRequestDTO.getContent());
|
post.setContent(postRequestDTO.getContent());
|
||||||
if (postRequestDTO.getMediaOssKeys() != null && !postRequestDTO.getMediaOssKeys().isEmpty()) {
|
if (postRequestDTO.getMediaOssKeys() != null && !postRequestDTO.getMediaOssKeys().isEmpty()) {
|
||||||
post.setMediaOssKeys(postRequestDTO.getMediaOssKeys());
|
post.setMediaOssKeys(postRequestDTO.getMediaOssKeys());
|
||||||
|
|||||||
@@ -10,9 +10,6 @@ import com.bao.dating.util.MD5Util;
|
|||||||
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
import java.util.HashMap;
|
|
||||||
import java.util.Map;
|
|
||||||
|
|
||||||
@Service
|
@Service
|
||||||
public class UserServiceImpl implements UserService {
|
public class UserServiceImpl implements UserService {
|
||||||
|
|
||||||
@@ -30,13 +27,12 @@ public class UserServiceImpl implements UserService {
|
|||||||
if (user == null){
|
if (user == null){
|
||||||
throw new RuntimeException("用户不存在");
|
throw new RuntimeException("用户不存在");
|
||||||
}
|
}
|
||||||
// 密码加密
|
// 密码校验
|
||||||
boolean match = MD5Util.verifyWithSalt(
|
boolean match = MD5Util.verifyWithSalt(
|
||||||
userLoginDTO.getPassword(),
|
userLoginDTO.getPassword(),
|
||||||
user.getSalt(),
|
user.getSalt(),
|
||||||
user.getPasswordHash()
|
user.getPasswordHash()
|
||||||
);
|
);
|
||||||
// 密码校验
|
|
||||||
if (!match){
|
if (!match){
|
||||||
throw new RuntimeException("密码错误");
|
throw new RuntimeException("密码错误");
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user