身份验证请求失败:org.springframework.security.authentication.BadCredentialsException:凭据错误

时间:2014-05-20 09:22:46

标签: spring hibernate spring-mvc spring-security

我正在尝试使用spring安全性实现登录示例,所以我流了一些教程,到目前为止我编写了这段代码:

Role.java:

@Entity
public class Role {
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private int id;
    private String roleName;
    @ManyToMany(mappedBy="roles")
    private List<User> users;

    public Role(){}

    public Role(int id, String roleName, List<User> users) {
        super();
        this.id = id;
        this.roleName = roleName;
        this.users = users;
      //all setter and getters 

}

User.java

@Entity
@Table(name = "User")
public class User implements Serializable{

@Autowired
private SessionFactory factory;

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private int id;
    private String username;
    private String passowrd;
    @ManyToMany
    @JoinTable(name="UserAndRoles",
               joinColumns=@JoinColumn(name="user_id"),
               inverseJoinColumns=@JoinColumn(name="role_id"))
    private List<Role> roles;
    @Enumerated(EnumType.STRING)
    private UserStatus  status;

//构造函数和setter,getters

}

道上课:

public interface UserDao {

    void addUser(User user);

    void editUser(User user);

    void deleteUser(int userId);

    User findUser(int userId);

    User findUserByName(String username);

    List<User> getAllUsers();

}
道实施:

@Repository
public class UserDaoImpl implements UserDao {

    @Autowired
    private SessionFactory session = HibernateUtil.getSessionFactory();

    @Override
    public void addUser(User user) {

        session.getCurrentSession().save(user);
        }
//all methods of Dao Class
    }

和userDetailsS​​ervice类:

@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserDao userDao; 

    @Override
    @Transactional(readOnly = true)
    public UserDetails loadUserByUsername(String username)
            throws UsernameNotFoundException {
        User user=userDao.findUserByName(username);

            if(user!=null)
            {


                String password=user.getPassowrd();

                boolean enabled=user.getStatus().equals(UserStatus.ACTIVE);
                boolean accountNonExpired = user.getStatus().equals(UserStatus.ACTIVE);
                boolean credentialsNonExpired = user.getStatus().equals(UserStatus.ACTIVE);
                boolean accountNonLocked = user.getStatus().equals(UserStatus.ACTIVE);

                //populate user roles

                Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
                for(Role role : user.getRoles()){

                    authorities.add(new GrantedAuthorityImpl(role.getRoleName()));
                }

                //create spring security object
                org.springframework.security.core.userdetails.User securityUser = new 
                    org.springframework.security.core.userdetails.User(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities);

                    return securityUser;
            }else {
                throw new UsernameNotFoundException("user not found !!!");
            }
    }

}

弹簧security.xml文件:

<security:http>
        <security:intercept-url pattern="/**" access="ROLE_USER" />
            <security:form-login />
        <security:logout logout-success-url="/logout" />        
    </security:http>
  <bean id="daoAuthenticationProvider" class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
        <property name="userDetailsService" ref="userDetailsService"></property>
 </bean>
 <bean id="authenticationManager" class="org.springframework.security.authentication.ProviderManager">
        <property name="providers">
            <list>
                    <ref local="daoAuthenticationProvider"/>
            </list>
        </property>
  </bean>
    <bean id="userDetailsService" class="com.dz.hrportal.service.UserDetailsServiceImpl"></bean>
     <security:authentication-manager>
        <security:authentication-provider user-service-ref="userDetailsService">
            <security:password-encoder hash="md5"></security:password-encoder>
        </security:authentication-provider>
    </security:authentication-manager>
    <context:annotation-config />
<context:component-scan base-package="com.dz.hrportal.dao,com.dz.hrportal.dao.impl,com.dz.hrportal.service" />

最后是spring-servlet.xml:

<!-- Hibernate Configurations   -->
        <bean id="propertyConfigurer"    class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="location" value="classpath:jdbc.properties" />
</bean> 
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
    <property name="url" value="jdbc:mysql://localhost:3306/portal"/>
    <property name="username" value="root"/>
    <property name="password" value="root"/>
   </bean>

    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
                <property name="configLocation"     value="classpath:hibernate.cfg.xml" />
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                <prop key="hibernate.show_sql">true</prop>
              </props>
        </property> 

我编写的上面的代码正在成功执行,但它没有获取登录凭据。

我使用的是构建的int spring security的登录表单,我在DB中创建了三个名为:

的表

用户, 角色, userAndRoles

我仍然无法登录。

有人有解决方案吗?

1 个答案:

答案 0 :(得分:1)

在mysql中,工作台password不匹配,或者您无法设置root user的密码。

<强>解决方案:

  1. 打开Mysql工作台
  2. 转到管理数据库连接
  3. 在左侧菜单中,单击localhost(连接名称)
  4. 在密码字段点击Store in Vault,将会打开一个弹出窗口Store Password For Connection
  5. 输入密码为password
  6. 注意:如果您输入root作为密码,则可能会更好地使用8个长度字符作为密码。