2

对不起我的英语不好。isAuthenticated()为什么Spring 安全性中的工作方法不起作用?我在 JSF 中使用:

#{loginMB.authentication.authenticated}

<sec:authorize access="hasRole('ROLE_ADMIN')">
    test
</sec:authorize>

它不工作。无论我是否经过身份验证,它都会返回true

如果显示角色:

#{loginMB.authentication.authorities}

正确显示,当角色被认证时,角色是[ROLE_ADMIN],当角色未被认证时[ROLE_ANONYMOUS]

什么时候出问题?

==== 更新 ====

如果像 Aleksandr 所说的那样创建方法isAuthenticated()进行LoginBean检查:AnonymousAuthenticationToken

public boolean isAuthenticated(){

    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    return authentication != null && !(authentication instanceof AnonymousAuthenticationToken) && authentication.isAuthenticated();

}

这是工作。谢谢亚历山大。但是授权标签不起作用。如果我添加一个 JSF 页面:

<sec:authorize access="hasRole('ROLE_ANONYMOUS')">
    ROLE_ANONYMOUS
</sec:authorize>
<sec:authorize access="hasRole('ROLE_ADMIN')">
    ROLE_ADMIN
</sec:authorize>

它打印 ROLE_ANONYMOUS 和 ROLE_ADMIN。为什么?

==== 更新了 2 ====

applicationContext-security.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
             xmlns:beans="http://www.springframework.org/schema/beans"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xmlns:context="http://www.springframework.org/schema/context"
             xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
           http://www.springframework.org/schema/security
           http://www.springframework.org/schema/security/spring-security-3.1.xsd">

    <beans:import resource="applicationContext.xml"/>


    <global-method-security jsr250-annotations="enabled" />

    <http auto-config="true" use-expressions="true">
        <form-login login-page="/pages/login.html" authentication-failure-url="/fail.html"/>
        <intercept-url pattern="/**" access="permitAll" />

    </http>

    <authentication-manager alias="authenticationManager">
        <authentication-provider user-service-ref="UserDAO">
            <password-encoder hash="plaintext" />
        </authentication-provider>
    </authentication-manager>

</beans:beans>
4

1 回答 1

5

问题解决了。

  1. 如果在 LoginBean 中创建方法 isAuthenticated() 以检查 AnonymousAuthenticationToken,如 Aleksandr 所说:

       public boolean isAuthenticated(){
    
           Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
           return authentication != null && !(authentication instanceof AnonymousAuthenticationToken) && authentication.isAuthenticated();
    
       }
    

    这是工作。谢谢亚历山大。

  2. 对于将工作授权标签在 JSF 页面中阅读这里。我遇到问题。

于 2013-10-10T22:28:10.390 回答