source

Spring Boot 및 OAuth2 예제에서 기본값 이외의 암호 부여 자격 증명을 사용하는 방법

manysource 2023. 6. 24. 09:19

Spring Boot 및 OAuth2 예제에서 기본값 이외의 암호 부여 자격 증명을 사용하는 방법

는 Dave Syer의 기본적인 Spring Boot OAuth2 예를 따르고 있습니다. https://github.com/dsyer/sparklr-boot/blob/master/src/main/java/demo/Application.java

@Configuration
@ComponentScan
@EnableAutoConfiguration
@RestController
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @RequestMapping("/")
    public String home() {
        return "Hello World";
    }

    @Configuration
    @EnableResourceServer
    protected static class ResourceServer extends ResourceServerConfigurerAdapter {

        @Override
        public void configure(HttpSecurity http) throws Exception {
            // @formatter:off
            http
                // Just for laughs, apply OAuth protection to only 2 resources
                .requestMatchers().antMatchers("/","/admin/beans").and()
                .authorizeRequests()
                .anyRequest().access("#oauth2.hasScope('read')");
            // @formatter:on
        }

        @Override
        public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
            resources.resourceId("sparklr");
        }

    }

    @Configuration
    @EnableAuthorizationServer
    protected static class OAuth2Config extends AuthorizationServerConfigurerAdapter {

        @Autowired
        private AuthenticationManager authenticationManager;

        @Override
        public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
            endpoints.authenticationManager(authenticationManager);
        }

        @Override
        public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
            // @formatter:off
            clients.inMemory()
                .withClient("my-trusted-client")
                    .authorizedGrantTypes("password", "authorization_code", "refresh_token", "implicit")
                    .authorities("ROLE_CLIENT", "ROLE_TRUSTED_CLIENT")
                    .scopes("read", "write", "trust")
                    .resourceIds("sparklr")
                    .accessTokenValiditySeconds(60)
            .and()
                .withClient("my-client-with-registered-redirect")
                    .authorizedGrantTypes("authorization_code")
                    .authorities("ROLE_CLIENT")
                    .scopes("read", "trust")
                    .resourceIds("sparklr")
                    .redirectUris("http://anywhere?key=value")
            .and()
                .withClient("my-client-with-secret")
                    .authorizedGrantTypes("client_credentials", "password")
                    .authorities("ROLE_CLIENT")
                    .scopes("read")
                    .resourceIds("sparklr")
                    .secret("secret");
        // @formatter:on
        }

    }
}

이 예제는 두 가지 유형의 권한 모두에 매우 효과적이지만 암호 권한 부여는 Spring Boot 기본 보안 사용자를 사용합니다(시작 시 "기본 보안 암호 사용: 927ca0a0-634a-4671-bd1c-1323a866618a").

제 질문은 어떻게 기본 사용자 계정을 재정의하고 실제로 WebSecurityConfig에 의존합니까?다음과 같은 섹션을 추가했습니다.

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
protected static class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(AuthenticationManagerBuilder authManagerBuilder)
            throws Exception {
        authManagerBuilder.inMemoryAuthentication().withUser("user")
                .password("password").roles("USER");
    }
}

그러나 설명서에서 기본 Spring 사용자/암호를 재정의하지는 않는 것 같습니다.

이 일을 하려면 무엇이 부족할까요?

아직 2.0.3 버전이기 때문에 몇 가지를 더 시도해 보았는데 효과가 있는 것 같습니다.

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
protected static class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(AuthenticationManagerBuilder authManagerBuilder) throws Exception {
        authManagerBuilder
            .inMemoryAuthentication()
                .withUser("user1").password("password1").roles("USER").and()
                .withUser("admin1").password("password1").roles("ADMIN");
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }
}

authenticationManager bean을 명시적으로 정의함으로써 기본 제공 사용자 인증이 사라졌고 메모리에서 내 것에 의존하기 시작했습니다.인증.2.0.4가 출시되면 Dave가 위에 올린 솔루션을 다시 평가해 보겠습니다.

@Configuration
protected static class AuthenticationManagerConfiguration extends GlobalAuthenticationConfigurerAdapter {

        @Override
        public void init(AuthenticationManagerBuilder auth) throws Exception {
            auth.inMemoryAuthentication().withUser("min").password("min").roles("USER");
        }

    }

언급URL : https://stackoverflow.com/questions/26621693/how-to-get-spring-boot-and-oauth2-example-to-use-password-grant-credentials-othe