복붙노트

[SPRING] Spring Security Oauth2에서 RemoteTokenServices로 리소스 서버 구성하기

SPRING

Spring Security Oauth2에서 RemoteTokenServices로 리소스 서버 구성하기

스프링 보안 oauth2를 사용하여 권한 서버와 자원 서버를 구현하려고합니다. 지금까지 나는 인증 서버를 설정했고 jdbc 토큰 저장소를 공유하고 싶지 않기 때문에 remoteTokenService를 사용하여 토큰 @ resource server의 유효성을 검사하려고합니다. 하지만 리소스 REST 메서드에 액세스하려고 할 때마다 401 오류가 발생합니다.

XML 환경을 사용하여 프로젝트의 특성상 스프링 보안을 설정하고 있습니다. Javaconfig 및 그 잘 작동하는 다른 샘플 프로젝트를 시도했다.

다음은 리소스 서버의 구성입니다.

을 포함한다.

<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         version="3.0" metadata-complete="true">

    <display-name>rest-project</display-name>
    <description>rest project Implementation</description>

    <!--
        - Location of the XML file that defines the root application context.
        - Applied by ContextLoaderListener.
    -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring/*.xml</param-value>
    </context-param>

    <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>


    <!--
    - Servlet that dispatches request to registered handlers (Controller implementations).
    -->
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring/mvc-core-config.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

</web-app>

여기 내 security-config.xml입니다.

<beans:beans xmlns="http://www.springframework.org/schema/security"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xmlns:beans="http://www.springframework.org/schema/beans"
             xmlns:context="http://www.springframework.org/schema/context"
             xmlns:oauth2="http://www.springframework.org/schema/security/oauth2"
             xmlns:p="http://www.springframework.org/schema/p"
             xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
                        http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.2.xsd
                        http://www.springframework.org/schema/security/oauth2 http://www.springframework.org/schema/security/spring-security-oauth2-2.0.xsd">



    <http pattern="/cards/**" use-expressions="true" create-session="never" entry-point-ref="oauthAuthenticationEntryPoint">
        <anonymous enabled="false"/>
        <intercept-url pattern="/cards/**" access="isAuthenticated()" requires-channel="https"/>
        <access-denied-handler ref="oauthAccessDeniedHandler"/>
    </http>

    <oauth2:resource-server id="resourceServerFilter" resource-id="connector-bus" token-services-ref="tokenServices"/>

    <beans:bean id="tokenServices" class="org.springframework.security.oauth2.provider.token.RemoteTokenServices">
        <beans:property name="checkTokenEndpointUrl" value="https://localhost:8443/auth-server/api/oauth/check_token"/>
        <beans:property name="clientId" value="123456" />
        <beans:property name="clientSecret" value="456"/>
    </beans:bean>


    <authentication-manager>
        <authentication-provider>
            <user-service>
                <user name="jimi" password="jimispassword" authorities="ROLE_USER, ROLE_ADMIN" />
                </user-service>
        </authentication-provider>
    </authentication-manager>


    <beans:bean id="oauthAuthenticationEntryPoint" class="org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint"/>

    <beans:bean id="oauthAccessDeniedHandler" class="org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler" />
</beans:beans>

제가 여기서 누락 된 부분을 지적하십시오.

미리 감사드립니다.

해결법

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

    1.어떤 이유로 xml 구성을 원격으로 액세스 토큰의 유효성을 검사 할 수 없습니다. 하지만 oauth2 리소스 서버를 자바 구성을 사용하여 설정할 수 있었고 문제가 해결되었습니다. 아래 코드를 찾으십시오.

    어떤 이유로 xml 구성을 원격으로 액세스 토큰의 유효성을 검사 할 수 없습니다. 하지만 oauth2 리소스 서버를 자바 구성을 사용하여 설정할 수 있었고 문제가 해결되었습니다. 아래 코드를 찾으십시오.

    @Configuration
    @EnableWebSecurity
    @EnableResourceServer
    public class Oauth2ResesourceServerConfiguration  extends ResourceServerConfigurerAdapter{
    
    
        @Override
        public void configure(HttpSecurity http) throws Exception {
             http.authorizeRequests()
                    .antMatchers(HttpMethod.GET,"/api/**").access("#oauth2.hasScope('read')");
        }
    
        @Primary
        @Bean
        public RemoteTokenServices tokenService() {
            RemoteTokenServices tokenService = new RemoteTokenServices();
            tokenService.setCheckTokenEndpointUrl(
                    "https://localhost:8443/auth-server/oauth/check_token");
            tokenService.setClientId("client-id");
            tokenService.setClientSecret("client-secret");
            return tokenService;
        }
    
    
    
    }
    
  2. ==============================

    2./ oauth / check_token은 기본적으로 'denyAll'권한을 별도로 구성해야합니다. 특성에 logging.level.org.springframework.security = DEBUG를 추가하면 다음 로깅 행을 찾을 수 있습니다.

    / oauth / check_token은 기본적으로 'denyAll'권한을 별도로 구성해야합니다. 특성에 logging.level.org.springframework.security = DEBUG를 추가하면 다음 로깅 행을 찾을 수 있습니다.

    2017-09-14 14:52:01.379  INFO 15591 --- [           main] b.a.s.AuthenticationManagerConfiguration : 
    Using default security password: f1f7e508-4a30-4aad-914f-d0e90da6079a
    2017-09-14 14:52:01.775 DEBUG 15591 --- [           main] edFilterInvocationSecurityMetadataSource : Adding web access control expression 'fullyAuthenticated', for Ant [pattern='/oauth/token']
    2017-09-14 14:52:01.872 DEBUG 15591 --- [           main] edFilterInvocationSecurityMetadataSource : Adding web access control expression 'denyAll()', for Ant [pattern='/oauth/token_key']
    2017-09-14 14:52:01.879 DEBUG 15591 --- [           main] edFilterInvocationSecurityMetadataSource : Adding web access control expression 'denyAll()', for Ant [pattern='/oauth/check_token']
    

    나는 xml에서 그것을 허용하는 방법을 모르지만, javaconfig에 따라

    @Configuration
    @EnableAuthorizationServer
    public class AuthServerConfig extends AuthorizationServerConfigurerAdapter {
        @Override
        public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
            security.checkTokenAccess("isAuthenticated()");
            // security.checkTokenAccess("permitAll");
        }
    }
    

    XML을 사용하여 스프링 보안 Oauth2에서 / oauth / check_token을 활성화하는 방법을 찾았습니다. 어쩌면 도움이 될지도 모른다.

  3. ==============================

    3.https://stackoverflow.com/a/40626102/3044680에서 설명한대로 tokenService 메소드 @Primary를 작성하고 springboot 1.5를 이후부터 application.properties에 security.oauth2.resource.filter-order = 3을 추가하십시오

    https://stackoverflow.com/a/40626102/3044680에서 설명한대로 tokenService 메소드 @Primary를 작성하고 springboot 1.5를 이후부터 application.properties에 security.oauth2.resource.filter-order = 3을 추가하십시오

  4. ==============================

    4.속성 설정을 통해 간단하게이 작업을 수행 할 수 있습니다. / cards / URI에 대한 HttpSecurity 설정과 함께 application.yml에 넣어보세요.

    속성 설정을 통해 간단하게이 작업을 수행 할 수 있습니다. / cards / URI에 대한 HttpSecurity 설정과 함께 application.yml에 넣어보세요.

    security:
      oauth2:
        resource:
          token-info-uri: https://[your token validation endpoint]
          preferTokenInfo: true
    

    @EnableWebSecurity 및 @EnableResourceServer를 갖는 것이 중복됩니다. @EnableWebSecurity는 필요하지 않습니다.

  5. from https://stackoverflow.com/questions/40607535/configuring-resource-server-with-remotetokenservices-in-spring-security-oauth2 by cc-by-sa and MIT license