How to allow anonymous user access from localhost only in Spring security?

Viewed 4923

I want to allow only requests from localhost for a specific URL pattern. I tried this so far:

<sec:intercept-url pattern="/blabla/**" access="hasIpAddress('127.0.0.1')" />

But this isn't working and I got the following statement in the log output:

Access is denied (user is anonymous); redirecting to authentication entry point

So my question is, how do I allow anonymous user access from localhost only?

3 Answers

I ended up using the following:

http.authorizeRequests()
// restrict all requests unless coming from localhost IP4 or IP6
.antMatchers("/**").access("hasIpAddress(\"127.0.0.1\") or hasIpAddress(\"::1\")")

I tried only with hasIpAddress("127.0.0.1") which was working ok if I put that IP in the browser url but it wasn't working with requesting it from localhost as an alias.

Take a look at the HttpSecurity::anonymous method enabling and providing the AnonymousConfigurer<H extends HttpSecurityBuilder<H>> configuration of the anonymous authentication.

At your Spring Security configuration class, there should be an overriding method:

@Override
public void configure(HttpSecurity http) throws Exception {
    http.and()
        .anonymous()...          // enables and configures the anonymous access
    .and()
        .authorizeRequests()...

Is it possible to express this and() relation in XML based configuration?

As per documentation here https://docs.spring.io/spring-security/site/docs/3.0.x/reference/el-access.html below should work.

Here we have defined that the “blabla” area of an application (defined by the URL pattern) should only be available to anonymous users whose IP address matches 127.0.0.1.

    <sec:intercept-url pattern="/blabla/**"
        access="isAnonymous() and hasIpAddress('127.0.0.1')"/>
Related