spring oauth2 conf for scg via java类

nvbavucw  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(422)

有没有一种方法可以通过java类来描述与下面相同的oauth2配置?有没有可能在飞行中重新装填?我从官方手册中获取了以下配置:https://spring.io/blog/2019/08/16/securing-services-with-spring-cloud-gateway

security:
    oauth2:
      client:
        registration:
          gateway:
            provider: uaa
            client-id: gateway
            client-secret: secret
            authorization-grant-type: authorization_code
            redirect-uri-template: "{baseUrl}/login/oauth2/code/{registrationId}"
            scope: openid,profile,email,resource.read
        provider:
          uaa:
            authorization-uri: http://localhost:8090/uaa/oauth/authorize
            token-uri: http://uaa:8090/uaa/oauth/token
            user-info-uri: http://uaa:8090/uaa/userinfo
            user-name-attribute: sub
            jwk-set-uri: http://uaa:8090/uaa/token_keys
ylamdve6

ylamdve61#

您可以通过注册 ClientRegistrationRepository 豆子:

@Bean
public ReactiveClientRegistrationRepository clientRegistrations() {
    ClientRegistration clientRegistration = ClientRegistration.withRegistrationId("gateway")
        .clientId("gateway")
        .clientSecret("secret")
        .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
        .redirectUriTemplate("{baseUrl}/login/oauth2/code/{registrationId}")
        .scope("openid", "profile", "email", "resource.read")
        .authorizationUri("http://localhost:8090/uaa/oauth/authorize")
        .tokenUri("http://uaa:8090/uaa/oauth/token")
        .userInfoUri("http://uaa:8090/uaa/userinfo")
        .userNameAttributeName(IdTokenClaimNames.SUB)
        .jwkSetUri("http://uaa:8090/uaa/token_keys")
        .build();
    return new InMemoryReactiveClientRegistrationRepository(clientRegistration);
}

并提供 WebSecurityConfigurerAdapter (或 SecurityFilterChain 如果您使用的是springsecurity5.4或更高版本),则可以通过 httpSecurity.oauth2Login() :

@EnableWebSecurity
public class UiSecurityConfiguration extends WebSecurityConfigurerAdapter {
    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests(authorize -> authorize
                .anyRequest().authenticated()
            )
            .oauth2Login(withDefaults());
    }
}

您可以在spring安全参考文档中找到更多信息。

相关问题