복붙노트

[SPRING] 스프링 보안 OAuth2는 보안을 결정합니까?

SPRING

스프링 보안 OAuth2는 보안을 결정합니까?

나는 JHipster에서 영감을 얻어 Dave Syer의 가이드를 사용하여 OAuth2 인증 서버를 구현하려고 노력했습니다. 그러나 나는 그것이 어떻게 함께 작동 하는지를 알 수 없다.

ResourceServerConfigurerAdapter를 사용할 때 WebSecurityConfigurerAdapter를 사용하는 보안 설정을 덮어 쓰는 것 같습니다.

@Configuration
@EnableResourceServer
public class OAuth2ResourceConfig extends ResourceServerConfigurerAdapter {

    private TokenExtractor tokenExtractor = new BearerTokenExtractor();

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
                .addFilterAfter(contextClearer(), AbstractPreAuthenticatedProcessingFilter.class)
                .authorizeRequests()
                .anyRequest().authenticated().and().httpBasic();
    }

    private OncePerRequestFilter contextClearer() {
        return new OncePerRequestFilter() {
            @Override
            protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
                if (tokenExtractor.extract(request) == null) {
                    SecurityContextHolder.clearContext();
                }
                filterChain.doFilter(request, response);
            }
        };
    }

@Component
public class CustomWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {

    private final AuthenticationManager authenticationManager;

    @Autowired
    public CustomWebSecurityConfigurerAdapter(AuthenticationManager authenticationManager) {
        this.authenticationManager = authenticationManager;
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
                .parentAuthenticationManager(authenticationManager);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .formLogin()
                    .loginPage("/login").permitAll()
                .and()
                    .authorizeRequests().antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
                .and()
                    .requestMatchers().antMatchers("/login", "/oauth/authorize", "/oauth/confirm_access")
                .and()
                    .authorizeRequests().anyRequest().authenticated();
    }
}

이것은 몇 가지 다른 예제에서 가져온 코드이므로 잘 혼합하지 않을 수도 있습니다. 하지만 OAuth2 (멋진 문서가있는 Spring Boot와는 달리)에 대한 좋은 문서 / 예제 목록을 찾을 수 없으므로 모든 방법이 함께 어울리는 지 이해하는 데 문제가 있습니다. ResourceFormConfigurerAdapter에 loginForm을 추가하지 않으면 권한이 부여되지 않습니다. 하지만 WebSecurityConfigurererAdapter에서 permitAll ()으로 정의했습니다.

다음은 AuthorizationServerConfigurerAdapter입니다.

@Configuration
@EnableAuthorizationServer
public class OAuth2AuthorizationConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private JwtAccessTokenConverter jwtAccessTokenConverter;

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                .withClient("acme")
                .secret("acmesecret")
                .authorizedGrantTypes("authorization_code", "refresh_token",
                        "password").scopes("openid");
    }

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

    @Override
    public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
        oauthServer.tokenKeyAccess("permitAll()").checkTokenAccess("isAuthenticated()");
    }
}

내가 잘못한 건 뭐니? ResourceServerConfigurerAdapter 내의 모든 보안을 설정해야합니까? 더 이상 WebSecurityConfigurerAdapter가 필요합니까?

누군가가 가이드, 튜토리얼, 블로그 또는 그 밖의 방법으로 내 머리를 감싸는 데 도움이 될만한 정보를 알고 있다면 크게 감사 할 것입니다.

친절 하네, 케네스.

해결법

  1. ==============================

    1./ authorize 엔드 포인트를 보호하고 사용자가 인증 할 수있는 방법을 제공하려면 WebSecurityConfigurerAdapter가 필요합니다. 스프링 부트 애플리케이션은 당신을 위해 그것을 할 것입니다 (HTTP Basic Auth를 가진 자체 WebSecurityConfigurerAdapter를 추가함으로써). 기본적으로 order = 0 인 필터 체인을 만들고 요청 일치자를 제공하지 않는 한 모든 리소스를 보호합니다. @EnableResourceServer는 비슷한 기능을 수행하지만 추가되는 필터 체인은 기본적으로 order = 3에 있습니다. WebSecurityConfigurerAdapter에는 @Order (100) 주석이 있습니다. 먼저 ResourceServer가 점검 (인증)되고 WebSecurityConfigureAdapter의 enxtension에서 점검이 점검됩니다.

    / authorize 엔드 포인트를 보호하고 사용자가 인증 할 수있는 방법을 제공하려면 WebSecurityConfigurerAdapter가 필요합니다. 스프링 부트 애플리케이션은 당신을 위해 그것을 할 것입니다 (HTTP Basic Auth를 가진 자체 WebSecurityConfigurerAdapter를 추가함으로써). 기본적으로 order = 0 인 필터 체인을 만들고 요청 일치자를 제공하지 않는 한 모든 리소스를 보호합니다. @EnableResourceServer는 비슷한 기능을 수행하지만 추가되는 필터 체인은 기본적으로 order = 3에 있습니다. WebSecurityConfigurerAdapter에는 @Order (100) 주석이 있습니다. 먼저 ResourceServer가 점검 (인증)되고 WebSecurityConfigureAdapter의 enxtension에서 점검이 점검됩니다.

    구성이 정상적으로 보이지 않습니다 (로그인 체인이 우선하지만 작은 요청 집합에만 해당).

  2. from https://stackoverflow.com/questions/28537181/spring-security-oauth2-which-decides-security by cc-by-sa and MIT license