spring security 3.1 isAuthenticated() 不工作

Posted

技术标签:

【中文标题】spring security 3.1 isAuthenticated() 不工作【英文标题】:spring security 3.1 isAuthenticated() not working 【发布时间】:2012-03-04 05:06:12 【问题描述】:

我正在使用 spring mvc 3 和 spring security 3.1.0 开始一个新项目。 我编写了一个身份验证提供程序,一个 UserDetails 类。很简单。 身份验证工作正常,但是当我在我的 jsp(使用 sitemesh 的模板之一)中使用时,它似乎无法正常工作。

这是我的例子。

<security:authorize access="isAuthenticated()"> 
                <ul class="nav">
                    <li class="$selectedMenu.equals('index') ? 'active' : ''"><a href="<c:url value="/" />">Home</a></li>
                    ....            
                </ul>
            </security:authorize>
            <p class="navbar-text pull-right">Logged in as <a href="#"><security:authentication property="principal.username"/></a></p>

我从来没有看到 ul 并且是空白的..

我不知道我错过了什么

这是我的配置:

security-applicationContext.xml

<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"
    xsi:schemaLocation="
      http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
      http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd">

    <http pattern="/resources/**" security="none"/>
    <http use-expressions="true">
        <intercept-url pattern="/**" access="isFullyAuthenticated()" />
         <form-login login-page='/spring_security_login' default-target-url='/index.html'
            always-use-default-target='true' />
        <session-management session-fixation-protection="none" />

    </http>

    <authentication-manager>
        <authentication-provider user-service-ref="AuthRepository">
            <password-encoder ref="passwordEncoder"/>
        </authentication-provider>
    </authentication-manager>

</beans:beans>

用户详情

package ar.com.held.auth;

import java.util.ArrayList;
import java.util.Collection;

import org.springframework.security.core.GrantedAuthority;

import ar.com.held.model.User;



public class UserDetails implements org.springframework.security.core.userdetails.UserDetails 

        /**
         * 
         */
        private static final long serialVersionUID = -2636146093986968636L;

        private User user;

        private String userName;
        private String password;

        public User getUser() 
            return user;
        

        public UserDetails(User user)
                this.user = user;
                this.userName = user.getUsername();
                this.password = user.getPassword();
        

        @Override
        public Collection<? extends GrantedAuthority> getAuthorities() 
                return new ArrayList<GrantedAuthority>();
        

        @Override
        public String getPassword() 
                return this.password;
        

        @Override
        public String getUsername() 
                return this.userName;
        

        @Override
        public boolean isAccountNonExpired() 
                return true;
        

        @Override
        public boolean isAccountNonLocked() 
                return true;
        

        @Override
        public boolean isCredentialsNonExpired() 
                return true;
        

        @Override
        public boolean isEnabled() 
                return true;
        




AuthRepository

package ar.com.held.auth;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.core.userdetails.jdbc.JdbcDaoImpl;
import org.springframework.stereotype.Repository;

import ar.com.held.model.User;
import ar.com.held.repository.UserRepository;


/***
 * Authentication users repository
 * 
 *
 */
@Repository(value="AuthRepository")
public class AuthRepository extends JdbcDaoImpl 

        @Autowired
        private UserRepository userRepository;

        @Override
        public UserDetails loadUserByUsername(String username)
                        throws UsernameNotFoundException 
                User user = userRepository.findByUserName(username);
                if(user==null)
                        throw new UsernameNotFoundException(username+" no es un usuario registrado");
                return new ar.com.held.auth.UserDetails(user);
        

        @Override
        protected void checkDaoConfig() 
        

已编辑***

这是我登录时请求JSP页面时的调试信息:

2012-02-14 18:18:28 AntPathRequestMatcher [DEBUG] Checking match of request : '/companies/list'; against '/resources/**'
2012-02-14 18:18:28 FilterChainProxy [DEBUG] /companies/list at position 1 of 10 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
2012-02-14 18:18:28 HttpSessionSecurityContextRepository [DEBUG] Obtained a valid SecurityContext from SPRING_SECURITY_CONTEXT: 'org.springframework.security.core.context.SecurityContextImpl@127c16e: Authentication: org.springframework.security.authentication.UsernamePasswordAuthenticationToken@127c16e: Principal: ar.com.held.auth.UserDetails@1250cda; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@fffd3270: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: 4E06EC71A480C21A3CB08DDE2EBFDAF5; Not granted any authorities'
2012-02-14 18:18:28 FilterChainProxy [DEBUG] /companies/list at position 2 of 10 in additional filter chain; firing Filter: 'LogoutFilter'
2012-02-14 18:18:28 FilterChainProxy [DEBUG] /companies/list at position 3 of 10 in additional filter chain; firing Filter: 'UsernamePasswordAuthenticationFilter'
2012-02-14 18:18:28 FilterChainProxy [DEBUG] /companies/list at position 4 of 10 in additional filter chain; firing Filter: 'DefaultLoginPageGeneratingFilter'
2012-02-14 18:18:28 FilterChainProxy [DEBUG] /companies/list at position 5 of 10 in additional filter chain; firing Filter: 'RequestCacheAwareFilter'
2012-02-14 18:18:28 FilterChainProxy [DEBUG] /companies/list at position 6 of 10 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter'
2012-02-14 18:18:28 FilterChainProxy [DEBUG] /companies/list at position 7 of 10 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter'
2012-02-14 18:18:28 AnonymousAuthenticationFilter [DEBUG] SecurityContextHolder not populated with anonymous token, as it already contained: 'org.springframework.security.authentication.UsernamePasswordAuthenticationToken@127c16e: Principal: ar.com.held.auth.UserDetails@1250cda; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@fffd3270: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: 4E06EC71A480C21A3CB08DDE2EBFDAF5; Not granted any authorities'
2012-02-14 18:18:28 FilterChainProxy [DEBUG] /companies/list at position 8 of 10 in additional filter chain; firing Filter: 'SessionManagementFilter'
2012-02-14 18:18:28 FilterChainProxy [DEBUG] /companies/list at position 9 of 10 in additional filter chain; firing Filter: 'ExceptionTranslationFilter'
2012-02-14 18:18:28 FilterChainProxy [DEBUG] /companies/list at position 10 of 10 in additional filter chain; firing Filter: 'FilterSecurityInterceptor'
2012-02-14 18:18:28 FilterSecurityInterceptor [DEBUG] Secure object: FilterInvocation: URL: /companies/list; Attributes: [isFullyAuthenticated()]
2012-02-14 18:18:28 FilterSecurityInterceptor [DEBUG] Previously Authenticated: org.springframework.security.authentication.UsernamePasswordAuthenticationToken@127c16e: Principal: ar.com.held.auth.UserDetails@1250cda; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@fffd3270: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: 4E06EC71A480C21A3CB08DDE2EBFDAF5; Not granted any authorities
2012-02-14 18:18:28 AffirmativeBased [DEBUG] Voter: org.springframework.security.web.access.expression.WebExpressionVoter@10932b8, returned: 1
2012-02-14 18:18:28 FilterSecurityInterceptor [DEBUG] Authorization successful
2012-02-14 18:18:28 FilterSecurityInterceptor [DEBUG] RunAsManager did not change Authentication object
2012-02-14 18:18:28 FilterChainProxy [DEBUG] /companies/list reached end of additional filter chain; proceeding with original chain
2012-02-14 18:18:28 DispatcherServlet [DEBUG] DispatcherServlet with name 'spring' processing GET request for [/Held/companies/list]
2012-02-14 18:18:28 RequestMappingHandlerMapping [DEBUG] Looking up handler method for path /companies/list
2012-02-14 18:18:28 RequestMappingHandlerMapping [DEBUG] Returning handler method [public java.lang.String ar.com.held.controller.CompanyController.list(org.springframework.ui.Model)]
2012-02-14 18:18:28 DefaultListableBeanFactory [DEBUG] Returning cached instance of singleton bean 'companyController'
2012-02-14 18:18:28 DispatcherServlet [DEBUG] Last-Modified value for [/Held/companies/list] is: -1
2012-02-14 18:18:28 SharedEntityManagerCreator$SharedEntityManagerInvocationHandler [DEBUG] Creating new EntityManager for shared EntityManager invocation
2012-02-14 18:18:28 SessionImpl [DEBUG] Opened session at timestamp: 13292543088
2012-02-14 18:18:28 LogicalConnectionImpl [DEBUG] Obtaining JDBC connection
2012-02-14 18:18:28 DriverManagerDataSource [DEBUG] Creating new JDBC DriverManager Connection to [jdbc:mysql://localhost:3306/held]
2012-02-14 18:18:28 LogicalConnectionImpl [DEBUG] Obtained JDBC connection
2012-02-14 18:18:28 SQL [DEBUG] select company0_.id as id7_, company0_.version as version7_, company0_.city as city7_, company0_.state as state7_, company0_.street as street7_, company0_.name as name7_, company0_.owner_id as owner7_7_ from Company company0_ where company0_.owner_id=?
2012-02-14 18:18:28 StatefulPersistenceContext [DEBUG] Initializing non-lazy collections
2012-02-14 18:18:28 EntityManagerFactoryUtils [DEBUG] Closing JPA EntityManager
2012-02-14 18:18:28 LogicalConnectionImpl [DEBUG] Releasing JDBC connection
2012-02-14 18:18:28 LogicalConnectionImpl [DEBUG] Released JDBC connection
2012-02-14 18:18:28 ConnectionProxyHandler [DEBUG] HHH000163: Logical connection releasing its physical connection
2012-02-14 18:18:28 DefaultListableBeanFactory [DEBUG] Invoking afterPropertiesSet() on bean with name 'company/list'
2012-02-14 18:18:28 DefaultListableBeanFactory [DEBUG] Returning cached instance of singleton bean 'org.springframework.transaction.config.internalTransactionAdvisor'
2012-02-14 18:18:28 DefaultListableBeanFactory [DEBUG] Returning cached instance of singleton bean 'org.springframework.security.methodSecurityMetadataSourceAdvisor'
2012-02-14 18:18:28 DefaultListableBeanFactory [DEBUG] Returning cached instance of singleton bean 'org.springframework.transaction.config.internalTransactionAdvisor'
2012-02-14 18:18:28 DefaultListableBeanFactory [DEBUG] Returning cached instance of singleton bean 'org.springframework.security.methodSecurityMetadataSourceAdvisor'
2012-02-14 18:18:28 DispatcherServlet [DEBUG] Rendering view [org.springframework.web.servlet.view.JstlView: name 'company/list'; URL [/WEB-INF/view/company/list.jsp]] in DispatcherServlet with name 'spring'
2012-02-14 18:18:28 JstlView [DEBUG] Added model object 'companies' of type [java.util.ArrayList] to request in view with name 'company/list'
2012-02-14 18:18:28 JstlView [DEBUG] Forwarding to resource [/WEB-INF/view/company/list.jsp] in InternalResourceView 'company/list'
2012-02-14 18:18:30 DispatcherServlet [DEBUG] Successfully completed request
2012-02-14 18:18:30 ExceptionTranslationFilter [DEBUG] Chain processed normally
2012-02-14 18:18:30 SecurityContextPersistenceFilter [DEBUG] SecurityContextHolder now cleared, as request processing completed
2012-02-14 18:18:30 AntPathRequestMatcher [DEBUG] Checking match of request : '/resources/img/hp_notepad2_mechapencil.ico'; against '/resources/**'
2012-02-14 18:18:30 FilterChainProxy [DEBUG] /resources/img/hp_notepad2_mechapencil.ico has an empty filter list
2012-02-14 18:18:30 DispatcherServlet [DEBUG] DispatcherServlet with name 'spring' processing GET request for [/Held/resources/img/hp_notepad2_mechapencil.ico]
2012-02-14 18:18:30 RequestMappingHandlerMapping [DEBUG] Looking up handler method for path /resources/img/hp_notepad2_mechapencil.ico
2012-02-14 18:18:30 RequestMappingHandlerMapping [DEBUG] Did not find handler method for [/resources/img/hp_notepad2_mechapencil.ico]
2012-02-14 18:18:30 SimpleUrlHandlerMapping [DEBUG] Matching patterns for request [/resources/img/hp_notepad2_mechapencil.ico] are [/resources/**]
2012-02-14 18:18:30 SimpleUrlHandlerMapping [DEBUG] URI Template variables for request [/resources/img/hp_notepad2_mechapencil.ico] are 
2012-02-14 18:18:30 SimpleUrlHandlerMapping [DEBUG] Mapping [/resources/img/hp_notepad2_mechapencil.ico] to HandlerExecutionChain with handler [org.springframework.web.servlet.resource.ResourceHttpRequestHandler@1ca2fb0] and 1 interceptor
2012-02-14 18:18:30 DispatcherServlet [DEBUG] Last-Modified value for [/Held/resources/img/hp_notepad2_mechapencil.ico] is: -1
2012-02-14 18:18:30 ResourceHttpRequestHandler [DEBUG] Trying relative path [img/hp_notepad2_mechapencil.ico] against base location: ServletContext resource [/resources/]
2012-02-14 18:18:30 ResourceHttpRequestHandler [DEBUG] Found matching resource: ServletContext resource [/resources/img/hp_notepad2_mechapencil.ico]
2012-02-14 18:18:30 ResourceHttpRequestHandler [DEBUG] Determined media type 'image/x-icon' for ServletContext resource [/resources/img/hp_notepad2_mechapencil.ico]
2012-02-14 18:18:30 ResourceHttpRequestHandler [DEBUG] Resource not modified - returning 304
2012-02-14 18:18:30 DispatcherServlet [DEBUG] Null ModelAndView returned to DispatcherServlet with name 'spring': assuming HandlerAdapter completed request handling
2012-02-14 18:18:30 DispatcherServlet [DEBUG] Successfully completed request

你能帮我吗?..我错过了什么吗?

提前致谢。

【问题讨论】:

您需要提供更多详细信息。网址是什么?请求 JSP 时调试日志包含什么内容? 我已经用调试信息编辑了帖子。谢谢 哦..我明白了..感谢调试信息我做了一个测试..我在 list.jsp 上写了 令我惊讶被渲染。所以这意味着我的 sitemesh 模板有问题.. 因为我使用 sitemesh 进行模板,并且我的模板中的同一行没有呈现...我希望清楚.... 【参考方案1】:

问题很简单。所有 spring 安全标签都用于站点网格模板中。我首先在我的 web.xml sitemesh 配置中,然后是 spring 安全配置.. 所以它不起作用.. 它必须首先是 spring security,然后是 sitemesh。

这是web.xml的一部分

<!-- Security -->

    <filter>
      <filter-name>springSecurityFilterChain</filter-name>
      <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>

    <filter-mapping>
      <filter-name>springSecurityFilterChain</filter-name>
      <url-pattern>/*</url-pattern>
    </filter-mapping>
<!-- end security --> 
<!-- Site Mesh -->

    <filter>
        <filter-name>sitemesh</filter-name>
        <filter-class>com.opensymphony.module.sitemesh.filter.PageFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>sitemesh</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

<!-- -->   

你可以看到这个帖子:Spring security tags in sitemesh decorator

感谢卢克·泰勒。他问我调试信息,我意识到发生了什么。

【讨论】:

以上是关于spring security 3.1 isAuthenticated() 不工作的主要内容,如果未能解决你的问题,请参考以下文章

Spring Security 3.1 活动目录认证

spring 3.1 with hibernate 4 with spring security 3.1:如何确保包含所有依赖项以及要包含哪些标签?

Spring Security 3.1 + JPA - 空指针异常

使用 Active Directory 的 Spring Security 3.1

spring security 3.1 isAuthenticated() 不工作

Spring Security 3.1 - 发生会话超时时自动重定向到登录页面