Skip to content

基于 Spring Boot 3 + Spring Authorization Server 1.5.0 使用 Maven 构建的 Spring OAuth2 授权和认证服务示例

License

Notifications You must be signed in to change notification settings

chensoul/spring-security6-oauth2-samples

Repository files navigation

Build with Maven Code QL License

spring-security6-oauth2-samples

video_spider

基于 Spring Boot 3 + Spring Authorization Server 1.5.0 使用 Maven 构建的 Spring OAuth2 授权和认证服务示例。

要求

运行此服务器至少需要 Java 17 运行时,因为本项目使用了 Spring Boot 3.x。

关键技术:

  • Spring Boot 3.5.0
  • Spring Framework 6.2.7
  • Spring Security 6.5.0
  • Spring Security OAuth2 Authorization Server 1.5.0
  • Spring Security OAuth2 Resource Server 1.5.0

使用

通过运行类 com.chensoul.AuthServerApplication 启动授权服务器。

http://localhost:9000/.well-known/openid-configuration 查找 OAuth2/OIDC 配置,以配置您的客户端和资源服务器。

以下是最重要的配置设置:

Configuration Parameter Value
issuer http://localhost:9000
authorization_endpoint http://localhost:9000/oauth2/authorize
token_endpoint http://localhost:9000/oauth2/token
jwks_uri http://localhost:9000/oauth2/jwks
userinfo_endpoint http://localhost:9000/userinfo
introspection_endpoint http://localhost:9000/oauth2/introspect

使用 OpenSSL 生成非对称密钥

如果您选择生成自己的密钥,请按照以下步骤操作:

  • 进入资源目录:

    cd src/main/resources
  • 生成密钥对: 此行使用 OpenSSL(openssl genrsa)生成长度为 2048 位的 RSA 私钥。 然后指定将保存生成的私钥的输出文件(-out keypair.pem)。 其意义在于创建一个可以用于非对称密码学中的加密、解密以及数字签名的私钥。

    openssl genrsa -out keypair.pem 2048   
  • 从私钥生成公钥: 此命令从先前生成的私钥(openssl rsa)中提取公钥。 它从 -in keypair.pem 指定的文件中读取私钥,并将相应的公钥(-pubout)输出到名为 publicKey.pem 的文件中。 其意义在于从私钥中获取公钥,公钥可以公开共享,用于加密和验证,同时保持私钥安全。

    openssl rsa -in keypair.pem -pubout -out publicKey.pem
  • 将私钥(keypair.pem)格式化为支持的格式(PKCS8 格式): 此行将第一步生成的私钥(keypair.pem)转换为 PKCS#8 格式,这是私钥编码(openssl pkcs8)的广泛使用的标准。 它指定输入密钥格式为 PEM(-inform PEM),输出密钥格式也为 PEM(-outform PEM),并且不应用加密(-nocrypt)。 生成的私钥保存在名为 private.pem 的文件中。 其意义在于将私钥转换为可在不同的加密系统和应用程序之间互操作的标准格式。

    openssl pkcs8 -topk8 -inform PEM -outform PEM -nocrypt -in keypair.pem -out privateKey.pem

    如果您想在使用 OpenSSL 导出私钥时对其进行加密,只需在 openssl pkcs8 命令中省略 -nocrypt 选项即可。这样,OpenSSL 就会提示您输入用于加密私钥的密码 注意:加密私钥会增加一层额外的安全性,但这也意味着无论何时您想使用私钥进行加密操作,您都需要提供密码。

  • 从配置文件中添加这些密钥的引用,以便在 RSAKeyRecord 中使用。

    @ConfigurationProperties(prefix = "jwt")
    public record RSAKeyRecord (RSAPublicKey rsaPublicKey, RSAPrivateKey rsaPrivateKey){
    
    }
  • 配置文件中添加以下内容。

  jwt:
    rsa-private-key: classpath:certs/privateKey.pem
    rsa-public-key: classpath:certs/publicKey.pem

参考资料

工具

License

Apache 2.0 licensed

About

基于 Spring Boot 3 + Spring Authorization Server 1.5.0 使用 Maven 构建的 Spring OAuth2 授权和认证服务示例

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors 3

  •  
  •  
  •  

Languages