首页 > Java > java教程 > 正文

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

聖光之護
发布: 2025-08-24 18:06:25
原创
441人浏览过

使用 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 编码器和解码器。

Zyro AI Background Remover
Zyro AI Background Remover

Zyro推出的AI图片背景移除工具

Zyro AI Background Remover 55
查看详情 Zyro AI Background Remover
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 身份验证方法。这将为您提供一个安全且灵活的解决方案,用于保护您的资源服务器。记住,安全性是一个持续的过程,因此请务必定期审查和更新您的配置,以应对新的威胁。

以上就是使用 Spring Security 实现自定义 OAuth2 授权的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号