'Spring Security with OAuth2 and anonymous access

I have my Spring REST API secured with Spring Security and OAuth2, I can successfully retrieve a token and access my APIs. My App defines the OAuth2 client itsself.

Now I want users to have anonymous access on some resources. The use case is really simple: I want my app to be usable without login - but if they are logged in, I want to have access to that principal.

Here is my WebSecurityConfigurerAdapter so far:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.antMatcher("/api1").anonymous().and()
            .authorizeRequests().antMatchers("/ap2**").permitAll();
}

As soon as I add a second antMatcher/anonymous, it fails to work though, and it doesn't really express my intent either - e.g. I wan't to have anonymous access on api1 GETs, but authenticated on POSTs (easy to do with @PreAuthorize).

How can I make the OAuth2 authentication optional?



Solution 1:[1]

I dropped my @EnableWebSecurity and used a ResourceServerConfigurerAdapter like so:

@Configuration
@EnableResourceServer
protected static class ResourceServer extends ResourceServerConfigurerAdapter {

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                    .antMatchers(HttpMethod.GET, "/api/api1", "/api/api2").permitAll()
                .and().authorizeRequests()
                    .anyRequest().authenticated();
    }

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources.resourceId("my-resource-id");
    }
}

/api/api1 may now be called with or without authentication.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Gille de Ray Ban