3.9.7. 创建带 OAuth2 保护的自定义控制器

如果需要创建由 OAuth2 保护的自定义 REST 控制器,可以按照以下步骤:

  1. 假设有如下 REST 控制器:

    package com.company.test.portal.myapi;
    
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    import com.company.test.services.SomeService;
    
    @RestController
    @RequestMapping("/myapi")
    public class MyController {
    
        @Inject
        protected SomeService someService;
    
        @GetMapping("/dosmth")
        public String doSmth() {
            return someService.getResult();
        }
    }
  2. web 或者 portal 模块包的根目录(com.company.test)创建一个新的 Spring 配置文件 rest-dispatcher-spring.xml。文件内容如下:

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:context="http://www.springframework.org/schema/context"
           xmlns:security="http://www.springframework.org/schema/security"
           xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-4.2.xsd">
    
        <!-- Define a base package for your controllers-->
        <context:component-scan base-package="com.company.test.portal.myapi"/>
    
        <security:http pattern="/rest/myapi/**"
                       create-session="stateless"
                       entry-point-ref="oauthAuthenticationEntryPoint"
                       xmlns="http://www.springframework.org/schema/security">
            <!-- Specify one or more protected URL patterns-->
            <intercept-url pattern="/rest/myapi/**" access="isAuthenticated()"/>
            <anonymous enabled="false"/>
            <csrf disabled="true"/>
            <cors configuration-source-ref="cuba_RestCorsSource"/>
            <custom-filter ref="resourceFilter" before="PRE_AUTH_FILTER"/>
            <custom-filter ref="cuba_AnonymousAuthenticationFilter" after="PRE_AUTH_FILTER"/>
        </security:http>
    </beans>
  3. 在模块的属性文件(比如 portal-app.properties)里定义一个累加属性 cuba.restSpringContextConfig

    cuba.restSpringContextConfig = +com/company/test/rest-dispatcher-spring.xml
  4. 这个新的控制器在 CubaRestApiServlet 上下文内运行。所以控制器内方法的 URL 以 /rest 开头,比如 doSmth()方法可以通过 URL http://localhost:8080/app-portal/rest/myapi/dosmth 来访问。

    自定义控制器的 URL 绝对不能/rest/v2 开头。