使用 Spring Security 实现自定义 OAuth2 授权

使用 Spring Security 实现自定义 OAuth2 授权

本文档旨在指导开发者如何使用 spring Security 构建自定义 OAuth2 授权服务器,重点在于实现 private_KEY_JWT 身份验证方法。通过配置 RSA 密钥、JWT 编码器和解码器,以及自定义 JWT 转换器,可以创建一个安全且灵活的授权服务器,从而为资源服务器提供有效的访问令牌。

配置 RSA 密钥

首先,需要在 application.yml 文件中配置 RSA 密钥的位置。这将允许应用程序加载用于签名和验证 JWT 的私钥和公钥。

rsa:   privateKey: classpath:certs/private.pem   publicKey: classpath:certs/public.pem

确保 certs/private.pem 和 certs/public.pem 文件存在于您的 classpath 中,并且包含有效的 PEM 格式的私钥和公钥。

接下来,创建一个配置类 RsaKeyProperties 来加载这些密钥。

import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Configuration;  import java.security.interfaces.RSAPrivateKey; import java.security.interfaces.RSAPublicKey;  @Configuration @ConfigurationProperties(prefix = "rsa") public class RsaKeyProperties {      private RSAPrivateKey privateKey;     private RSAPublicKey publicKey;      public RSAPrivateKey getPrivateKey() {         return privateKey;     }      public void setPrivateKey(RSAPrivateKey privateKey) {         this.privateKey = privateKey;     }      public RSAPublicKey getPublicKey() {         return publicKey;     }      public void setPublicKey(RSAPublicKey publicKey) {         this.publicKey = publicKey;     } }

配置 WebSecurityConfig

现在,配置 WebSecurityConfig 类来启用 OAuth2 资源服务器,并配置 JWT 编码器和解码器。

import com.nimbusds.jose.jwk.JWK; import com.nimbusds.jose.jwk.JWKSet; import com.nimbusds.jose.jwk.RSAKey; import com.nimbusds.jose.jwk.source.ImmutableJWKSet; import com.nimbusds.jose.jwk.source.JWKSource; import com.nimbusds.jose.proc.SecurityContext; import org.springframework.context.annotation.Bean; 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.annotation.web.configurers.oauth2.server.resource.OAuth2ResourceServerConfigurer; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.oauth2.jwt.JwtDecoder; import org.springframework.security.oauth2.jwt.JwtEncoder; import org.springframework.security.oauth2.jwt.NimbusJwtDecoder; import org.springframework.security.oauth2.jwt.NimbusJwtEncoder; import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;  @Configuration @EnableWebSecurity public class WebSecurityConfig {    @Bean   protected SecurityFilterChain configure(       BasicAuthenticationFilter basicAuthFilter,       HttpSecurity http) throws Exception {     return http         // Disabling csrf is safe for token-based API's         .csrf().disable()         .oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt)         .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))         .authorizeRequests(auth -> {           auth.antMatchers(                "/api/authenticate/**",                "/api/tenants/**").permitAll();           auth.antMatchers("/api/**").authenticated();            // When an exception is thrown, ErrorMvcAutoConfiguration sets stuff up so that /error is called           // internally using an anonymous user. Without this line, the call to /error fails with a 403 error           // because anonymous users would not be able to view the page.           auth.antMatchers("/error").anonymous();         })         .build();   }    @Bean   public JwtDecoder jwtDecoder(RsaKeyProperties rsaKeyProperties) {     return NimbusJwtDecoder.withPublicKey(rsaKeyProperties.getPublicKey()).build();   }    @Bean   public JwtEncoder jwtEncoder(RsaKeyProperties rsaKeyProperties) {     JWK jwk = new RSAKey.Builder(rsaKeyProperties.getPublicKey())         .privateKey(rsaKeyProperties.getPrivateKey())         .build();     JWKSource<SecurityContext> jwks = new ImmutableJWKSet<>(new JWKSet(jwk));     return new NimbusJwtEncoder(jwks);   } }

这段代码配置了以下内容:

  • 禁用 CSRF 保护,因为对于基于令牌的 API,CSRF 保护通常是不必要的。
  • 启用 OAuth2 资源服务器,并使用 JWT 进行身份验证。
  • 配置会话管理,将其设置为无状态,因为 JWT 提供了身份验证信息。
  • 配置授权规则,允许匿名访问某些端点(例如,身份验证端点),并要求对其他端点进行身份验证。
  • 创建 JwtDecoder bean,它使用公钥来验证 JWT 的签名。
  • 创建 JwtEncoder bean,它使用私钥来签名 JWT。

自定义 JWT 转换器

默认情况下,spring security 会将 “SCOPE_” 前缀添加到 JWT 中的所有权限声明中。如果您的身份验证服务器不使用此约定,则需要创建一个自定义的 JwtAuthenticationConverter 来删除此前缀。

import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter; import org.springframework.security.oauth2.server.resource.authentication.JwtGrantedAuthoritiesConverter;  @Configuration public class JwtConverterConfig {     /**      * For some reason the JwtGrantedAuthoritiesConverter defaults to adding the prefix "SCOPE_" to all      * the claims in the token, so we need to provide a JwtGrantedAuthoritiesConverter that doesn't do      * that and just passes them through.      */     @Bean     public JwtAuthenticationConverter jwtAuthenticationConverter() {         JwtGrantedAuthoritiesConverter grantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter();         grantedAuthoritiesConverter.setAuthorityPrefix("");          JwtAuthenticationConverter authConverter = new JwtAuthenticationConverter();         authConverter.setJwtGrantedAuthoritiesConverter(grantedAuthoritiesConverter);         return authConverter;     } }

这段代码创建了一个 JwtAuthenticationConverter bean,它使用一个 JwtGrantedAuthoritiesConverter,该转换器将权限前缀设置为空字符串。这将确保权限声明不会被修改。

注意事项

  • 确保您的 RSA 密钥安全地存储,并且只有授权的服务才能访问私钥。
  • 考虑使用密钥轮换策略来定期更换 RSA 密钥,以提高安全性。
  • 仔细配置授权规则,以确保只有经过身份验证的用户才能访问受保护的资源。
  • 监控您的授权服务器,以检测和防止潜在的安全漏洞。

总结

通过按照本文档中的步骤操作,您可以创建一个自定义的 OAuth2 授权服务器,该服务器使用 Spring Security 和 PRIVATE_KEY_JWT 身份验证方法。这将为您提供一个安全且灵活的解决方案,用于保护您的资源服务器。记住,安全性是一个持续的过程,因此请务必定期审查和更新您的配置,以应对新的威胁。

© 版权声明
THE END
喜欢就支持一下吧
点赞10 分享