欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 财经 > 创投人物 > 使用Token管理用户session

使用Token管理用户session

2024/10/24 17:33:55 来源:https://blog.csdn.net/qq_43954910/article/details/140052042  浏览:    关键词:使用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();}//用于解析Tokenpublic 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 {@Overrideprotected 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 {@Overrideprotected 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();}
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com