2012-02-12 4 views
3

Я начинаю новый проект с весной mvc 3 и весной безопасности 3.1.0. Я закодировал поставщика аутентификации, класс UserDetails. Очень просто. Аутентификация работает исправно, но когда я использую мой jsp (шаблон с использованием sitemesh), похоже, что он не работает.Весна безопасности 3.1 isAuthenticated() не работает

Вот мой пример.

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

я никогда не увидеть ул и пусто ..

Я не знаю, что я не хватает

Вот моя конфигурация:

безопасности 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> 

UserDetails

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: '[email protected]7c16e: Authentication: org.springframew[email protected]127c16e: Principal: [email protected]; Credentials: [PROTECTED]; Authenticated: true; Details: org.sprin[email protected]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.springframew[email protected]127c16e: Principal: [email protected]; Credentials: [PROTECTED]; Authenticated: true; Details: org.sprin[email protected]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.springframew[email protected]127c16e: Principal: [email protected]; Credentials: [PROTECTED]; Authenticated: true; Details: org.sprin[email protected]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.sp[email protected]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.[email protected]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 

Можете ли вы мне помочь? .. Я что-то пропустил?

Заранее спасибо.

+2

Вам нужно будет предоставить более подробную информацию. Что такое URL? Что делает журнал отладки, когда вы запрашиваете JSP? –

+0

Я отредактировал сообщение с отладочной информацией. Спасибо –

+0

Ох .. я вижу .. благодаря отладочной информации я сделал тест. Я написал в моем списке.jsp и к моему удивлению. Таким образом, это означает, что у меня есть проблема с моим шаблоном sitemesh .. потому что я использую sitemesh для шаблонов, и одна и та же строка в моем шаблоне не отображается ... Я надеюсь, что будет ясно .... –

ответ

7

Проблема была очень простой. Все теги безопасности весны использовались в шаблоне сетки сайта. И у меня есть моя конфигурация sitemesh в web.xml, а затем весенняя конфигурация безопасности. Так что это не сработает. Это должна быть первая весенняя безопасность, а затем 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> 

<!-- --> 

Yo можно увидеть этот пост: Spring security tags in sitemesh decorator

Благодаря Люк Тейлор. Он попросил меня отладочную информацию, и я понял, что произойдет.

+0

спасибо, это сработало для меня! – Jasonw

Смежные вопросы