2013-10-07 187 views
2

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

#{loginMB.authentication.authenticated} 

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

它不工作。如果我通过验证,所有时间都会返回true

如果呈现出角色:

#{loginMB.authentication.authorities} 

它显示正确的,当验证的作用是[ROLE_ADMIN],在未认证的作用是[ROLE_ANONYMOUS]

什么时候有问题?

==== ====更新

如果LoginBean创建梅托德isAuthenticated()进行检查AnonymousAuthenticationToken为亚历山大说:

public boolean isAuthenticated(){ 

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

} 

这是工作。谢谢Aleksandr。但授权标签不起作用。如果我添加一个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> 
+0

它工作正常。如果你想使用这种方法,你只需要检查'AnonymousAuthenticationToken'。 –

+0

我在LoginBean中创建了metod isAuthenticated()来检查AnonymousAuthenticationToken,它是可行的。但春季安全授权标签不起作用。 – z3r9

+0

你是什么意思? –

回答

3

问题解决了。

  1. 如果创建梅托德isAuthenticated()在LoginBean进行检查AnonymousAuthenticationToken为亚历山大说:

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

    这是工作。谢谢Aleksandr。

  2. 对于将工作授权标签在JSF页面阅读here。我有it问题。