Solve the problem of nginx proxy spring boot tomcat project error

created at 07-04-2021 views: 4

description

Problem scenario: All business logic is normal without passing nginx proxy, but some businesses often report null pointer errors after nginx proxy.

Error message:

java.lang.NullPointerException  
        at org.springframework.web.util.WebUtils.isSameOrigin(WebUtils.java:816)  
        at org.springframework.web.cors.DefaultCorsProcessor.processRequest(DefaultCorsProcessor.java:76)  
        at org.springframework.web.servlet.handler.AbstractHandlerMapping$CorsInterceptor.preHandle(AbstractHandlerMapping.java:503)  
        at org.springframework.web.servlet.HandlerExecutionChain.applyPreHandle(HandlerExecutionChain.java:134)  
        at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:956)  
        at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:895)  
        at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:967)  
        at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:869)  
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)  

Find the code:

public static boolean isSameOrigin(HttpRequest request) {  
    String origin = request.getHeaders().getOrigin();  
    if (origin == null) {  
        return true;  
    }  
    UriComponents actualUrl = UriComponentsBuilder.fromHttpRequest(request).build();  
    UriComponents originUrl = UriComponentsBuilder.fromOriginHeader(origin).build();  
    return (actualUrl.getHost().equals(originUrl.getHost()) && getPort(actualUrl) == getPort(originUrl));  
}  

Looking at this code logic is to judge whether the actual request address is consistent with the source address.

Solution

Modify the request header to the browser's request source at the nginx proxy layer.

location /mgmt {  
        proxy_pass http://sunbar_mgmt/mgmt;  
        proxy_set_header        X-Real-IP       $remote_addr;  
        proxy_set_header        Host            $host;  
        proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;  
        proxy_pass_request_headers              on;  
}  
Please log in to leave a comment.