| package com.oep.backend.config.filter; |
| |
| |
| |
| import com.oep.backend.mapper.AccountMapper; |
| import com.oep.backend.pojo.Account; |
| import com.oep.backend.serviceImpl.utils.UserDetailsImpl; |
| import com.oep.backend.utils.JwtUtil; |
| import io.jsonwebtoken.Claims; |
| import org.jetbrains.annotations.NotNull; |
| import org.springframework.beans.factory.annotation.Autowired; |
| import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; |
| import org.springframework.security.core.context.SecurityContextHolder; |
| import org.springframework.stereotype.Component; |
| import org.springframework.util.StringUtils; |
| import org.springframework.web.filter.OncePerRequestFilter; |
| |
| import javax.servlet.FilterChain; |
| import javax.servlet.ServletException; |
| import javax.servlet.http.HttpServletRequest; |
| import javax.servlet.http.HttpServletResponse; |
| import java.io.IOException; |
| |
| @Component |
| public class JwtAuthenticationTokenFilter extends OncePerRequestFilter { |
| @Autowired |
| private AccountMapper userMapper; |
| |
| @Override |
| protected void doFilterInternal(HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull FilterChain filterChain) throws ServletException, IOException { |
| String token = request.getHeader("Authorization"); |
| |
| if (!StringUtils.hasText(token) || !token.startsWith("Bearer ")) { |
| filterChain.doFilter(request, response); |
| return; |
| } |
| |
| token = token.substring(7); |
| |
| String userid; |
| try { |
| Claims claims = JwtUtil.parseJWT(token); |
| userid = claims.getSubject(); |
| } catch (Exception e) { |
| throw new RuntimeException(e); |
| } |
| |
| Account account = userMapper.selectById(Integer.parseInt(userid)); |
| |
| if (account == null) { |
| throw new RuntimeException("用户名未登录"); |
| } |
| |
| UserDetailsImpl loginUser = new UserDetailsImpl(account); |
| UsernamePasswordAuthenticationToken authenticationToken = |
| new UsernamePasswordAuthenticationToken(loginUser, null, null); |
| |
| SecurityContextHolder.getContext().setAuthentication(authenticationToken); |
| |
| filterChain.doFilter(request, response); |
| } |
| } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)