• 使用Token管理用户session


    起因:单点登录问题,登录时访问的是tomcat1,访问获取用户数据时访问的是tomcat2,而用户的session信息在tomcat1上存储,tomcat2并不知道该用户来过,所以在获取个人信息时从session中获取不到数据,所以就显示该用户未登录

    改用Token(JWT)来管理用户会话和认证,可以按照以下步骤进行修改:

    1. 引入JWT依赖
      首先,需要在项目的pom.xml中引入JWT相关的依赖。
    <dependency>
        <groupId>io.jsonwebtoken</groupId>
        <artifactId>jjwt</artifactId>
        <version>0.9.1</version>
    </dependency>
    
    1. 生成和验证Token
      接下来,在用户服务中实现Token的生成和验证逻辑。在用户登录成功后,生成一个JWT Token:
    import io.jsonwebtoken.Jwts;
    import io.jsonwebtoken.SignatureAlgorithm;
    
    public class JwtUtil {
        private static final String SECRET_KEY = "yourSecretKey"; // 应该放在配置文件中
        public static String generateToken(User user) {
            long now = System.currentTimeMillis();
            long exp = now + 1000 * 60 * 60; // Token有效期,例如1小时
            return Jwts.builder()
                    .setSubject(user.getMobile()) // 可以将用户的手机号作为Subject
                    .setIssuedAt(new Date(now))
                    .setExpiration(new Date(exp))
                    .signWith(SignatureAlgorithm.HS512, SECRET_KEY)
                    .compact();
        }
        //用于解析Token
        public static Claims parseToken(String token) {
            return Jwts.parser()
                    .setSigningKey(SECRET_KEY)
                    .parseClaimsJws(token)
                    .getBody();
        }
    }
    

    然后在doLogin方法中使用JwtUtil.generateToken(user)来生成Token,并将Token返回给客户端。验证Token创建一个过滤器或拦截器来解析请求中携带的Token,并进行验证:

     //JwtAuthenticationFilter - 拦截请求并验证JWT Token
    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;
    
    public class JwtAuthenticationFilter extends OncePerRequestFilter {
        @Override
        protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
                throws ServletException, IOException {
            String token = request.getHeader("Authorization");
            if (token != null && !token.isEmpty()) {
                try {
                    Claims claims = JwtUtil.parseToken(token);
                    // 这里将用户信息设置到SecurityContext或者请求中
                    request.setAttribute("user", claims.getSubject());
                } catch (Exception e) {
                    // Token验证失败的处理
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Token验证失败");
                    return;
                }
            }
            filterChain.doFilter(request, response);
        }
    }
    
    1. SecurityConfig - 配置安全性
      这里需要配置Spring Security来使用我们的JwtAuthenticationFilter:
    import org.springframework.context.annotation.Configuration;
    import org.springframework.security.config.annotation.web.builders.HttpSecurity;
    import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
    import org.springframework.security.config.http.SessionCreationPolicy;
    import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
    import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
    
    @Configuration
    @EnableWebSecurity
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
    
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
                .csrf().disable()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .addFilterBefore(new JwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)
                .authorizeRequests()
                .antMatchers("/login").permitAll()
                .anyRequest().authenticated();
        }
    }
    
  • 相关阅读:
    GoFrame学习随便记1
    单位固定资产应该怎么管理
    PHP 代码 清理 redis 消息问题
    关于Idea合并不同分支代码你怎么看
    C++使用spdlog输出日志文件
    LabVIEW专栏五、网口
    Shell系统学习之Shell条件测试,判断语句和运算符
    Shell脚本快速入门
    中霖教育:注册安全工程师考是科目有哪些?
    小微企业是怎样从客户管理系统中获益的?
  • 原文地址:https://blog.csdn.net/qq_43954910/article/details/140052042