2017-04-18 25 views
2

我有一個由Spring Boot REST MVC API應用程序(spring引導版本1.5.2)提供服務的單個頁面客戶端。如何將CORS頭添加到由BasicErrorController呈現的Spring錯誤頁面?

我的應用程序通過Auth0 JWT令牌保護。如果一切正常,由ServletFilter提供響應的CORS標頭被配置爲建立安全的一部分:

protected void configure(HttpSecurity http) throws Exception { 
    ... 
    http.addFilterBefore(simpleCORSFilter(), Auth0AuthenticationFilter.class); 
    ... 
    } 

這似乎到處都是工作,所以到目前爲止,我已經測試過它 - 但一個地方它不起作用的是默認的Spring錯誤頁面(路徑「/ error」,默認由BasicErrorController類渲染)。

當我的服務方法拋出異常時,錯誤頁面工作並在響應正文中呈現我想要的JSON內容,但客戶端應用程序無法訪問http響應正文,因爲響應缺少CORS標頭。

所以問題:「我如何添加CORS頭到錯誤頁面」?

我應該從我的安全設置中刪除CORS過濾器並更全面地應用CORS過濾器嗎?在哪裏做 - 我找不到與Spring文檔相關的任何內容。

或者我應該寫一個自定義的錯誤控制器?文檔中自定義錯誤控制器的唯一例子似乎只允許您返回一個字符串。

回答

1

您可以定義錯誤單獨的控制器,並允許跨起源於它使用

@CrossOrigin("*") 
0

結合Poorvi與喬尼Karppinen的custom error controller代碼的答案給出:

@RestController 
public class ErrorController 
implements org.springframework.boot.autoconfigure.web.ErrorController 
{ 
    private static final String PATH = "/error"; 

    @Autowired private ErrorAttributes errorAttributes; 

    @Override 
    public String getErrorPath(){ 
    return PATH; 
    } 

    // I guess when time comes to lock down cors header, we could use a spring 
    // value configuration here to share with corsfilter. 
    @CrossOrigin("*") 
    @RequestMapping(value = PATH, produces = "application/json") 
    public @ResponseBody 
    ErrorJson error(HttpServletRequest request, HttpServletResponse response){ 
    return new ErrorJson(
     response.getStatus(), 
     getErrorAttributes(request, false)); 
    } 

    private Map<String, Object> getErrorAttributes(
    HttpServletRequest request, 
    boolean includeStackTrace 
){ 
    RequestAttributes requestAttributes = new ServletRequestAttributes(request); 
    return errorAttributes.getErrorAttributes(
     requestAttributes, 
     includeStackTrace); 
    } 

} 

class ErrorJson { 

    public Integer status; 
    public String error; 
    public String message; 
    public String timeStamp; 
    public String trace; 

    public ErrorJson(int status, Map<String, Object> errorAttributes){ 
    this.status = status; 
    this.error = (String) errorAttributes.get("error"); 
    this.message = (String) errorAttributes.get("message"); 
    this.timeStamp = errorAttributes.get("timestamp").toString(); 
    this.trace = (String) errorAttributes.get("trace"); 
    } 

} 

這似乎做的工作爲我。

相關問題