Pep Gomez
Pep Gomez

Reputation: 217

Spring security: deny access to resource to specific role

Im programming a collection of rest web services with Spring, but cant configure it with Spring security for certain logic. I have these types of resources:

I have a problem with the last requirement. I have tried the following:

        http
        .authorizeRequests()  
            .antMatchers("/resource1").permitAll()                
            .antMatchers(HttpMethod.GET, "/resource2").hasAnyAuthority("ROLE_USER", "ROLE_ADMIN")
            .antMatchers(HttpMethod.GET, "/resource3").hasAuthority("ROLE_ADMIN")
            .antMatchers(HttpMethod.GET, "/resource4").not().hasAuthority("ROLE_USER")
            .anyRequest().fullyAuthenticated()
            .and().requestCache().requestCache(new NullRequestCache())
            .and().httpBasic().authenticationEntryPoint(authenticationEntryPoint)
            .and().csrf().disable();

This code is the most similar to what I need:

BUT, the problem is on "resource4"... if the user is authenticated, everything works fine (only users without any role USER can access the resource)... the problem is that Spring permits access to non-authentitcated users (as I suppose it considers they don't belong to the rule USER, which is correct)

Any idea on how to configure a resource as not being accessible for certain roles, BUT having to be authenticated?

Upvotes: 1

Views: 4796

Answers (1)

Dirk Deyne
Dirk Deyne

Reputation: 6936

you could use .access(String expression) it allows specifying that URLs are secured by an arbitrary expression

with expression = "not( hasRole('USER') ) and isAuthenticated()"

resulting in

http
    .authorizeRequests()  
        .antMatchers("/resource1").permitAll()                
        .antMatchers(HttpMethod.GET, "/resource2").hasAnyAuthority("ROLE_USER", "ROLE_ADMIN")
        .antMatchers(HttpMethod.GET, "/resource3").hasAuthority("ROLE_ADMIN")
        .antMatchers(HttpMethod.GET,"/resource4").access("not( hasRole('USER') ) and isAuthenticated()")

Upvotes: 4

Related Questions