为什么以下Java Spring Security代码会抛出" Bad Credential Exception"?

时间:2016-03-07 12:26:37

标签: java xml spring spring-mvc spring-security

以下是代码,我已经使用BCrypt密码编码器在数据库中插入数据。插入时我在java代码中做了BCrypt。我正在为我的项目添加Spring Security。作为第一阶段,我将BCrypt添加到我的spring-security.xml中,然后尝试登录并调试代码,我看到" Bad Credentials Exception"

的web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/spring/root-context.xml,
                /WEB-INF/spring/appServlet/spring-security.xml</param-value>
  </context-param>

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

  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <servlet>
    <servlet-name>appServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>
                /WEB-INF/spring/appServlet/spring-security.xml
            </param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>appServlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

弹簧security.xml文件

<?xml version="1.0" encoding="UTF-8"?>

<b:beans xmlns="http://www.springframework.org/schema/mvc"
    xmlns:b="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:context="http://www.springframework.org/schema/context" 
    xmlns:security="http://www.springframework.org/schema/security"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
        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.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
        http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd">
    <tx:annotation-driven transaction-manager="transactionManager"/>
    <b:bean class="org.springframework.security.web.access.expression.DefaultWebSecurityExpressionHandler"/>

       <security:authentication-manager >
            <security:authentication-provider user-service-ref="personService">
                <security:password-encoder ref="encoder"/>
            </security:authentication-provider> 
       </security:authentication-manager> 


     <security:global-method-security secured-annotations="enabled"/>
    <b:bean id="personDAO" class="com.cT.www.dao.PersonDAOImpl">
        <b:property name="sessionFactory" ref="hibernate4AnnotatedSessionFactory" />
    </b:bean>
<!-- For hashing and salting user passwords -->
    <b:bean id="encoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder"/>   

    <b:bean id="personService" class="com.cT.www.service.PersonServiceImpl">
        <b:property name="personDAO" ref="personDAO"></b:property>
    </b:bean>

    <security:http use-expressions='true'>
         <security:form-login login-page="/login" default-target-url="/loginSuccess"
            authentication-failure-url="/home" 
            username-parameter="mobile_Number"
            password-parameter="password"/> 
          <security:intercept-url pattern="/home" access="permitAll" />
          <security:intercept-url pattern="/RankOption/**" access="hasRole('ROLE_ADMIN')" />
          <security:logout logout-url="/logout"/>
    </security:http>

    <b:bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close">
        <b:property name="driverClassName" value="com.mysql.jdbc.Driver" /> 
        <b:property name="url"
            value="jdbc:mysql://121.0.0.1:3306/testDB" />
        <b:property name="username" value="root" />
        <b:property name="password" value="" />
    </b:bean>

    <!--  Form Validator -->

    <b:bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <b:property name="sessionFactory" ref="hibernate4AnnotatedSessionFactory" />
    </b:bean> 


    <!-- Hibernate 4 SessionFactory Bean definition -->
    <b:bean id="hibernate4AnnotatedSessionFactory"
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <b:property name="dataSource" ref="dataSource" />
        <b:property name="packagesToScan">
            <b:list>
                <b:value>com.cT.www.model</b:value>
                    </b:list>
        </b:property>
        <b:property name="hibernateProperties">
            <b:props>
                <b:prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect
                </b:prop>
                <b:prop key="hibernate.show_sql">true</b:prop>
            </b:props>
        </b:property>
    </b:bean>

    <context:component-scan base-package="com.cT.www" />

        <!-- Enables the Spring MVC @Controller programming model -->
    <annotation-driven />

    <!-- Handles HTTP GET requests for /resources/** by efficiently serving 
        up static resources in the ${webappRoot}/resources directory -->
    <resources mapping="/resources/**" location="/resources/" />

    <!-- Resolves views selected for rendering by @Controllers to .jsp resources 
        in the /WEB-INF/views directory -->
    <b:bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <b:property name="prefix" value="/WEB-INF/views/" />
        <b:property name="suffix" value=".jsp" />
    </b:bean>

</b:beans>

PersonServiceImpl.java

package com.cT.www.service;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.cT.www.dao.PersonDAO;
import com.cT.www.model.Best_Option_Questions;
import com.cT.www.model.Options;
import com.cT.www.model.Person;
import com.cT.www.model.Questions;
import com.cT.www.model.Rank_Option_Questions;
import com.cT.www.model.Reset_Password;
import com.cT.www.model.UserSignUp;
import com.cT.www.model.UserVerification;
import com.cT.www.model.Yes_Or_No;

@Service
public class PersonServiceImpl implements PersonService, UserDetailsService {

    private PersonDAO personDAO;

    public void setPersonDAO(PersonDAO personDAO) {
        this.personDAO = personDAO;
    }



    @Override
    @Transactional
    public List getMobile_Number_N_Password(String mobile_Number) {
        // TODO Auto-generated method stub
        return this.personDAO.getMobile_Number_N_Password(mobile_Number);
    }


    @Override
    @Transactional
    public UserDetails loadUserByUsername(String mobile_Number)
            throws UsernameNotFoundException {
        // TODO Auto-generated method stub
        // return this.getMobile_Number_N_Password(Long.parseLong(mobile_Number));


        List result = personDAO.getMobile_Number_N_Password(mobile_Number);

        String existing_Password = null;
        Boolean verification_Boolean = false;
        if(result != null){
            if(result.get(0) != null){
                for(Iterator itr = result.iterator(); itr.hasNext();){

                    Object[] myResult = (Object[]) itr.next();

                    existing_Password = (String) myResult[0];

                    verification_Boolean = (Boolean) myResult[1];



                }           
            }   


        }   

        if(result == null){
            throw new UsernameNotFoundException("No user found with mobile number" + mobile_Number);
        }



        return new org.springframework.security.core.userdetails.User(mobile_Number, 
                existing_Password,true, true, true, true, getGrantedAuthorities());


    }



    private List<GrantedAuthority> getGrantedAuthorities(){

         List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
         authorities.add(new SimpleGrantedAuthority("VERIFIED_USER"));
        return authorities;


    }

}

0 个答案:

没有答案