0

I am using Spring Data Rest to expose JPA repositories to our React front-end application. And I also use Spring Security and JWT to protect REST APIs.

For examples, we have Entity and Repository as below:

@Entity
@Table(name = "customer")
public class Customer {
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private long id;
  ....
}

public interface CustomerRepository extends PagingAndSortingRepository<Customer, Long> {
}

Spring Data Rest will expose CustomerRepository to REST endpoint /api/customers So our React application can call REST endpoints to get data. It works well.

However, someone with valid JWT token can use tools like Postman to fetch all customers data from the servers. Of course, we don't want this happen.

My questions:

  • How can we prevent such abnormal usage?
  • What's the best practice to use Spring Data Rest?
Trung
  • 1,012
  • 13
  • 26
  • Use Spring Security to secure the end-points in line with your requirements. – Alan Hay Feb 13 '20 at 17:01
  • Yes, we used Spring Security in our project. However, in case of a novice user logins into the app. A bad guy steals token from him and use Postman to fetch data from server. We would like to prevent that situation. How can we prevent this abnormal usage? – Trung Feb 14 '20 at 04:17
  • You could consider standard session based auth for a normal web application. 1. https://stackoverflow.com/questions/34259248/what-if-jwt-is-stolen 2. https://speakerdeck.com/rdegges/jwts-suck – Alan Hay Feb 14 '20 at 09:15

1 Answers1

0

Your application exposes a REST API by using Spring Data REST. One of your entities is a Customer entity which is exposed through the CustomerRepository. On querying the list of all entities by calling /api/customers you only want those Customer entities to be listed that the querying principal has permission to see.

This can be done by annotating the method in question with @PreFilter or @PostFilter as explained in the Spring Security reference documentation. You need to specify some sort of condition.

An example:

@PostFilter(hasPermission(filterObject, 'read'))
public List<Customer> findAll();

Mind that @PostFilter iterates through the returned value, which can take some time, depending on the size of the returned list.

Daniel
  • 458
  • 5
  • 16