DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Less Code With Spring Data Rest
  • Introduction To Spring Data JPA With Inheritance in A REST Application
  • The Magic of Spring Data
  • Build Reactive REST APIs With Spring WebFlux

Trending

  • Agentic AI for Automated Application Security and Vulnerability Management
  • Endpoint Security Controls: Designing a Secure Endpoint Architecture, Part 1
  • Kullback–Leibler Divergence: Theory, Applications, and Implications
  • Simplifying Multi-LLM Integration With KubeMQ
  1. DZone
  2. Data Engineering
  3. Data
  4. Securing Spring Data REST With PreAuthorize

Securing Spring Data REST With PreAuthorize

In this post we take a look at how to secure a Spring Data REST using Spring Security and Spring Boot. Come find out how straight forward this is!

By 
Martin Farrell user avatar
Martin Farrell
·
Jun. 11, 17 · Tutorial
Likes (5)
Comment
Save
Tweet
Share
62.2K Views

Join the DZone community and get the full member experience.

Join For Free

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

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 the following: 

mvnw spring-boot:run


Maven

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


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.


package com.javabullets.springdata.jparest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;

import org.springframework.http.HttpMethod;

@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth)
throws Exception {
auth.
inMemoryAuthentication()
.withUser("user").password("user").roles("USER").and()
.withUser("admin").password("admin").roles("USER","ADMIN");
}

    @Override
    protected void configure(HttpSecurity http) throws Exception {
    http
          .authorizeRequests()
            .antMatchers("/rest/**").hasAnyRole("ADMIN","USER").and()
          .httpBasic()
            .and()
   .csrf().disable();   
    }
}

ParkrunCourseRepository

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

package com.javabullets.springdata.jparest;

import org.springframework.data.repository.CrudRepository;
import org.springframework.security.access.prepost.PreAuthorize;

@PreAuthorize("hasRole('ROLE_USER')")
public interface ParkrunCourseRepository extends CrudRepository<ParkrunCourse, Long> {
@Override
@PreAuthorize("hasRole('ROLE_ADMIN')")
ParkrunCourse save(ParkrunCourse parkrunCourse);
}


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

mvnw spring-boot:run


POST Methods – Access Forbidden

curl -u user:user -X POST -H "Content-Type:application/json" -d "{  \"courseName\" : \"adminOnly\",  \"url\" : \"url\",  \"averageTime\" : \"10000\" }" http://localhost:8080/rest/parkrunCourses

{"timestamp":1496134011261,"status":403,"error":"Forbidden","message":"Access is denied","path":"/rest/parkrunCourses"}


POST Methods – Access Allowed

curl -u admin:admin -X POST -H "Content-Type:application/json" -d "{  \"courseName\" : \"adminOnly\",  \"url\" : \"url\",  \"averageTime\" : \"10000\" }" http://localhost:8080/rest/parkrunCourses

{
  "courseName" : "adminOnly",
  "url" : "url",
  "averageTime" : 10000,
  "_links" : {
    "self" : {
      "href" : "http://localhost:8080/rest/parkrunCourses/13"
    },
    "parkrunCourse" : {
      "href" : "http://localhost:8080/rest/parkrunCourses/13"
    }
  }
}

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.

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

REST Web Protocols Spring Data Spring Framework Data (computing)

Published at DZone with permission of Martin Farrell, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Less Code With Spring Data Rest
  • Introduction To Spring Data JPA With Inheritance in A REST Application
  • The Magic of Spring Data
  • Build Reactive REST APIs With Spring WebFlux

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!