0

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

alexg
  • 902
  • 11
  • 37

1 Answers1

1

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>
Nitin Arora
  • 2,650
  • 1
  • 26
  • 27
  • ok, thanks. I'm new to Spring, where do I store this file? also a few documentation links explaining what's happening here would be very helpful. – alexg Apr 26 '15 at 01:30
  • Generally you would put this file in src/main/resources. If you are starting out with Spring, follow this link to get up and running https://malalanayake.wordpress.com/2014/06/27/spring-security-on-rest-api/. If you want to use Java Configuration then follow this http://java.dzone.com/articles/secure-rest-services-using – Nitin Arora Apr 26 '15 at 01:38