Spring OAuth2 Resource Server 配置

Spring OAuth2 Resource Server 是 Spring Security 中的一个模块,用于保护资源服务器上的API资源,确保只有持有合法访问令牌(access token)的客户端才能访问受保护的资源。以下是一个简化的Spring Boot应用中如何配置OAuth2 Resource Server的基本步骤和示例:

依赖引入

首先,在pom.xmlbuild.gradle中引入相应的依赖:

<!-- Maven -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
</dependency>

<!-- Gradle -->
dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-oauth2-resource-server'
}

配置资源服务器

使用JWT令牌验证

如果你的Authorization Server使用的是JWT令牌,则需要配置资源服务器来验证这种令牌:

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.oauth2.core.DelegatingOAuth2TokenValidator;
import org.springframework.security.oauth2.core.OAuth2Error;
import org.springframework.security.oauth2.jose.jws.JwsAlgorithms;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.security.oauth2.jwt.JwtValidators;
import org.springframework.security.oauth2.jwt.NimbusJwtDecoder;

import java.util.Arrays;

@Configuration
@EnableWebSecurity
public class ResourceServerConfig extends WebSecurityConfigurerAdapter {

    @Value("${spring.security.oauth2.resourceserver.jwt.issuer-uri}")
    private String issuerUri;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
            .anyRequest().authenticated()
            .and()
            .oauth2ResourceServer()
                .jwt()
                    .decoder(jwtDecoder())
                    .jwtAuthenticationConverter(jwtAuthenticationConverter());
    }

    // 创建JWT解码器
    private JwtDecoder jwtDecoder() {
        NimbusJwtDecoder jwtDecoder = NimbusJwtDecoder.withJwkSetUri(issuerUri).build();
        jwtDecoder.setJwtValidator(new DelegatingOAuth2TokenValidator<>(Arrays.asList(
            JwtValidators.createDefaultWithIssuer(issuerUri),
            new CustomJwtValidator() // 如果有自定义验证逻辑,可以添加自定义验证器
        )));
        return jwtDecoder;
    }

    // 自定义JWT转换器(如有必要)
    private Converter<Jwt, ? extends AbstractAuthenticationToken> jwtAuthenticationConverter() {
        JwtAuthenticationConverter converter = new JwtAuthenticationConverter();
        // 可能需要映射JWT声明到角色或其他属性
        OAuth2AuthenticatedPrincipal authoritiesExtractor = new AuthoritiesExtractor();
        converter.setJwtAuthoritiesConverter(authoritiesExtractor);
        return converter;
    }
    
    // 示例自定义验证器
    private static class CustomJwtValidator implements OAuth2TokenValidator<Jwt> {
        @Override
        public OAuth2TokenValidatorResult validate(Jwt jwt) {
            // 这里添加额外的JWT验证逻辑
            // ...
            return OAuth2TokenValidatorResult.success(); // 如果验证成功
        }
    }

    // 示例JWT声明转角色的提取器
    private static class AuthoritiesExtractor implements Converter<Jwt, Collection<GrantedAuthority>> {
        @Override
        public Collection<GrantedAuthority> convert(Jwt jwt) {
            // 从JWT声明中获取角色并转换成GrantedAuthority对象
            // ...
            return Arrays.asList(new SimpleGrantedAuthority("ROLE_USER")); // 示例
        }
    }
}
使用opaque令牌验证

如果使用的是opaque类型的访问令牌,则通常需要配置远程Token服务来验证:

// 配置opaque令牌验证
private RemoteTokenServices tokenService() {
    RemoteTokenServices tokenService = new RemoteTokenServices();
    tokenService.setCheckTokenEndpointUrl("http://auth-server/oauth/check_token");
    tokenService.setClientId("your-client-id");
    tokenService.setClientSecret("your-client-secret");
    return tokenService;
}

// 在configure(HttpSecurity)方法中添加配置
.and()
.oauth2ResourceServer()
.authenticationManager(new DefaultOAuth2AuthenticationManager(tokenService()));

注意事项

  • issuer-uri应该指向颁发JWT的Authorization Server的公共元数据URI,以便下载公钥进行验证。

  • 对于opaque令牌,配置RemoteTokenServices时需要替换为实际的检查令牌端点URL、客户端ID和客户端密钥。

  • 上述示例仅作演示用途,实际配置需根据具体的Authorization Server配置和需求调整。

  • JwtAuthenticationConverter用于将JWT中的声明转换为Spring Security可以识别的角色或其他权限信息。

务必按照您的OAuth2授权服务器的具体要求来适配上述配置。在现代应用中,尤其是采用OpenID Connect协议的场景下,使用JWT令牌并验证其签名及标准声明已经成为主流做法。

相关推荐

  1. Mac iTerm2 配置

    2024-04-03 02:36:03       54 阅读
  2. 12.2 【Screen配置】khronos模块配置

    2024-04-03 02:36:03       62 阅读
  3. TongRDS2.2 Center 哨兵配置

    2024-04-03 02:36:03       55 阅读
  4. Nginx实战:2-日志配置

    2024-04-03 02:36:03       55 阅读
  5. 2.windows ubuntu子系统配置

    2024-04-03 02:36:03       41 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-04-03 02:36:03       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-04-03 02:36:03       106 阅读
  3. 在Django里面运行非项目文件

    2024-04-03 02:36:03       87 阅读
  4. Python语言-面向对象

    2024-04-03 02:36:03       96 阅读

热门阅读

  1. Spring-01

    Spring-01

    2024-04-03 02:36:03      27 阅读
  2. 【nosql-redis】关于持久化的补充

    2024-04-03 02:36:03       34 阅读
  3. 关于投标的细节

    2024-04-03 02:36:03       38 阅读
  4. Nginx 配置,自定义日志格式 log_format

    2024-04-03 02:36:03       44 阅读
  5. k8s 常用指令

    2024-04-03 02:36:03       39 阅读
  6. Centos7安装Docker-Compose

    2024-04-03 02:36:03       38 阅读
  7. bash简化if-else

    2024-04-03 02:36:03       38 阅读
  8. P10086 [ROIR 2022 Day 1] 口算比赛

    2024-04-03 02:36:03       30 阅读