복붙노트

[SPRING] 봄 보안, Cors 오류 때 Oauth2 사용

SPRING

봄 보안, Cors 오류 때 Oauth2 사용

내 oauth / 토큰 끝점을 쿼리하는 동안 오류가 발생했습니다.

내 리소스에 대해 활성화 된 cors를 구성했으나 모든 리소스를 허용하려고 시도했지만 아무 것도 작동하지 않았습니다.

vendor.js:1837 ERROR SyntaxError: Unexpected token u in JSON at position 0
    at JSON.parse (<anonymous>)
    at CatchSubscriber.selector (app.js:7000)
    at CatchSubscriber.error (vendor.js:36672)
    at MapSubscriber.Subscriber._error (vendor.js:282)
    at MapSubscriber.Subscriber.error (vendor.js:256)
    at XMLHttpRequest.onError (vendor.js:25571)
    at ZoneDelegate.invokeTask (polyfills.js:15307)
    at Object.onInvokeTask (vendor.js:4893)
    at ZoneDelegate.invokeTask (polyfills.js:15306)
    at Zone.runTask (polyfills.js:15074)
defaultErrorLogger @ vendor.js:1837
ErrorHandler.handleError @ vendor.js:1897
next @ vendor.js:5531
schedulerFn @ vendor.js:4604
SafeSubscriber.__tryOrUnsub @ vendor.js:392
SafeSubscriber.next @ vendor.js:339
Subscriber._next @ vendor.js:279
Subscriber.next @ vendor.js:243
Subject.next @ vendor.js:14989
EventEmitter.emit @ vendor.js:4590
NgZone.triggerError @ vendor.js:4962
onHandleError @ vendor.js:4923
ZoneDelegate.handleError @ polyfills.js:15278
Zone.runTask @ polyfills.js:15077
ZoneTask.invoke @ polyfills.js:15369

우편 배달부는 모든 것이 완벽하게 작동합니다.

나의 보안 설정 :

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedHeaders("*")
                .allowedMethods("*")
                .allowCredentials(true);
    }
}

또한 허용 된 출처에 http : // localhost : 1111을 추가하려고 시도했습니다.

우편 배달부의 코드 :

require 'uri'
require 'net/http'

url = URI("http://localhost:8080/oauth/token")

http = Net::HTTP.new(url.host, url.port)

request = Net::HTTP::Post.new(url)
request["content-type"] = 'application/x-www-form-urlencoded'
request["authorization"] = 'Basic Y2hhdHRpbzpzZWNyZXRzZWNyZXQ='
request["cache-control"] = 'no-cache'
request["postman-token"] = 'daf213da-e231-a074-02dc-795a149a3bb2'
request.body = "grant_type=password&username=yevhen%40gmail.com&password=qwerty"

response = http.request(request)
puts response.read_body

해결법

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

    1.고생을 많이 한 후에 인증 서버가 자체적으로 구성하고 다른 솔루션을 찾지 못했기 때문에 WebSecurityConfigurerAdapter 클래스의 메서드 configure (WebSecurity 웹)를 재정의했습니다. 또한 모든 "/ oauth / token"Http.Options 메소드를 허용해야합니다. 나의 방법 :

    고생을 많이 한 후에 인증 서버가 자체적으로 구성하고 다른 솔루션을 찾지 못했기 때문에 WebSecurityConfigurerAdapter 클래스의 메서드 configure (WebSecurity 웹)를 재정의했습니다. 또한 모든 "/ oauth / token"Http.Options 메소드를 허용해야합니다. 나의 방법 :

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers(HttpMethod.OPTIONS, "/oauth/token");
    }
    

    이 후 HTTP 상태를 OK로 설정하기 위해 cors 필터를 추가해야합니다. 이제 우리는 Http.Options 메소드를 인터셉트 할 수 있습니다.

    @Component
    @Order(Ordered.HIGHEST_PRECEDENCE)
    @WebFilter("/*")
    public class CorsFilter implements Filter {
    
        public CorsFilter() {
        }
    
        @Override
        public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
            final HttpServletResponse response = (HttpServletResponse) res;
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
            response.setHeader("Access-Control-Allow-Headers", "x-requested-with, authorization");
            response.setHeader("Access-Control-Max-Age", "3600");
            if ("OPTIONS".equalsIgnoreCase(((HttpServletRequest) req).getMethod())) {
                response.setStatus(HttpServletResponse.SC_OK);
            } else {
                chain.doFilter(req, res);
            }
        }
    
        @Override
        public void destroy() {
        }
    
        @Override
        public void init(FilterConfig config) throws ServletException {
        }
    }
    
  2. ==============================

    2.토큰 엔드 포인트에서 모든 OPTIONS 요청에 대한 보안을 끄지 않고 Spring Security 5 및 Spring Security OAuth 2.3.5에서 401 오류를 수정하는 방법을 찾았습니다. AuthorizationServerSecurityConfigurer를 통해 토큰 엔드 포인트에 보안 필터를 추가 할 수 있다는 것을 깨달았습니다. CorsFilter를 추가하려고 시도했는데 효과가있었습니다. 이 방법으로 가지고있는 유일한 문제는 스프링 MVC의 CorsRegistry를 활용할 수 없다는 것입니다. 누구든지 CorsRegistry를 사용하는 방법을 알아낼 수 있다면 알려주십시오.

    토큰 엔드 포인트에서 모든 OPTIONS 요청에 대한 보안을 끄지 않고 Spring Security 5 및 Spring Security OAuth 2.3.5에서 401 오류를 수정하는 방법을 찾았습니다. AuthorizationServerSecurityConfigurer를 통해 토큰 엔드 포인트에 보안 필터를 추가 할 수 있다는 것을 깨달았습니다. CorsFilter를 추가하려고 시도했는데 효과가있었습니다. 이 방법으로 가지고있는 유일한 문제는 스프링 MVC의 CorsRegistry를 활용할 수 없다는 것입니다. 누구든지 CorsRegistry를 사용하는 방법을 알아낼 수 있다면 알려주십시오.

    내 솔루션에 대한 샘플 구성을 아래에 복사했습니다.

    import org.springframework.context.annotation.Configuration;
    import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
    import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
    import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
    import org.springframework.web.cors.CorsConfiguration;
    import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
    import org.springframework.web.filter.CorsFilter;
    
    @Configuration
    @EnableAuthorizationServer
    public static class AuthServerConfiguration extends AuthorizationServerConfigurerAdapter {
        //... other config
    
        @Override
        public void configure(AuthorizationServerSecurityConfigurer security) {
            //... other config
    
            UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
            CorsConfiguration config = new CorsConfiguration();
            config.applyPermitDefaultValues();
    
            // Maybe there's a way to use config from AuthorizationServerEndpointsConfigurer endpoints?
            source.registerCorsConfiguration("/oauth/token", config);
            CorsFilter filter = new CorsFilter(source);
            security.addTokenEndpointAuthenticationFilter(filter);
        }
    }
    
    
  3. from https://stackoverflow.com/questions/44625488/spring-security-cors-error-when-enable-oauth2 by cc-by-sa and MIT license