Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confusion around Spring Security anonymous access using Java Config

I am using the following Java Config with Spring Security:

protected void configure(HttpSecurity http) throws Exception {
    http
        .authorizeRequests()
            .anyRequest().authenticated()
            .and()
        .httpBasic();
}

Based on this configuration, all requests are authenticated. When you hit a controller without being authenticated, the AnonymousAuthenticationFilter will create an Authentication object for you with username=anonymousUser, role=ROLE_ANONYMOUS.

I am trying to provide anonymous access to a a specific controller method and have tried to use each of the following:

  1. @Secured("ROLE_ANONYMOUS")
  2. @Secured("IS_AUTHENTICATED_ANONYMOUSLY")

When the controller methods get invoked, the following response is given: "HTTP Status 401 - Full authentication is required to access this resource"

Can someone help me understand why we are receiving this message and why ROLE_ANONYMOUS/IS_AUTHENTICATED_ANONYMOUSLY don't seem to work using this configuration?

Thanks,
JP

like image 613
user2145809 Avatar asked Mar 13 '14 16:03

user2145809


People also ask

Is Anonymous () Spring Security?

Spring Security's anonymous authentication just gives you a more convenient way to configure your access-control attributes. Calls to servlet API calls such as getCallerPrincipal , for example, will still return null even though there is actually an anonymous authentication object in the SecurityContextHolder .

How do I bypass WebSecurityConfigurerAdapter?

Step 1: Add the security jar or dependency in your application. Step 2: Create a security config class and extend the WebSecurityConfigurerAdapter class. Step 3: Add the annotation @EnableWebSecurity on top of the class. Step 4: For authentication, override the method configure(AuthenticationManagerBuilder auth) .

Why is WebSecurityConfigurerAdapter deprecated?

In Spring Security 5.7. 0-M2 we deprecated the WebSecurityConfigurerAdapter , as we encourage users to move towards a component-based security configuration.


1 Answers

Your security configuration is blocking all unauthenticated requests. You should allow access to the controller with

.antMatchers("/mycontroller").permitAll()

See also:

  • http://spring.io/blog/2013/07/03/spring-security-java-config-preview-web-security/
like image 183
anttix Avatar answered Sep 28 '22 04:09

anttix