1

My application listens to both HTTP and HTTPS ports. HTTP channel is available only for several clients, all other must be redirected to the secure channel (HTTPS) when trying to access the insecure one.

The problem is the HTTPS port for the redirection, for good reasons I'm starting the connector by myself, based on the application properties. The configuration is unknown to the default port-mapping implementation PortMapperImpl, so it returns always 443 or 8443 ignoring the actual ports the application is listening on.

So far I have find this; it works, but it looks really ugly:

@Configuration
class MySecurityAdapter extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity
            .requiresChannel()
            .requestMatchers(/* some matchers */)
            .requiresSecure()
            .and()
            .setSharedObject(PortMapper.class, myPortMapper());
    }
    @Bean
    PortMapper myPortMapper() { return new MyPortMapper(); }
}

I'm using the standard Servlet API, so I can't benefit from ServerHttpSecurity where the explicit setting of the port mapper seems to be included.

What is the correct way to set up a custom port mapper? It there any elegant?

ttulka
  • 10,309
  • 7
  • 41
  • 52

1 Answers1

0

The servlet API also allows setting the port mapper using the portMapper() method.

In this case you could use the following configuration

httpSecurity
        .requiresChannel()
            .requestMatchers(/* some matchers */)
            .requiresSecure()
            .and()
        .portMapper()
            .portMapper(new MyPortMapper());
  • I couldn't get it to work with your solution. I am using Spring Security 5.5.1. What worked for me is this: https://stackoverflow.com/a/60756754 – Sathish Aug 17 '21 at 14:29