Social Media

Spring Security and Spring Data REST

Spring Security and Spring Data REST are discussed in this post. It builds on the previous post “Introduction to Spring Data REST” and my series of posts on Spring Security –

Spring Security and Spring Data REST

Spring Security is split into two components –

  • Authentication – Defined by AuthenticationManager, or the source of the authentication credentials
  • Authorisation – what we want to protect – URL’s, Roles, method

This tutorial is only considering BasicAuthentication with an memory realm. I will probably return to this subject to show how to properly harden a RESTful API.

Source Code

Code available on github –

https://github.com/farrelmr/introtospringdatarest/tree/2.0.0

https://github.com/farrelmr/introtospringdatarest/releases/tag/2.0.0

Run the code by typing –

Maven

You can secure spring boot by simply including this dependency –

You can then get the password when you startup spring boot, but that is not very practical for most usages.

SecurityConfig

Ive moved the Spring Data REST API URL to /rest in application.properties –

SecurityConfig has –

  • Two users – user(Role – USER), admin(Role – admin)
  • Restrictions –
    • Only “ADMIN” or “USER” roles can access “/rest”,
    • Only “ADMIN” users can POST to the web service –

Putting It Together

Ive switched to curl for calling the API’s as its clearer for tutorials –

No credentials – Doesnt Authenticate

user/user credentials – Authenticates

POST methods – Access Forbidden

POST methods – Access Allowed

Conclusions

This post shows how Spring Security and Spring Data REST can be combined to secure REST API URL’s and HTTP methods. It used a basic form of Spring authentication, combining a MemoryRealm with the security configuration. We have also demonstrated how to restrict access to REST methods based on user group.

About the Author Martin Farrell

My name is Martin Farrell. I have almost 20 years Java experience. I specialize inthe Spring Framework and JEE. I’ve consulted to a range of businesses, and have provide Java and Spring mentoring and training.

You can learn more at About

follow me on: