Social Media

Securing Spring Data REST with PreAuthorize

Securing Spring Data REST with PreAuthorize is an alternative method to securing Spring Data REST API’s, building on the previous apporach covered in Spring Security and Spring Data REST.

Securing Spring Data REST with Preauthorize

Securing Spring Data REST with PreAuthorize code is available on github –

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

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

Run the code by typing –

Maven

In order to use the preAuthorise attributes you need to import spring-boot-security –

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>

SecurityConfig

The key points are –

  • Maintain security for roles “ADMIN” and “USER” on “/rest/**” requests
  • @EnableGlobalMethodSecurity(prePostEnabled = true) – this enables the annotations on the JPA model

ParkrunCourseRepository

The key changes are the use of PreAuthorize on the ParkrunCourseRepository –

The key points are –

  • Use of hasRole – note you need to append ROLE_ to your roles
  • We could also add PreAuthorize security to custom methods defined in the repository

Putting It Together

POST methods – Access Forbidden

POST methods – Access Allowed

Discussion

This post shows a different approach to role based security of Spring Data REST with PreAuthorize. It is not a question of which method is better, but which is practical. It may be that you cannot use preAuthorize in your codebase, but can use role based authentication as outlined in Spring Security and Spring Data REST

From a design point of view you may want to define a custom repository with your core PreAuthorize rules, allowing your model to inherit security.

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.

My next post will look at how Spring Data REST can restrict access by deciding what methods it exposes, and what fields are exposed

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:

Leave a Comment: