簡體   English   中英

如何安全地在Spring Boot Rest控制器中使用“ / images”路徑?

[英]How do I use “/images” path in Spring boot Rest controller with security?

我有一個Spring boot REST服務(spring-boot-starter-parent:1.3.2),該服務使用RestController定義的方法公開了一些端點。 我也在使用Spring安全性。 一切正常,直到我嘗試定義映射到“ / images”的控制器方法為止。 當我嘗試訪問此api路徑時,出現以下錯誤。 通過調試,我可以看到正在映射我的控制器處理程序,但是未調用preauthorize過濾器(對於其他映射,該過濾器已正確調用)。 我設置了以下屬性,但沒有更改。 如何解決此問題,以便可以使用“ / images”?

spring.resources.add-mappings=false
spring.mvc.static-path-pattern=/hide-me/**

錯誤:

    "exception": "org.springframework.security.authentication.AuthenticationCredentialsNotFoundException",
    "message": "An Authentication object was not found in the SecurityContext",

碼:

@RestController
@PreAuthorize(value = "hasAnyAuthority('SOMEUSER')")
public class ImageController {
  ...
  @RequestMapping(value = { "/images/{imageId}" }, method = RequestMethod.GET)
  @ResponseBody
  public Image getImage(@PathVariable UUID imageId) {
    return imageDataService.getImage(imageId);
  }
  ...

如果將映射更改為以下內容,則可以正常工作。

  @RequestMapping(value = { "/image/{imageId}" }, method = RequestMethod.GET)
  @ResponseBody
  public Image getImage(@PathVariable UUID imageId) {
    return imageDataService.getImage(imageId);
  }

我認為靜態資源的配置具有一個默認條目,該條目告訴Spring安全性忽略預身份驗證過濾器的“ / images”路徑。 我正在嘗試找出可能會被覆蓋的地方。

SpringBoot默認使用一些路徑

私有靜態最終String [] CLASSPATH_RESOURCE_LOCATIONS = {“ classpath:/ META-INF / resources /”,“ classpath:/ resources /”,“ classpath:/ static /”,“ classpath:/ public /”};

https://spring.io/blog/2013/12/19/serving-static-web-content-with-spring-boot

其中一個路徑是/ images

Java Web應用程序。 春季啟動。 定位圖像

當您使用SpringSecurity時,您也有以下限制

在Web應用程序中開箱即用的基本功能是:

具有內存存儲和單個用戶的AuthenticationManager bean(有關用戶的屬性,請參閱SecurityProperties.User)。 常見靜態資源位置(/ css / ,/ js / ,/ images / ,/ webjars /和** / favicon.ico)的路徑被忽略(不安全)。 所有其他端點的HTTP基本安全性。 發布到Spring的ApplicationEventPublisher的安全事件(成功和失敗的身份驗證以及訪問被拒絕)。

http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/

默認情況下,Spring Security提供的常見低級功能(HSTS,XSS,CSRF,緩存)處於啟用狀態。

您需要確保為每個請求完成安全性。 這可以使用以下SecurityConfiguration來完成:

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().anyRequest().authenticated();
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM