Juan Reina Pascual
Juan Reina Pascual

Reputation: 4588

spring basic authentication plus ip filter

I´m trying to configure a basic authentication plus ip filter, the basic auth, works fine with this configure:

protected void configure(HttpSecurity http) throws Exception {
    http
        .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
        .csrf()
            .disable()
        .authorizeRequests()
            .anyRequest()
            .fullyAuthenticated()
            .and()
        .httpBasic();
}

I would like to add ip filter, I´ve read some about hasIpAddress but I don´t know how use it.

Upvotes: 0

Views: 526

Answers (1)

dur
dur

Reputation: 16979

For XML configuraton see Spring Security Reference:

26.2 Web Security Expressions

To use expressions to secure individual URLs, you would first need to set the use-expressions attribute in the <http> element to true. Spring Security will then expect the access attributes of the <intercept-url> elements to contain Spring EL expressions. The expressions should evaluate to a Boolean, defining whether access should be allowed or not. For example:

<http>
    <intercept-url pattern="/admin*"
       access="hasRole('admin') and hasIpAddress('192.168.1.0/24')"/>
    ...
</http>

Here we have defined that the "admin" area of an application (defined by the URL pattern) should only be available to users who have the granted authority "admin" and whose IP address matches a local subnet. We’ve already seen the built-in hasRole expression in the previous section. The expression hasIpAddress is an additional built-in expression which is specific to web security. It is defined by the WebSecurityExpressionRoot class, an instance of which is used as the expression root object when evaluation web-access expressions.

For Java configuration see ExpressionUrlAuthorizationConfigurer.AuthorizedUrl#access:

Parameters:

attribute - the expression to secure the URLs (i.e. "hasRole('ROLE_USER') and hasRole('ROLE_SUPER')")

Your modified code:

protected void configure(HttpSecurity http) throws Exception {
    http
        .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
        .csrf()
            .disable()
        .authorizeRequests()
            .anyRequest().access("isFullyAuthenticated() and hasIpAddress('192.168.1.0/24')")
            .and()
        .httpBasic();
}

Upvotes: 1

Related Questions