javaspringspring-security

Why my REST Configuration in spring-security.xml not intercepting /rest endpoints?


I am using Spring 6.0 and spring-security 6.1

This is my REST config

    <security:http security-context-explicit-save="true" use-expressions="true" use-authorization-manager="false" pattern="/rest/**" create-session="stateless" entry-point-ref="restServicesEntryPoint">
        <security:custom-filter ref="restServicesFilter" position="BASIC_AUTH_FILTER" />
    </security:http>
    <bean id="restServicesEntryPoint" class="com.example.webservices.auth.RestAuthenticationEntryPoint">
        <property name="realmName" value="Square" />
    </bean>
    <bean id="restServicesFilter" class="com.example.webservices.auth.CustomRestSecurityFilter"/>

This is non-rest Config

<security:http create-session="stateless" security-context-explicit-save="true" use-authorization-manager="false" authentication-manager-ref="authenticationManagerWithMultipleProviders" security-context-repository-ref="nullSecurityContextRepository">
<!-- Login config -->
<security:access-denied-handler error-page="/bs/denied"/>
    <!-- Login config -->   
<security:form-login login-page="/bs/login" authentication-success-handler-ref="customAuthenticationSuccessHandler" authentication-failure-handler-ref="customAuthenticationFailureHandler" />
//other codes

When hitting /rest/** endpoints. it is not intercepted by REST security config. Instead of rest config, it is coming through non-rest config.

And if removed property use-authorization-manager=false it is giving circular dependency error.


Solution

  • pattern="/rest/**" is not working. Instead of pattern I created CustomRestMatcher. And it starts intercepting rest endpoints.

    security config

    `<security:http request-matcher-ref="restMatcher" security-context-explicit-save="true" use-expressions="true" use-authorization-manager="false" create-session="stateless" entry-point-ref="restServicesEntryPoint">
        <security:custom-filter ref="restServicesFilter" position="BASIC_AUTH_FILTER" />
    </security:http>
    
    <bean id="restServicesEntryPoint" class="com.example.webservices.auth.RestAuthenticationEntryPoint">
        <property name="realmName" value="Square" />
    </bean>
    <bean id="restServicesFilter" class="com.example.webservices.auth.CustomRestSecurityFilter"/>
    <bean id="restMatcher" class="com.example.CustomRestMatcher" />`
    

    CustomRestMatcher class

    public class CustomRestMatcher implements RequestMatcher {
    @Override
    public boolean matches(HttpServletRequest request) {
        // method to check request is rest endpoint or not i.e. starts from /rest/**
        String requestPath = request.getServletPath();
        return requestPath.startsWith("/rest");
    }}