2016-09-25 131 views
0

我們使用的是Spring Security版本4.默認情況下,匿名用戶擁有ROLE_ANONYMOUS分配。Spring Security定義了一個定製的匿名過濾器

我們想爲匿名用戶添加更多角色。

我試圖延長AnonymousAuthenticationFilter並將其添加到如下春季安全方面:

<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> 

和類:

public class CustomAnonymousAuthenticationFilter extends AnonymousAuthenticationFilter { 
    @Inject 
    HelperClass aHelperClass; 

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

上面的代碼改變匿名角色,並添加ROLE_FOO_BAR,但我在此過濾器中不能使用@Inject@Autowire其他Spring bean。

請讓我知道:

  1. 這是定義自定義過濾匿名的正確方法?
  2. 我怎樣才能authowire其他豆在這裏?

我用同樣的方法來定義自定義UserDetailsServiceautowire在那裏工作。

回答

2

據我瞭解spring security documentation一個可以添加額外的作用,這樣用戶:

<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> 

這樣你很可能避免編寫自己的身份驗證篩選器。

試一試。我希望它適合你的需求。

+0

謝謝,但我需要我自己的類,因爲'roles'不能用xml進行硬編碼,並且應該從文件中讀取。 –

+0

也許這篇文章http://stackoverflow.com/questions/32494398/unable-to-autowire-the-service-inside-my-authentication-filter-in-spring將解決您的autowire問題。 – Compito

相關問題