2017-04-10 133 views
0

我有一個端點,我想允許訪問而不需要基本的認證。這是下面如下終點:Spring Security有條件的基本認證

@ApiOperation(value = "Get a image by id", response = ResponseEntity.class) 
@RequestMapping(value = "/{id}", method = RequestMethod.GET) //sets the mapping url and the HTTP method 
public void getById(@PathVariable("id") Long id, HttpServletResponse response) throws NotFoundException { 
    ImageView view; 
    try { 
     view = manager.get(id); 
     ByteArrayInputStream in = new ByteArrayInputStream(view.getImageData()); 
     response.setContentType(MediaType.parseMediaType(view.getImageMimeType()).toString()); 
     IOUtils.copy(in, response.getOutputStream()); 
    } catch (NotFoundException e) { 
     response.setStatus(204); //HttpStatus.NO_CONTENT); 
     return; 
    } catch (IOException ioe) { 
     response.setStatus(400);//HttpState.BAD_REQUEST 
     return; 
    } 
} 

我已經閱讀遇到類似問題的人等幾個堆棧溢出後,只見那壓倒一切的安全性配置工作。以下是我通過閱讀幾篇文章而設計的解決方案。但是,我仍然遇到問題,並在未經身份驗證的情況下請求資源時收到401。方不要,全路徑將是「(東道國)/服務/ V1 /圖片/(編號)」

@Override 
protected void configure(HttpSecurity http) throws Exception { 
    http.csrf().disable() //disable csrf being needed for header in a request 
      .authorizeRequests() //authorize the following request based on following set rules 
      .antMatchers(HttpMethod.OPTIONS, "**").permitAll() //allow any user to access this when OPTIONS 
      .antMatchers(HttpMethod.GET,"**/service/v1/images/**").permitAll() //allows GETS for given route permitted to all users 
      .anyRequest().authenticated() //catch all: this implies that if nothing matches the above two patterns, then require authentication 
      .and().httpBasic(); //utilize http basic for authentication 

} 

任何洞察我可能做錯了,如何解決這一將不勝感激。

回答

1

爲了忽略安全特定的URL做到這一點:

除了你

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

你也需要重寫下一個方法:

@Override 
public void configure(WebSecurity web) throws Exception { ... } 

在該方法,你可以寫這樣的事情,以便忽略特定URL的安全性:

@Override 
public void configure(WebSecurity web) throws Exception { 
    web.ignoring().antMatchers("/css/**", "/js/**", 
      "/app/controllers/**", "/app/partials/**", "/app/*", 
      "/", "/index.html", "/favicon.ico"); 
} 

上面的示例將禁用指定的ant匹配器的安全性。

你可以刪除permitAll()

+0

所以我可以刪除下面的代碼或只是刪除許可證?:.antMatchers(HttpMethod.GET, 「** /服務/ V1 /圖片/ **」)。 permitAll() – Jleaton

+1

但首先添加web.ignoring.antMatchers(「/ service/v1/images /」) –