-1

SpringMVC,restful api

获取 /order/{orderId}

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

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

role1 可以调用 api1 角色2 可以调用 api1 & api2 & api3

如何匹配 API 路径的 url

对不起,我的英语很差。

4

1 回答 1

0

如果您使用的是基于 Java 的配置,您可以这样做:

@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");
    }
}

这只是显示可以应用于 URL 的基于角色的授权配置,而不是完整的 Spring Security 配置。关于 url 匹配角色授权的内容。

您可以使用许多其他 RequestMatcher 实现。如果 ant 路径匹配对您来说还不够,您也可以实现自己的。

实现相同结果的完全不同的方法是@EnableGlobalMethodSecurity在配置文件中使用注释启用全局方法安全性。然后在您的服务/端点中使用@Secured@PreAuthorize@PostAuthorize注释之一。例如:

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

同样,这只是展示了如何将角色授权应用于端点,而不是 Spring Security 所需的所有配置。

于 2016-02-17T02:44:13.673 回答