Open
Description
There may be multiple cases.
Anonymous access is disabled in REST API
Then an a anonymous session must be obtained and set to the security context in controller code. E.g.:
@RestController("sample_MyUnprotectedController")
@RequestMapping("/unprotected")
public class MyUnprotectedController {
@Inject
private DataManager dataManager;
@Inject
private TrustedClientService trustedClientService;
@Inject
private RestApiConfig restApiConfig;
@GetMapping("/logins")
public List<String> getUserLogins() {
UserSession anonymousSession = getAnonymousSession();
AppContext.setSecurityContext(new SecurityContext(anonymousSession));
try {
return dataManager.load(User.class)
.list()
.stream()
.map(User::getLogin)
.collect(Collectors.toList());
} finally {
AppContext.setSecurityContext(null);
}
}
private UserSession getAnonymousSession() {
try {
return trustedClientService.getAnonymousSession(restApiConfig.getTrustedClientPassword(),
restApiConfig.getSecurityScope());
} catch (LoginException e) {
throw new RuntimeException("Unable to obtain anonymous session for REST", e);
}
}
}
Anonymous access is enabled in REST API
Then endpoints may be configured in the rest-dispatcher-spring.xml
:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:oauth2="http://www.springframework.org/schema/security/oauth2"
xmlns:security="http://www.springframework.org/schema/security">
<context:component-scan base-package="com.company.sample.rest"/>
<security:http pattern="/rest/anonymous/**"
create-session="stateless"
entry-point-ref="oauthAuthenticationEntryPoint"
xmlns="http://www.springframework.org/schema/security">
<intercept-url pattern="/rest/anonymous/**" access="isAuthenticated()"/>
<anonymous enabled="false"/>
<csrf disabled="true"/>
<cors configuration-source-ref="cuba_RestCorsSource"/>
<custom-filter ref="firstRestEndpointFilter" before="FIRST"/>
<custom-filter ref="cuba_AnonymousAuthenticationFilter" after="PRE_AUTH_FILTER"/>
<custom-filter ref="cuba_RestLastSecurityFilter" position="LAST"/>
</security:http>
</beans>
cuba_AnonymousAuthenticationFilter
will do the job
Define reusable filter
A reusable filter similar to cuba_AnonymousAuthenticationFilter
may be defined, but the new filter will populate security context with anonymous session no matter cuba.rest.anonymousEnabled
property is set.