【问题标题】:Getting redirect to the authentication failure url when trying to authenticate with Spring Security + Spring MVC尝试使用 Spring Security + Spring MVC 进行身份验证时重定向到身份验证失败 url
【发布时间】:2012-12-31 08:40:26
【问题描述】:

我在实现 Spring Security 以及 Spring MVC 和 Hibernate 时遇到了麻烦。

当我提供凭据并验证表单时,它会转到以下 URL: http://localhost:8080/test/login_error.htm;jsessionid=9BE14BCXXXXXXXXXXXXXXXXX 所以它会将我重定向到我在 spring-security.xml 中配置的 login_error.htm 页面。看起来已经创建了一个会话,所以之后会出现问题。

我确实尝试调试以了解更多信息,这是交易:

由于在我的 spring-security.xml 中将 UserDetailsS​​ervice 配置为我的 authenticationProvider,它进入了 UserDetailsS​​erviceImpl 类中的 findByUserName 方法:

public UserDetails loadUserByUsername(String username)

    throws UsernameNotFoundException, DataAccessException {

        UserEntity userEntity = dao.findByName(username);

        if (userEntity == null)
            throw new UsernameNotFoundException("user not found");

        return (UserDetails)assembler.buildUserFromUserEntity(userEntity);

    }

返回时,用户已正确加载,因此已建立与数据库的连接并找到用户,那一侧没有问题。我不知道问题出在哪里。

这是我正在使用的 UserEntityDAOImpl 类:

@Repository("userEntityDao")
public class UserEntityDAOImpl implements UserEntityDAO {

    private SessionFactory sessionFactory;

    @Autowired
    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    public void addUser(UserEntity user) {
        sessionFactory.getCurrentSession().save(user);
    }

    public UserEntity findByName(String username) {
        Session session = sessionFactory.getCurrentSession();
        UserEntity user = (UserEntity)session.createQuery("select u from UserEntity u where u.username = '" + username + "'").uniqueResult();
        return user;
    }

...others methods like activate, listUsers, etc...

编辑:

@Service("assembler")
public class Assembler {

    @Transactional(readOnly = true)
    User buildUserFromUserEntity(UserEntity userEntity) {

        String username = userEntity.getUsername();
        String password = userEntity.getPassword();
        boolean enabled = userEntity.getActive();
        boolean accountNonExpired = userEntity.getActive();
        boolean credentialsNonExpired = userEntity.getActive();
        boolean accountNonLocked = userEntity.getActive();

        Collection<SimpleGrantedAuthority> authorities = new ArrayList<SimpleGrantedAuthority>();

        for (SecurityRoleEntity role : userEntity.getSecurityRoleCollection()) {
            authorities.add(new SimpleGrantedAuthority(role.getName()));
        }

        User user = new User(username, password, enabled,
        accountNonExpired, credentialsNonExpired, accountNonLocked, authorities);
        return user;

    }

}

它正在从数据库中正确检索角色(在我的例子中为 ROLE_Admin)。

这是我的 spring-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/context 
                        http://www.springframework.org/schema/context/spring-context-3.0.xsd
                        http://www.springframework.org/schema/security 
                        http://www.springframework.org/schema/security/spring-security-3.1.xsd">

    <http pattern="/resources/**" security="none"/>
    <http auto-config='true' use-expressions='true'>
        <intercept-url pattern="/login*" access="isAnonymous()" />
        <intercept-url pattern="/secure/**" access="hasRole('ROLE_Admin')" />

        <logout logout-success-url="/home.htm" />

        <form-login login-page="/login.htm" login-processing-url="/j_spring_security_check"
            authentication-failure-url="/login_error.htm" default-target-url="/home.htm"
            always-use-default-target="true" />
    </http>

    <beans:bean id="com.daoAuthenticationProvider"
        class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
        <beans:property name="userDetailsService" ref="userDetailsService" />
    </beans:bean>

    <beans:bean id="authenticationManager"
        class="org.springframework.security.authentication.ProviderManager">
        <beans:property name="providers">
            <beans:list>
                <beans:ref local="com.daoAuthenticationProvider" />
            </beans:list>
        </beans:property>
    </beans:bean>

    <authentication-manager>
        <authentication-provider user-service-ref="userDetailsService">
            <password-encoder hash="plaintext" />
        </authentication-provider>
    </authentication-manager>
</beans:beans>

这里是 web.xml:

<web-app id="WebApp_ID" version="2.4"
    xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
    http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

    <display-name>Spring MVC Application</display-name>

    <!-- Spring MVC -->
    <servlet>
        <servlet-name>mvc-dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>mvc-dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

</servlet> -->

    <!-- This listener creates the root application Context -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <listener>
        <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
    </listener>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            /WEB-INF/applicationContext.xml
            /WEB-INF/spring-security.xml
        </param-value>
    </context-param>

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

</web-app>

【问题讨论】:

    标签: spring spring-mvc spring-security


    【解决方案1】:

    我怀疑您的用户没有设置所需的权限(即Authorities)。启用Spring Security debug logging。是什么

    assembler.buildUserFromUserEntity(userEntity);
    

    做吗?在将 UserDetails-getAuthorities() 返回到控制台之前,如果在 loadUserByUsername 方法中看到什么?

    【讨论】:

    • 我编辑了我最初的帖子并添加了 Assembler 类的内容。从数据库中正确检索到与用户关联的角色。
    • 打印 UserDetails-getAuthorities(),我在尝试使用具有 ROLE_User 作为安全角色的用户登录时看到 [ROLE_User],或者在尝试使用具有 ROLE_Admin 作为安全角色的用户登录时看到 [ROLE_Admin] .
    • 在遵循您的建议并配置 log4j 之后,我意识到日志记录过程未通过的原因是用户帐户由于某种原因被锁定。这是因为我根据从数据库中取出的用户设置 accountNonLocked 布尔值,但由于我没有任何列,所以它总是被设置为 false...
    猜你喜欢
    • 2016-10-01
    • 2015-07-28
    • 1970-01-01
    • 2011-04-30
    • 2011-10-17
    • 2012-11-21
    • 2012-11-27
    • 2022-08-16
    相关资源
    最近更新 更多