2017-08-12 87 views
1

我已经有了一个应用程序,它通过Spring MVC提供一些web内容,还有一些在同一个URI下的JSON。如何使用Spring Security来保护REST API(而不是视图)?

@Controller 
public class SomeController { 

    @RequestMapping(value = {"/someUri"}, method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE) 
    public String getView() { 
     return "index.html"; 
    } 

    @RequestMapping(path = "/someUri", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) 
    public @ResponseBody String getJson() { 
     return "{ \"some\": \"json\" }"; 
    } 

,现在我想,以确保只有REST API产生的MediaType.APPLICATION_JSON_VALUE与春季安全。

当我在每种方法上添加@PreAuthorize@Secured注释时,它都能正常工作。但我想全局配置它,例如在WebSecurityConfiguration#configure(HttpSecurity http)方法中。是否有可能以全球任何方式确保产生特定媒体类型的端点?

回答

1

你可以使用MediaTypeRequestMatcher

允许匹配基于从ContentNegotiationStrategy解决MediaTypeHttpServletRequest。默认情况下,匹配过程将执行以下操作:

  • ContentNegotiationStrategy将解决MediaType的当前请求
  • 已传递到构造每个matchingMediaTypes将针对从解决MediaType实例进行比较ContentNegotiationStrategy
  • 如果matchingMediaTypes之一是从ContentNegotiationStrategy返回的解决MediaType的一个兼容,则返回true

例如,请考虑下面的例子

GET/
Accept: application/json 
ContentNegotiationStrategy negotiationStrategy = new HeaderContentNegotiationStrategy() 
MediaTypeRequestMatcher matcher = new MediaTypeRequestMatcher(negotiationStrategy, MediaType.APPLICATION_JSON); 
assert matcher.matches(request) == true // returns true 
0

AFAIK Spring安全并不需要对url生成的媒体类型做任何事情。安全约束适用于URL模式。当你谈论@PreAuthorized和@Secured时,我假设你正在寻找一个全球授权机制。是的,你可以做这样的事情

@Configuration 
@EnableWebSecurity 
public class SecSecurityConfig extends WebSecurityConfigurerAdapter { 
    @Override 
    protected void configure(HttpSecurity http) throws Exception { 
     http 
      .authorizeRequests() 
      .antMatchers("/admin/**").hasRole("ADMIN"); 
    } 
    ... 
} 

但它是把所有需要授权某种像/安全子域的您的REST API的一个好主意,/ **,这样就可以应用安全直接到单一模式。否则,您需要逐个注册所有模式。

相关问题