使用 Spring Security 资源服务器来保护 Spring Cloud 微服务

服务器
以Spring Security实战干货的DEMO为例子,原本它是一个单体应用,认证和授权都在一个应用中使用。改造为独立的服务后,原本的认证就要剥离出去(这个后续再讲如何实现),服务将只保留基于用户凭证(JWT)的访问控制功能。

[[429798]]

我在上一篇对资源服务器进行了简单的阐述,让大家对资源服务器的概念有了简单的认识,今天我将用实际例子来演示单体应用改造为Spring Cloud微服务时的资源服务器实现。

资源服务器改造

以Spring Security实战干货的DEMO为例子,原本它是一个单体应用,认证和授权都在一个应用中使用。改造为独立的服务后,原本的认证就要剥离出去(这个后续再讲如何实现),服务将只保留基于用户凭证(JWT)的访问控制功能。接下来我们将一步步来实现该能力。

所需依赖

在Spring Security的基础上,我们需要加入新的依赖来支持OAuth2 Resource Server和JWT。我们需要引入下面几个依赖库:

  1. <dependency> 
  2.      <groupId>org.springframework.boot</groupId> 
  3.      <artifactId>spring-boot-starter-security</artifactId> 
  4.  </dependency> 
  5.  <!-- 资源服务器 --> 
  6.  <dependency> 
  7.      <groupId>org.springframework.security</groupId> 
  8.      <artifactId>spring-security-oauth2-resource-server</artifactId> 
  9.  </dependency> 
  10. <!-- jose --> 
  11.  <dependency> 
  12.      <groupId>org.springframework.security</groupId> 
  13.      <artifactId>spring-security-oauth2-jose</artifactId> 
  14.  </dependency> 

Spring Security 5.x 移除了OAuth2.0授权服务器,保留了OAuth2.0资源服务器。

JWT解码

要校验JWT就必须实现对JWT的解码功能,在Spring Security OAuth2 Resource Server模块中,默认提供了解码器,这个解码器需要调用基于:

  1. spring.security.oauth2.resourceserver 

配置下的元数据来生成解码配置,这里的配置大部分是调用授权服务器开放的well-known断点,包含了解析验证JWT一系列参数:

  • jwkSetUri 一般是授权服务器提供的获取JWK配置的well-known端点,用来校验JWT Token。
  • jwsAlgorithm 指定jwt使用的算法,默认 RSA-256。
  • issuerUri 获取OAuth2.0 授权服务器元数据的端点。
  • publicKeyLocation 用于解码的公钥路径,作为资源服务器来说将只能持有公钥,不应该持有私钥。

为了实现平滑过渡,默认的配置肯定不能用了,需要定制化一个JWT解码器。接下来我们一步步来实现它。

分离公私钥

资源服务器只能保存公钥,所以需要从之前的jks文件中导出一个公钥。

  1. keytool -export -alias felordcn -keystore <jks证书全路径>  -file <导出cer的全路径> 

例如:

  1. keytool -export -alias felordcn -keystore D:\keystores\felordcn.jks  -file d:\keystores\publickey.cer 

把分离的cer公钥文件放到原来jks文件的路径下面,资源服务器不再保存jks。

自定义jwt解码器

spring-security-oauth2-jose是Spring Security的jose规范依赖。我将根据该类库来实现自定义的JWT解码器。

  1. /** 
  2.  * 基于Nimbus的jwt解码器,并增加了一些自定义校验策略 
  3.  * 
  4.  * @param validator the validator 
  5.  * @return the jwt decoder 
  6.  */ 
  7. @SneakyThrows 
  8. @Bean 
  9. public JwtDecoder jwtDecoder(@Qualifier("delegatingTokenValidator") DelegatingOAuth2TokenValidator<Jwt> validator) { 
  10.     CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); 
  11.     // 从classpath路径读取cer公钥证书来配置解码器 
  12.     ClassPathResource resource = new ClassPathResource(this.jwtProperties.getCertInfo().getPublicKeyLocation()); 
  13.     Certificate certificate = certificateFactory.generateCertificate(resource.getInputStream()); 
  14.     PublicKey publicKey = certificate.getPublicKey(); 
  15.     NimbusJwtDecoder nimbusJwtDecoder = NimbusJwtDecoder.withPublicKey((RSAPublicKey) publicKey).build(); 
  16.     nimbusJwtDecoder.setJwtValidator(validator); 
  17.     return nimbusJwtDecoder; 

上面的解码器基于我们的公钥证书,同时我还自定义了一些校验策略。不得不说Nimbus的jwt类库比jjwt要好用的多。

自定义资源服务器配置

接下来配置资源服务器。

核心流程和概念

资源服务器其实也就是配置了一个过滤器BearerTokenAuthenticationFilter来拦截并验证Bearer Token。验证通过而且权限符合要求就放行,不通过就不放行。

和之前不太一样的是验证成功后凭据不再是UsernamePasswordAuthenticationToken而是JwtAuthenticationToken:

  1. @Transient 
  2. public class JwtAuthenticationToken extends AbstractOAuth2TokenAuthenticationToken<Jwt> { 
  3.  
  4.  private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID; 
  5.  
  6.  private final String name
  7.  
  8.  /** 
  9.   * Constructs a {@code JwtAuthenticationToken} using the provided parameters. 
  10.   * @param jwt the JWT 
  11.   */ 
  12.  public JwtAuthenticationToken(Jwt jwt) { 
  13.   super(jwt); 
  14.   this.name = jwt.getSubject(); 
  15.  } 
  16.  
  17.  /** 
  18.   * Constructs a {@code JwtAuthenticationToken} using the provided parameters. 
  19.   * @param jwt the JWT 
  20.   * @param authorities the authorities assigned to the JWT 
  21.   */ 
  22.  public JwtAuthenticationToken(Jwt jwt, Collection<? extends GrantedAuthority> authorities) { 
  23.   super(jwt, authorities); 
  24.   this.setAuthenticated(true); 
  25.   this.name = jwt.getSubject(); 
  26.  } 
  27.  
  28.  /** 
  29.   * Constructs a {@code JwtAuthenticationToken} using the provided parameters. 
  30.   * @param jwt the JWT 
  31.   * @param authorities the authorities assigned to the JWT 
  32.   * @param name the principal name 
  33.   */ 
  34.  public JwtAuthenticationToken(Jwt jwt, Collection<? extends GrantedAuthority> authorities, String name) { 
  35.   super(jwt, authorities); 
  36.   this.setAuthenticated(true); 
  37.   this.name = name
  38.  } 
  39.  
  40.  @Override 
  41.  public Map<String, Object> getTokenAttributes() { 
  42.   return this.getToken().getClaims(); 
  43.  } 
  44.  
  45.  /** 
  46.   * jwt 中的sub 值  用户名比较合适 
  47.   */ 
  48.  @Override 
  49.  public String getName() { 
  50.   return this.name
  51.  } 
  52.  

这个我们改造的时候要特别注意,尤其是从SecurityContext获取的时候用户凭证信息的时候。

资源管理器配置

从Spring Security 5的某版本开始不需要再集成适配类了,只需要这样就能配置Spring Security,资源管理器也是这样:

  1. @Bean 
  2. SecurityFilterChain jwtSecurityFilterChain(HttpSecurity http) throws Exception { 
  3.     return http.authorizeRequests(request -> request.anyRequest() 
  4.                     .access("@checker.check(authentication,request)")) 
  5.             .exceptionHandling() 
  6.             .accessDeniedHandler(new SimpleAccessDeniedHandler()) 
  7.             .authenticationEntryPoint(new SimpleAuthenticationEntryPoint()) 
  8.             .and() 
  9.             .oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt) 
  10.             .build(); 

这里只需要声明使用JWT校验的资源服务器,同时配置好定义的401端点和403处理器即可。这里我加了基于SpEL的动态权限控制,这个再以往都讲过了,这里不再赘述。

JWT个性化解析

从JWT Token中解析数据并生成JwtAuthenticationToken的操作是由JwtAuthenticationConverter来完成的。你可以定制这个转换器来实现一些个性化功能。比如默认情况下解析出来的权限都是带SCOPE_前缀的,而项目用ROLE_,你就可以通过这个类兼容一下老项目。

  1.      @Bean 
  2.     JwtAuthenticationConverter jwtAuthenticationConverter() { 
  3.         JwtAuthenticationConverter jwtAuthenticationConverter = new JwtAuthenticationConverter(); 
  4.         JwtGrantedAuthoritiesConverter jwtGrantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter(); 
  5. //        如果不按照规范  解析权限集合Authorities 就需要自定义key 
  6. //        jwtGrantedAuthoritiesConverter.setAuthoritiesClaimName("scopes"); 
  7. //        OAuth2 默认前缀是 SCOPE_     Spring Security 是 ROLE_ 
  8.         jwtGrantedAuthoritiesConverter.setAuthorityPrefix(""); 
  9.         jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(jwtGrantedAuthoritiesConverter); 
  10.         // 设置jwt中用户名的key  默认就是sub  你可以自定义 
  11.         jwtAuthenticationConverter.setPrincipalClaimName(JwtClaimNames.SUB); 
  12.         return jwtAuthenticationConverter; 
  13.     } 

这里基本上就改造完成了。你受保护的资源API将由Bearer Token来保护。

在实际生产中建议把资源服务器封装为依赖集成到需要保护资源的的服务中即可。

附加说明

为了测试资源服务器,假设我们有一个颁发令牌的授权服务器。这里简单模拟了一个发令牌的方法用来获取Token:

  1. /** 
  2.  * 资源服务器不应该生成JWT 但是为了测试 假设这是个认证服务器 
  3.  */ 
  4. @SneakyThrows 
  5. @Test 
  6. public void imitateAuthServer() { 
  7.  
  8.     JwtEncoder jwsEncoder = new NimbusJwsEncoder(jwkSource()); 
  9.  
  10.     JwtTokenGenerator jwtTokenGenerator = new JwtTokenGenerator(jwsEncoder); 
  11.     OAuth2AccessTokenResponse oAuth2AccessTokenResponse = jwtTokenGenerator.tokenResponse(); 
  12.  
  13.     System.out.println("oAuth2AccessTokenResponse = " + oAuth2AccessTokenResponse.getAccessToken().getTokenValue()); 
  14.  
  15.     @SneakyThrows 
  16. private JWKSource<SecurityContext> jwkSource() { 
  17.     ClassPathResource resource = new ClassPathResource("felordcn.jks"); 
  18.     KeyStore jks = KeyStore.getInstance("jks"); 
  19.     String pass = "123456"
  20.     char[] pem = pass.toCharArray(); 
  21.     jks.load(resource.getInputStream(), pem); 
  22.  
  23.     RSAKey rsaKey = RSAKey.load(jks, "felordcn", pem); 
  24.  
  25.     JWKSet jwkSet = new JWKSet(rsaKey); 
  26.     return new ImmutableJWKSet<>(jwkSet); 

相关的DEMO已经上传,你可以通过关注公众号“码农小胖哥” 回复 resourceserver获取资源服务器实现的DEMO。

本文转载自微信公众号「码农小胖哥」,可以通过以下二维码关注。转载本文请联系码农小胖哥公众号。

 

责任编辑:武晓燕 来源: 码农小胖哥
相关推荐

2024-02-06 18:05:54

微服务SpringCloud

2017-07-03 09:50:07

Spring Clou微服务架构

2017-07-04 17:35:46

微服务架构Spring Clou

2017-09-05 14:05:11

微服务spring clou路由

2021-08-03 22:51:05

Keycloak授权服务器

2018-06-01 23:08:01

Spring Clou微服务服务器

2021-12-14 06:59:39

微服务Kubernetes架构

2017-06-26 09:06:10

Spring Clou微服务架构

2018-07-09 09:27:10

Spring Clou微服务架构

2017-09-04 16:15:44

服务网关架构

2023-12-19 09:33:40

微服务监控

2017-08-10 11:15:05

Spring Clou微服务架构

2017-08-09 15:50:47

Spring Clou微服务架构

2017-12-20 15:37:39

Spring Clou微服务架构

2023-11-09 08:31:56

Spring微服务网关

2020-06-30 07:58:39

微服务Spring BootCloud

2021-10-18 06:54:45

应用服务器微服务

2023-03-20 08:00:00

公共云开发Spring Clo

2017-06-25 13:33:25

Spring Clou微服务架构

2018-03-02 16:11:29

Spring Clou分布式服务跟踪
点赞
收藏

51CTO技术栈公众号