如何在2020.0.3版Spring Cloud微服务中添加基于JWT Token的安全认证
实现方案(适配Spring Cloud 2020.0.3 + Spring Security JWT)
整体逻辑为认证统一在网关层处理,内部服务调用通过请求头透传JWT完成校验,避免重复实现登录逻辑,同时保证接口访问安全。
1 依赖引入
所有需要鉴权的服务(API网关、user服务、department服务)都需要引入对应依赖,网关为响应式WebFlux环境,和后端服务依赖略有差异:
网关依赖
<!-- Spring Security响应式依赖 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <!-- JWT依赖 --> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt-api</artifactId> <version>0.11.5</version> </dependency> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt-impl</artifactId> <version>0.11.5</version> <scope>runtime</scope> </dependency> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt-jackson</artifactId> <version>0.11.5</version> <scope>runtime</scope> </dependency>
user、department服务依赖
<!-- Spring Security MVC依赖 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <!-- 同网关一致的JWT依赖 --> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt-api</artifactId> <version>0.11.5</version> </dependency> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt-impl</artifactId> <version>0.11.5</version> <scope>runtime</scope> </dependency> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt-jackson</artifactId> <version>0.11.5</version> <scope>runtime</scope> </dependency>
2 统一JWT工具类
可以抽为公共模块复用,核心实现JWT生成、解析、校验能力,密钥所有服务统一配置,不要硬编码:
import io.jsonwebtoken.*; import io.jsonwebtoken.security.Keys; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import java.security.Key; import java.util.Date; import java.util.Map; @Component public class JwtUtil { @Value("${jwt.secret}") private String secret; @Value("${jwt.expiration}") private Long expiration; private Key getSignKey() { return Keys.hmacShaKeyFor(secret.getBytes()); } // 生成JWT public String generateToken(Map<String, Object> claims, String username) { return Jwts.builder() .setClaims(claims) .setSubject(username) .setIssuedAt(new Date(System.currentTimeMillis())) .setExpiration(new Date(System.currentTimeMillis() + expiration)) .signWith(getSignKey(), SignatureAlgorithm.HS256) .compact(); } // 解析JWT获取用户名 public String extractUsername(String token) { return Jwts.parserBuilder().setSigningKey(getSignKey()).build().parseClaimsJws(token).getBody().getSubject(); } // 校验JWT有效性 public Boolean validateToken(String token, String username) { final String extractedUsername = extractUsername(token); return (extractedUsername.equals(username) && !isTokenExpired(token)); } private Boolean isTokenExpired(String token) { return Jwts.parserBuilder().setSigningKey(getSignKey()).build().parseClaimsJws(token).getBody().getExpiration().before(new Date()); } }
配置文件添加对应参数:
jwt: secret: 自定义32位以上复杂度足够的密钥 expiration: 86400000 # 1天有效期,单位毫秒
3 网关层实现
网关核心做两个逻辑:放行登录接口、其他请求校验JWT有效性,校验通过后透传JWT到下游服务:
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cloud.gateway.filter.GatewayFilterChain; import org.springframework.cloud.gateway.filter.GlobalFilter; import org.springframework.core.Ordered; import org.springframework.http.HttpStatus; import org.springframework.http.server.reactive.ServerHttpRequest; import org.springframework.http.server.reactive.ServerHttpResponse; import org.springframework.stereotype.Component; import org.springframework.util.StringUtils; import org.springframework.web.server.ServerWebExchange; import reactor.core.publisher.Mono; @Component public class JwtGlobalFilter implements GlobalFilter, Ordered { @Autowired private JwtUtil jwtUtil; // 放行的登录路径 private static final String LOGIN_PATH = "/user/login"; @Override public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { ServerHttpRequest request = exchange.getRequest(); if (request.getURI().getPath().contains(LOGIN_PATH)) { return chain.filter(exchange); } // 从请求头获取JWT String token = request.getHeaders().getFirst("Authorization"); if (StringUtils.hasText(token) && token.startsWith("Bearer ")) { token = token.substring(7); try { String username = jwtUtil.extractUsername(token); if (StringUtils.hasText(username) && jwtUtil.validateToken(token, username)) { // 校验通过,透传JWT到下游 ServerHttpRequest newRequest = request.mutate() .header("Authorization", "Bearer " + token) .build(); return chain.filter(exchange.mutate().request(newRequest).build()); } } catch (Exception e) { ServerHttpResponse response = exchange.getResponse(); response.setStatusCode(HttpStatus.UNAUTHORIZED); return response.setComplete(); } } // 无有效JWT直接返回401 ServerHttpResponse response = exchange.getResponse(); response.setStatusCode(HttpStatus.UNAUTHORIZED); return response.setComplete(); } @Override public int getOrder() { return -100; // 调高优先级,先做鉴权 } }
网关Spring Security配置:
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity; import org.springframework.security.config.web.server.ServerHttpSecurity; import org.springframework.security.web.server.SecurityWebFilterChain; @Configuration @EnableWebFluxSecurity public class GatewaySecurityConfig { @Bean public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { http.csrf().disable() .authorizeExchange() .anyExchange().permitAll(); return http.build(); } }
4 user服务实现
user服务核心实现登录接口、JWT校验逻辑:
登录接口
@RestController @RequestMapping("/user") public class UserController { @Autowired private AuthenticationManager authenticationManager; @Autowired private JwtUtil jwtUtil; @PostMapping("/login") public String login(@RequestBody LoginRequest request) { // 校验用户名密码 Authentication authentication = authenticationManager.authenticate( new UsernamePasswordAuthenticationToken(request.getUsername(), request.getPassword()) ); SecurityContextHolder.getContext().setAuthentication(authentication); // 生成JWT返回,可自定义携带权限等信息 Map<String, Object> claims = new HashMap<>(); claims.put("roles", "user"); return jwtUtil.generateToken(claims, request.getUsername()); } }
JWT拦截过滤器
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.web.authentication.WebAuthenticationDetailsSource; import org.springframework.stereotype.Component; 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 JwtAuthenticationFilter extends OncePerRequestFilter { @Autowired private JwtUtil jwtUtil; @Autowired private UserDetailsService userDetailsService; @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { String token = request.getHeader("Authorization"); if (token != null && token.startsWith("Bearer ")) { token = token.substring(7); String username = jwtUtil.extractUsername(token); if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) { UserDetails userDetails = userDetailsService.loadUserByUsername(username); if (jwtUtil.validateToken(token, userDetails.getUsername())) { UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities()); authToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); SecurityContextHolder.getContext().setAuthentication(authToken); } } } filterChain.doFilter(request, response); } }
Spring Security配置
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration; 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.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; @Configuration @EnableWebSecurity public class SecurityConfig { @Autowired private JwtAuthenticationFilter jwtAuthenticationFilter; @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http.csrf().disable() .authorizeHttpRequests() .antMatchers("/user/login").permitAll() .anyRequest().authenticated() .and() .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); http.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class); return http.build(); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Bean public AuthenticationManager authenticationManager(AuthenticationConfiguration config) throws Exception { return config.getAuthenticationManager(); } // 自行实现UserDetailsService从数据库拉取用户信息即可 }
5 department服务实现
无需登录接口,直接复用user服务的JwtAuthenticationFilter和Spring Security配置即可,配置中不需要放行登录路径,所有请求强制鉴权。
6 RestTemplate调用JWT透传
实现RestTemplate拦截器,自动将当前请求的JWT携带到下游调用请求中:
import org.springframework.http.HttpHeaders; import org.springframework.http.HttpRequest; import org.springframework.http.client.ClientHttpRequestExecution; import org.springframework.http.client.ClientHttpRequestInterceptor; import org.springframework.http.client.ClientHttpResponse; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import javax.servlet.http.HttpServletRequest; import java.io.IOException; public class JwtRestTemplateInterceptor implements ClientHttpRequestInterceptor { @Override public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException { ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); if (attributes != null) { HttpServletRequest servletRequest = attributes.getRequest(); String jwt = servletRequest.getHeader("Authorization"); if (jwt != null) { request.getHeaders().add(HttpHeaders.AUTHORIZATION, jwt); } } return execution.execute(request, body); } }
注册拦截器到RestTemplate:
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.client.RestTemplate; import java.util.Collections; @Configuration public class RestTemplateConfig { @Bean public RestTemplate restTemplate() { RestTemplate restTemplate = new RestTemplate(); restTemplate.setInterceptors(Collections.singletonList(new JwtRestTemplateInterceptor())); return restTemplate; } }
注意事项
- HS256算法要求密钥最少32位,否则会抛出异常
- 可添加内部服务IP白名单,禁止外部直接访问user、department服务
- 公共逻辑可抽取为自定义starter,避免各服务重复编码
内容的提问来源于stack exchange,提问作者Bhavik Chavda
相关产品推荐
相关产品推荐

