PaulNUK
PaulNUK

Reputation: 5209

How to secure anonymous access restricted by ip address in Spring Security?

I'd like to allow anonymous access, restricted to a particular IP address subnet, to a URL.

The URL is :

http://10.102.34.98:880/auth/tokens/revoke/blabla where auth is the context root of the web-app.

The accessing IP address is 10.102.34.98 The subnet mask of the accessing IP address is 255.255.255.0 The trusted.client.subnet property is set to 10.102.34.0/24

Anonymous access works fine:

protected void configure(HttpSecurity http) throws Exception {
    http
        .csrf().disable()
        .requestMatchers()
            .antMatchers("/login", "/oauth/authorize","/tokens/revoke/**")
            .and()
        .authorizeRequests()
            .antMatchers("/tokens/revoke/**").permitAll()
            .and()
        .authorizeRequests()
            .anyRequest().authenticated()
            .and()
        .formLogin()
            .loginPage("/login")
            .permitAll();
}

but as soon as I replace the permitAll() with hasIpAddress() I get redirected to my login page.

How can I allow anonymous access restricted by IP address subnet?

protected void configure(HttpSecurity http) throws Exception {
    http
        .csrf().disable()
        .requestMatchers()
            .antMatchers("/login", "/oauth/authorize","/tokens/revoke/**")
            .and()
        .authorizeRequests() 
            .antMatchers("/tokens/revoke/**").hasIpAddress(environment.getProperty("trusted.client.subnet"))
            .and()
        .authorizeRequests()
            .anyRequest().authenticated()
            .and()
        .formLogin()
            .loginPage("/login")
            .permitAll();
}

Update 1:

It's this code at the end that is forcing the login form to be displayed. I was hoping it wouldn't take this into accont as well as it had passed the IP address whitelisting.

    .and()
    .authorizeRequests()
        .anyRequest().authenticated()
        .and()
    .formLogin()
        .loginPage("/login")
        .permitAll();

Upvotes: 2

Views: 1309

Answers (1)

Victor
Victor

Reputation: 2546

You should get more info by enabling the Spring Security logs:

-Dlogging.level.org.springframework.security=TRACE

Most likely, what is happening is that, one hasIpAddress matches, the role ROLE_ANONYMOUS is given to the user making the request. And that role is not enabled unless anonymous() is enabled in your security configuration.

See these other questions:

Upvotes: 1

Related Questions