0

0

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

聖光之護

聖光之護

发布时间:2025-08-24 18:06:25

|

443人浏览过

|

来源于php中文网

原创

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

短视频去水印微信小程序
短视频去水印微信小程序

抖猫高清去水印微信小程序,源码为短视频去水印微信小程序全套源码,包含微信小程序端源码,服务端后台源码,支持某音、某手、某书、某站短视频平台去水印,提供全套的源码,实现功能包括:1、小程序登录授权、获取微信头像、获取微信用户2、首页包括:流量主已经对接、去水印连接解析、去水印操作指导、常见问题指引3、常用工具箱:包括视频镜头分割(可自定义时长分割)、智能分割(根据镜头自动分割)、视频混剪、模糊图片高

下载
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 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框架介绍
spring框架介绍

本专题整合了spring框架相关内容,想了解更多详细内容,请阅读专题下面的文章。

103

2025.08.06

js 字符串转数组
js 字符串转数组

js字符串转数组的方法:1、使用“split()”方法;2、使用“Array.from()”方法;3、使用for循环遍历;4、使用“Array.split()”方法。本专题为大家提供js字符串转数组的相关的文章、下载、课程内容,供大家免费下载体验。

258

2023.08.03

js截取字符串的方法
js截取字符串的方法

js截取字符串的方法有substring()方法、substr()方法、slice()方法、split()方法和slice()方法。本专题为大家提供字符串相关的文章、下载、课程内容,供大家免费下载体验。

208

2023.09.04

java基础知识汇总
java基础知识汇总

java基础知识有Java的历史和特点、Java的开发环境、Java的基本数据类型、变量和常量、运算符和表达式、控制语句、数组和字符串等等知识点。想要知道更多关于java基础知识的朋友,请阅读本专题下面的的有关文章,欢迎大家来php中文网学习。

1465

2023.10.24

字符串介绍
字符串介绍

字符串是一种数据类型,它可以是任何文本,包括字母、数字、符号等。字符串可以由不同的字符组成,例如空格、标点符号、数字等。在编程中,字符串通常用引号括起来,如单引号、双引号或反引号。想了解更多字符串的相关内容,可以阅读本专题下面的文章。

619

2023.11.24

java读取文件转成字符串的方法
java读取文件转成字符串的方法

Java8引入了新的文件I/O API,使用java.nio.file.Files类读取文件内容更加方便。对于较旧版本的Java,可以使用java.io.FileReader和java.io.BufferedReader来读取文件。在这些方法中,你需要将文件路径替换为你的实际文件路径,并且可能需要处理可能的IOException异常。想了解更多java的相关内容,可以阅读本专题下面的文章。

550

2024.03.22

php中定义字符串的方式
php中定义字符串的方式

php中定义字符串的方式:单引号;双引号;heredoc语法等等。想了解更多字符串的相关内容,可以阅读本专题下面的文章。

545

2024.04.29

go语言字符串相关教程
go语言字符串相关教程

本专题整合了go语言字符串相关教程,阅读专题下面的文章了解更多详细内容。

162

2025.07.29

高德地图升级方法汇总
高德地图升级方法汇总

本专题整合了高德地图升级相关教程,阅读专题下面的文章了解更多详细内容。

42

2026.01.16

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
10分钟--Midjourney创作自己的漫画
10分钟--Midjourney创作自己的漫画

共1课时 | 0.1万人学习

Midjourney 关键词系列整合
Midjourney 关键词系列整合

共13课时 | 0.9万人学习

AI绘画教程
AI绘画教程

共2课时 | 0.2万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

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