-2

How do I do role validation for REST APIs?

I have 2 roles called admin and manager. How do I limit the access of REST APIs using RBAC (Role-based Access Control)? For example, /users POST can be accessed by admin role and /users GET can be accessed by manager role.

Jon
  • 3,573
  • 2
  • 17
  • 24

1 Answers1

1

You can achieve it by using Spring Security.

Spring Security

A highly customizable framework, Spring Security is widely used to handle the authentication and access control (authorization) issues arising in any Enterprise based application developed in Java.

Ex :

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    

    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    
    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.csrf().disable().authorizeRequests().antMatchers("/user/login").permitAll().antMatchers(HttpMethod.OPTIONS)

                .permitAll()
                .antMatchers(HttpMethod.GET, "/user").hasRole("ADMIN")
                .antMatchers(HttpMethod.GET, "/user/list").hasAnyRole("MANAGER", "ADMIN")
                .authenticated();       

    }   
}
Community
  • 1
  • 1
DEBENDRA DHINDA
  • 1,163
  • 5
  • 14