SpringMVC,Restful,API,how to match url to control privilege

198 views Asked by At

SpringMVC,restful api

GET /order/{orderId}

POST /order/{orderId}/abc/{abcId}-{bcdId}

POST /order/{orderId}/myresource/{subResources:[a-zA-Z0-9_/]+}

role1 can call api1 role2 can call api1 & api2 & api3

how to match url for the API path

sorry My English is poor.

1

There are 1 answers

3
Ulises On

If you're using Java Based configuration you can do this:

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
            .requestMatchers(new AntPathRequestMatcher("/order/*", HttpMethod.GET.name())).hasAnyRole("ROLE1", "ROLE2")
            .requestMatchers(new AntPathRequestMatcher("/order/*/abc/*", HttpMethod.POST.name())).hasRole("ROLE2")
            .requestMatchers(new AntPathRequestMatcher("/order/*/myresource/**", HttpMethod.POST.name())).hasRole("ROLE2");
    }
}

This is just showing the role based authorization config you can apply to the URLs, not the full Spring Security configuration. Just what regards to url matching role authorization.

There are many other RequestMatcher implementations you could use. You could implement your own too if the ant path matching isn't enough for you.

A completely different way of doing this with the same result would be to enable global method security with annotation @EnableGlobalMethodSecurity in your configuration file. An then using one of the @Secured, @PreAuthorize or @PostAuthorize annotations in your service/endpoint. For instance:

@RequestMapping(value="/order/{orderId}", method=RequestMethod.GET)
@Secured(value = {"ROLE1", "ROLE2"})
public @ResponseBody Order getOrder(@PathVariable("orderId") String orderId) {
    ...
}

Again, this just shows how you could apply the role authorization to your endpoint and not all config required for Spring Security.