如何在spring security 3中为匿名用户从数据库加载角色?

Jer*_*nce 5 security anonymous spring-security anonymous-users

我正在使用Spring Security 3.0.2,我找不到从数据库加载匿名用户角色的方法(我有动态角色,可以将角色分配给每个人).

我尝试使用自定义anonymousAuthenticationProvider,但从不调用此提供程序.这是我的配置:

<http auto-config="false">
    <logout invalidate-session="true" logout-success-url="/page/welcome" />
    <remember-me />
    <anonymous username="_GUEST_" granted-authority="ROLE_GUEST" key="anonymousKey" />
    <form-login login-page="/page/login" authentication-failure-url="/page/login?fail=1" default-target-url="/page/welcome" />
</http>

<authentication-manager alias="authenticationManager">
    <authentication-provider ref="anonymousAuthenticationProvider"></authentication-provider>
    <authentication-provider user-service-ref="accountDetails">
        <password-encoder ref="passwordEncoder">
            <salt-source user-property="xxxx" />
        </password-encoder>
    </authentication-provider>
</authentication-manager>

<beans:bean id="accountDetails" class="com.mysite.AccountDetailsImpl" />

<beans:bean id="passwordEncoder" class="org.springframework.security.authentication.encoding.ShaPasswordEncoder">
    <beans:constructor-arg value="512" />
</beans:bean>

<beans:bean id="anonymousAuthenticationProvider" class="com.my.site.security.CustomAnonymousAuthenticationProvider">
    <beans:property name="key" value="anonymousKey" />
</beans:bean>
Run Code Online (Sandbox Code Playgroud)

永远不会调用我的anonymousAuthenticationProvider,因此我无法从数据库加载自定义权限.当我登录时,我的服务accountDetails被调用,我可以从数据库为用户加载角色,我想为匿名用户做同样的事情.

我该怎么做 ?谢谢

axt*_*avt 4

实现它的最简单方法似乎是使用AnonymousAuthenticationFiltercustom声明 a UserAttribute,这将产生所需的权限:

<http auto-config = "false">
    <anonymous enabled = "false" />
    <custom-filter ref = "myFilter" position = "ANONYMOUS_FILTER" />
    ...
</http>

<beans:bean id = "myFilter" class = "org.springframework.security.web.authentication.AnonymousAuthenticationFilter">
    <beans:property name = "key" value = "anonymousKey" />
    <beans:property name = "userAttribute" ref = "myAttributes" />
</beans:bean>

<beans:bean id = "myAttributes" class = "..." />
Run Code Online (Sandbox Code Playgroud)