我正在使用Nginx作为Spring启动应用程序的反向代理.我还使用带有sockjs和stomp消息的Websockets.
这是上下文配置.
这是客户端代码:
var socket = new SockJS(entryPointUrl);
var stompClient = Stomp.over(socket);
var _this = this;
stompClient.connect({},function () {
stompClient.subscribe('/app/some-url',function (message) {
// do some stuff
});
});
我也是Spring Security来保护一些内容.
@Configuration
@Order(4)
public static class FrontendSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/js/**","/css/**","/webjars/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin().loginPage("/login").permitAll()
.and()
.logout().permitAll();
}
}
当我在Nginx反向代理后面运行这个应用程序时,一切都很好.这是相反的配置:
proxy_pass http://testsysten:8080;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
# WebSocket support (Nginx 1.4)
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $http_connection;
# Max body size
client_max_body_size 10M;
我正在使用1.9.7版.
你有什么想法,为什么客户端没有得到认证?
我知道类似的问题,比如this one,但解决方案根本不起作用.
更新
我设法通过HTTP运行应用程序.我需要在Nginx配置中传递CSRF令牌.新配置是:
proxy_pass http://testsysten:8080;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
# Pass the csrf token (see https://de.wikipedia.org/wiki/Cross-Site-Request-Forgery)
# Default in Spring Boot
proxy_pass_header X-XSRF-TOKEN;
# WebSocket support (Nginx 1.4)
proxy_http_version 1.1;
只有缺少是通过HTTPS重定向.在Spring日志中可以看到以下条目:
o.s.w.s.s.t.h.DefaultSockJsService - Processing transport request: GET http://testsystem:80/localization/226/3mbmu212/websocket
好像Nginx Proxy需要重写到正确的端口.
最佳答案
我自己解决了这个问题.基本上,如果要使用Websocket和Spring Security,Nginx需要传递一些额外的标头值.需要将以下行添加到Nginx配置中的位置部分:
原文链接:https://www.f2er.com/nginx/434598.html # Pass the csrf token (see https://de.wikipedia.org/wiki/Cross-Site-Request-Forgery)
# Default in Spring Boot and required. Without it Nginx suppresses the value
proxy_pass_header X-XSRF-TOKEN;
# Set origin to the real instance,otherwise a of Spring security check will fail
# Same value as defined in proxy_pass
proxy_set_header Origin "http://testsysten:8080";