4.8.2.7. Creating Custom OAuth2 Protected Controllers
If you need to create a custom REST controller protected with the OAuth2 authentication then you have to do the following:
-
Suppose you have the following REST controller:
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(); } }
-
Create a new Spring configuration file with name
rest-dispatcher-spring.xml
under the root package (com.company.test
) of web or portal module. The content of the file must be as follows:<?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.1.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>
-
Define an additive application property
cuba.restSpringContextConfig
in the properties file of the module,.e.g.portal-app.properties
:cuba.restSpringContextConfig = +com/company/test/rest-dispatcher-spring.xml
-
The new controller runs in the context of the
CubaRestApiServlet
. So the URL for controller methods will start with the/rest
, i.e. the doSmth() method will be accesed by the URL:http://localhost:8080/app-portal/rest/myapi/dosmth
.WarningURL of the custom controller MUST NOT start with the
/rest/v2
.