Search code examples
springrestspring-securityspring-security-rest

Spring Security for RESTful API


I'm building a restful API using Spring 4.1.6 and spring-boot-starter-data-rest.

To make the rest api fully functional I need the last piece of the puzzle: security. Now I noticed spring has it's own spring-security-* packages that can aid with that task.

I tried using spring-security-config and spring-security-web and it works like a charm, with the exception that if the user is not authenticated, spring will redirect the user to login, thus giving a HTML login form. Because it's a Restful API, I just need an error to be returned in a JSON object if the user lacks the credentials or does not have enough permissions to read a particular resource. I'm sure I'm not the first to ask this question and searched all over the web for people asking the same thing, but couldn't quite find was I was looking for. So.. should I continue my research in this direction with spring-security, or should I find something?

Any advice is welcome, thank you


Solution

  • To change the Login Form response to a custom Http Response you need to configure a custom http response handler for Http Security config. If you are using xml for your security configuration use the configuration shown below, failureHandler used is the one available in Spring Security package. Update the URL to match yours.

    <?xml version="1.0" encoding="UTF-8"?>
    <beans:beans xmlns="http://www.springframework.org/schema/security"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
        xmlns:sec="http://www.springframework.org/schema/security"
        xsi:schemaLocation="
          http://www.springframework.org/schema/security
          http://www.springframework.org/schema/security/spring-security-3.2.xsd
          http://www.springframework.org/schema/beans
          http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">
    
        <!-- Rest authentication entry point configuration -->
        <http use-expressions="true" entry-point-ref="restAuthenticationEntryPoint">
            <intercept-url pattern="/api/**" />
            <sec:form-login authentication-failure-handler-ref="myFailureHandler" />
    
            <logout />
        </http>
    
        <!-- Using default failure handler -->
        <beans:bean id="myFailureHandler"
            class="org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler" />
    </beans:beans>