如何使用Spring Security不存在用户时显示错误消息?

时间:2013-06-08 18:56:41

标签: java spring authentication spring-security

我是Spring Security的新手。我尝试使用条件is:question [spring-security] error message when user does not exist进行搜索,但没有帖子帮助。

目前,我使用Spring Security 3.1在我的网络应用程序中验证用户身份。我的实现如下:

  1. DaoAuthenticationProvider用作AuthenticationProvider
  2. 编写UserDetailsService
  3. 使用的DaoAuthenticationProvider的实现

    这是userDetailsServiceImpl bean:

    @Service("userDetailsServiceImpl")
    @Transactional(readOnly = true, propagation = Propagation.REQUIRED)
    public class UserDetailsServiceImpl implements UserDetailsService {
    
        @Autowired
        private UserDao userDao;
    
        @Override
        public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
            User existingUser = this.userDao.getUserByUsername(username);
            // TODO create a schema for storing ROLEs in database
            List<GrantedAuthority> roles = new ArrayList<GrantedAuthority>();
            roles.add(Role.USER);
    
            org.springframework.security.core.userdetails.User user = new org.springframework.security.core.userdetails.User(
                    existingUser.getUsername(), existingUser.getPassword(), existingUser.getEnable(), true, true, true, roles);
            return user;
        }
    
    }
    

    我在login.ftl(我正在使用freemarker)中显示错误消息,如下所示:

    <#if Session.SPRING_SECURITY_LAST_EXCEPTION?? 
        && Session.SPRING_SECURITY_LAST_EXCEPTION.message?has_content>
        <br />Message: ${Session.SPRING_SECURITY_LAST_EXCEPTION.message} 
    </#if>
    

    一切正常,但输入非现有用户名时登录页面上不会显示任何消息。我检查了console,但没有看到任何异常。

    2013-06-09 02:25:38.082 [DEBUG] [org.springframework.orm.hibernate4.HibernateTransactionManager] - Creating new transaction with name [net.dntuan.training.mvc.security.authentication.UserDetailsServiceImpl.loadUserByUsername]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT,readOnly; '' (AbstractPlatformTransactionManager.java:366)
    2013-06-09 02:25:38.162 [DEBUG] [org.springframework.orm.hibernate4.HibernateTransactionManager] - Opened new Session [SessionImpl(PersistenceContext[entityKeys=[],collectionKeys=[]];ActionQueue[insertions=[] updates=[] deletions=[] collectionCreations=[] collectionRemovals=[] collectionUpdates=[] unresolvedInsertDependencies=UnresolvedEntityInsertActions[]])] for Hibernate transaction (HibernateTransactionManager.java:416)
    2013-06-09 02:25:38.167 [DEBUG] [org.springframework.orm.hibernate4.HibernateTransactionManager] - Preparing JDBC Connection of Hibernate Session [SessionImpl(PersistenceContext[entityKeys=[],collectionKeys=[]];ActionQueue[insertions=[] updates=[] deletions=[] collectionCreations=[] collectionRemovals=[] collectionUpdates=[] unresolvedInsertDependencies=UnresolvedEntityInsertActions[]])] (HibernateTransactionManager.java:426)
    2013-06-09 02:25:38.234 [DEBUG] [org.springframework.orm.hibernate4.HibernateTransactionManager] - Exposing Hibernate transaction as JDBC transaction [org.postgresql.jdbc4.Jdbc4Connection@2b9fd66a] (HibernateTransactionManager.java:487)
    Hibernate: select this_.id as id1_1_0_, this_.enable as enable2_1_0_, this_.fullname as fullname3_1_0_, this_.password as password4_1_0_, this_.username as username5_1_0_ from public.user this_ where this_.username=?
    2013-06-09 02:25:38.367 [TRACE] [org.springframework.orm.hibernate4.HibernateTransactionManager] - Triggering beforeCompletion synchronization (AbstractPlatformTransactionManager.java:936)
    2013-06-09 02:25:38.367 [DEBUG] [org.springframework.orm.hibernate4.HibernateTransactionManager] - Initiating transaction rollback (AbstractPlatformTransactionManager.java:844)
    2013-06-09 02:25:38.367 [DEBUG] [org.springframework.orm.hibernate4.HibernateTransactionManager] - Rolling back Hibernate transaction on Session [SessionImpl(PersistenceContext[entityKeys=[],collectionKeys=[]];ActionQueue[insertions=[] updates=[] deletions=[] collectionCreations=[] collectionRemovals=[] collectionUpdates=[] unresolvedInsertDependencies=UnresolvedEntityInsertActions[]])] (HibernateTransactionManager.java:570)
    2013-06-09 02:25:38.371 [TRACE] [org.springframework.orm.hibernate4.HibernateTransactionManager] - Triggering afterCompletion synchronization (AbstractPlatformTransactionManager.java:965)
    2013-06-09 02:25:38.372 [DEBUG] [org.springframework.orm.hibernate4.HibernateTransactionManager] - Closing Hibernate Session [SessionImpl(PersistenceContext[entityKeys=[],collectionKeys=[]];ActionQueue[insertions=[] updates=[] deletions=[] collectionCreations=[] collectionRemovals=[] collectionUpdates=[] unresolvedInsertDependencies=UnresolvedEntityInsertActions[]])] after transaction (HibernateTransactionManager.java:632)
    

    在这种情况下是否可以显示错误消息?

1 个答案:

答案 0 :(得分:5)

由于您正在实现UserDetailsS​​ervice,因此您需要手动抛出UsernameNotFoundException,以告知Spring Security未找到尝试登录的用户。它会是这样的:

User existingUser = this.userDao.getUserByUsername(username);
if (existingUser != null) {
    List<GrantedAuthority> roles = new ArrayList<GrantedAuthority>();
    roles.add(Role.USER);

    org.springframework.security.core.userdetails.User user = new org.springframework.security.core.userdetails.User(
            existingUser.getUsername(), existingUser.getPassword(), existingUser.getEnable(), true, true, true, roles);
    return user;
} else {
    throw new UsernameNotFoundException("User not found");
}