Raghu
Raghu

Reputation: 23

How to use spring security in each REST call in Spring Boot?

I am trying to understand if there is a way to use spring security which helps my used case. Basically, I want to call spring security on each REST call in spring boot, rather than one time during the start of the application, and find the role of the user and further restrict endpoints based on the user roles.

I have 3 different rest controllers namely /admin1/*, /admin2/*, /admin3/*.
I have tried restricting endpoints manually as below.

http.authorizeRequests()
        .antMatchers("/admin1/**").permitAll()
        .and()
    .authorizeRequests()
        .antMatchers("/admin2/**").permitAll()
    .anyRequest().authenticated();

This will actually allow /admin1/* and /admin2/* APIs to work and restrict /admin3/*. However, my used case is as below.

In each rest call, we pass the user id in the header. I would like to use spring security on each rest call, and use the user id from the header to find the user roles from the database.

If user has ADMIN 1 user role, we have to just enable /admin1/* endpoints and restrict /admin2/* and /admin3/*. Similarly, if user has ADMIN 2 user role, we have to just enable /admin2/* endpoints and restrict /admin1/* and /admin3/*. In the same way, if user has ADMIN 3 user role, we have to just enable /admin3/* endpoints and restrict /admin1/* and /admin2/*.

Is there a way to achieve this using spring security?

Thank you

Upvotes: 2

Views: 1203

Answers (1)

Morteza
Morteza

Reputation: 662

AS far as I understood, you want to authenticate & authorize users on each call. True?

one way is tokenizing your REST APIs with JWT (JSON Web Token).

The example in https://dzone.com/articles/spring-boot-security-json-web-tokenjwt-hello-world would probably help.

I Also suggest that instead of using antMatchers In configure method to restrict URL access based on Roles, you use @PreAuthorize and @PostAuthorize annotations above the classes or methods you want to secure. This way gives you more flexibility on your restriction policies.

The example in https://www.baeldung.com/spring-security-method-security also may help you with that.

Upvotes: 1

Related Questions