Prevent direct call to my spring boot rest API

Viewed 3289

I have several REST services (on spring boot) used by a javascript file (website) and these services can be called directly by anyone (and you can see the API url/parameters with the developper console on any browser). So I would like to prevent the direct calls to the API, exept of course from the front side of my app.

I saw that I can use an API key with spring security but is it reliable? Since I think you can see the key if you intercept the message with developper console.

1 Answers

What you can do are the following :

  • Disable CORS in your springboot application by setting the following globally or per endpoint as you wish.

To set the CORS per endpoint :

@CrossOrigin(origins = "http://localhost:9000")
@GetMapping("/greeting")
public Test testing(@RequestParam(required=false, defaultValue="Test") String name) {
    System.out.println("in test");
    return new Testing(10, String.format(template, name));
}
  • You can use spring security to preauthorize your controller endpoints to make sure that only the authorized has access to the controller.

Like for example :

@RestController
@RequestMapping({"/v2/"})
public class ExampleTestController {
    @PreAuthorize("hasAuthority('ROLE_ADMIN')")
    @RequestMapping(value = "/test", method = RequestMethod.GET)
    String test() {
        return "Hello";
    }
}

Using spring security is safe, as the user is always validated before access is granted . Even while using Oath2 the key generated is after validating the user login and the key can be used to validate every request to the controller by passing it in the header or using it in the rest template.

  • Another way of isolating your rest endpoints is by using the load balancer (or ngnix or anything) to block requests to these endpoints from outside your domain.
Related