起因:单点登录问题,登录时访问的是tomcat1,访问获取用户数据时访问的是tomcat2,而用户的session信息在tomcat1上存储,tomcat2并不知道该用户来过,所以在获取个人信息时从session中获取不到数据,所以就显示该用户未登录
改用Token(JWT)来管理用户会话和认证,可以按照以下步骤进行修改:
- 引入JWT依赖
首先,需要在项目的pom.xml中引入JWT相关的依赖。
<dependency><groupId>io.jsonwebtoken</groupId><artifactId>jjwt</artifactId><version>0.9.1</version>
</dependency>
- 生成和验证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);}
}
- 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();}
}