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

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

  • 假设有如下 REST 控制器:
  1. package com.company.test.portal.myapi;
  2. import org.springframework.web.bind.annotation.GetMapping;
  3. import org.springframework.web.bind.annotation.RequestMapping;
  4. import org.springframework.web.bind.annotation.RestController;
  5. import com.company.test.services.SomeService;
  6. @RestController
  7. @RequestMapping("/myapi")
  8. public class MyController {
  9. @Inject
  10. protected SomeService someService;
  11. @GetMapping("/dosmth")
  12. public String doSmth() {
  13. return someService.getResult();
  14. }
  15. }
  • web 或者 portal 模块包的根目录(com.company.test)创建一个新的 Spring 配置文件 rest-dispatcher-spring.xml。文件内容如下:
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. xmlns:security="http://www.springframework.org/schema/security"
  6. 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">
  7. <!-- Define a base package for your controllers-->
  8. <context:component-scan base-package="com.company.test.portal.myapi"/>
  9. <security:http pattern="/rest/myapi/**"
  10. create-session="stateless"
  11. entry-point-ref="oauthAuthenticationEntryPoint"
  12. xmlns="http://www.springframework.org/schema/security">
  13. <!-- Specify one or more protected URL patterns-->
  14. <intercept-url pattern="/rest/myapi/**" access="isAuthenticated()"/>
  15. <anonymous enabled="false"/>
  16. <csrf disabled="true"/>
  17. <cors configuration-source-ref="cuba_RestCorsSource"/>
  18. <custom-filter ref="resourceFilter" before="PRE_AUTH_FILTER"/>
  19. <custom-filter ref="cuba_AnonymousAuthenticationFilter" after="PRE_AUTH_FILTER"/>
  20. </security:http>
  21. </beans>
  • 在模块的属性文件(比如 portal-app.properties)里定义一个可追加的属性 cuba.restSpringContextConfig
  1. cuba.restSpringContextConfig = +com/company/test/rest-dispatcher-spring.xml

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