0

We are using Spring Security version 4. By default the anonymous user has the ROLE_ANONYMOUS assigned.

We want to add more roles for the anonymous user.

I tried to extend the AnonymousAuthenticationFilter and add it to Spring Security context as below:

<http entry-point-ref="authenticationEntryPoint">
    <custom-filter ref="sabaAnonymousAuthenticationFilter" position="ANONYMOUS_FILTER"/> 
    <anonymous enabled="false"/>
.....

<beans:bean id="sabaAnonymousAuthenticationFilter"
                class="foo.bar.CustomAnonymousAuthenticationFilter">
                <beans:constructor-arg index="0" value="SomeUniqueKeyForThisApplication"/>
</beans:bean>

And the class:

public class CustomAnonymousAuthenticationFilter extends AnonymousAuthenticationFilter {
    @Inject 
    HelperClass aHelperClass;

    public CustomAnonymousAuthenticationFilter(String key) {
        super(key);
        getAuthorities().add(new SimpleGrantedAuthority("ROLE_FOO_BAR")); 
        ......
    }
}

The above code change anonymous roles and add ROLE_FOO_BAR, but I can not @Inject or @Autowire other Spring beans in this filter.

Please let me know:

  1. Is this a correct way of defining a custom anonymous filter?
  2. How can I authowire other beans here?

I used same approach for defining a custom UserDetailsService and the autowire works there.

dur
  • 15,689
  • 25
  • 79
  • 125
Alireza Fattahi
  • 42,517
  • 14
  • 123
  • 173

1 Answers1

2

As far as I understand the spring security documentation one could add an additional role to the user like this:

<bean id="anonymousAuthFilter"
      class="org.springframework.security.web.authentication.AnonymousAuthenticationFilter">
    <property name="key" value="foobar"/>
    <property name="userAttribute" value="anonymousUser,ROLE_ANONYMOUS, ROLE_FOOBAR"/>
</bean>

This way you could probably avoid writing your own Authentication Filter.

Try it out. I hope it suits your needs.

Compito
  • 851
  • 5
  • 6
  • Thanks, but I need to have my own class, as the `roles` can not be hard coded in xml and should read from a file. – Alireza Fattahi Sep 25 '16 at 12:59
  • Perhaps this post http://stackoverflow.com/questions/32494398/unable-to-autowire-the-service-inside-my-authentication-filter-in-spring will resolve your autowire problem. – Compito Sep 25 '16 at 14:23