简体   繁体   中英

Authentication problems with spring security behind nginx reverse proxy

I have a problem with Spring Security and a nginx reverse proxy server. Most of my routes are protected by Basic Auth in my Spring boot application. However, I want to have a specific set of route protected only by the nginx basic auth.

Unfortunately, I have the problem that the route asks always for both authentications.

I created a location targeting this specific spring route. The spring app and the nginx server are each running in a separate docker container.

This is my Spring Security setting.

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                .authorizeRequests()
                .antMatchers("/reporting/**").permitAll()
                .antMatchers("/user/create").hasRole("ADMIN")
                .anyRequest().authenticated()
                .and()
                .httpBasic();
    }

This is my location:

  location /smartphone-reporting {
    rewrite /smartphone-reporting(.*)$ $1 break;
    proxy_pass          http://172.17.0.1:8888/reporting;
    auth_basic "Restricted Content";
    auth_basic_user_file /etc/nginx/htpasswd.users;
  }

In my nginx server config, I have defined these header parameters:

server {
  ...
  # Add X-Forwarded-* headers
  proxy_set_header        X-Forwarded-Host $hostname;
  proxy_set_header        X-Forwarded-Proto $scheme;
  proxy_set_header        Upgrade $http_upgrade;
  proxy_set_header        Connection "upgrade";
  proxy_set_header        X-Cert $ssl_client_s_dn;
}

If I use curl on the server on the proxy_pass route, I receive a response without any authentication. If I make a request from outside the server, I end up in an endless loop which asks for both authentication types.

How do I have to setup the nginx that this is working?

I solved it. My rewrite rule did not forward to /reporting in Spring and I needed to clear the authentication header.

The following location configuration works for me:

  location /smartphone-reporting/ {
    proxy_pass          http://172.17.0.1:8888/reporting/;
    auth_basic "Restricted Content";
    auth_basic_user_file /etc/nginx/htpasswd.users;
    proxy_set_header Authorization "";    
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM