Spring secutity:自定义userdetailService不可见没有bean命名为' myUserDetailsS​​ervice'被定义为

时间:2015-12-21 12:20:54

标签: java spring spring-mvc spring-security

有人可以帮助我,这是我的弹簧安全问题,我的CustomuserDetailsS​​ervice bean不被身份验证提供者看到,如图所示

1 is not ok mean while 2,3 and 4 say it should be

web.xml
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
    /WEB-INF/spring/root-context.xml,
    /WEB-INF/spring/spring-security.xml
    </param-value>
</context-param>  

<!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<!-- Processes application requests -->
<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/servlet-context.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>

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

spring_security.xml

<http auto-config="true" use-expressions="true" >
    <!--<intercept-url pattern="/admin**" access="hasAnyRole('ROLE_USER', 'ROLE_ADMIN')" />-->
     <intercept-url pattern="/admin**" access="hasAnyRole('ROLE_USER', 'ROLE_ADMIN')" /> 
    <!-- <intercept-url pattern="/login*" access="hasRole('IS_AUTHENTICATED_ANONYMOUSLY')"/>  -->


    <!-- access denied page -->
    <access-denied-handler error-page="/403" />
    <form-login 
        login-page="/login" 
        default-target-url="/welcome"
        authentication-failure-url="/login?error" 
        username-parameter="username"
        password-parameter="password" />

    <logout logout-success-url="/login?logout" />
    <!-- enable csrf protection -->
    <csrf />
</http>

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

 <!-- <authentication-provider>
    <user-service>
    <user name="mkyong" password="123456" authorities="ROLE_ADMIN,ROLE_USER" />
    <user name="junior" password="toto" authorities="ROLE_USER" />
    </user-service>
  </authentication-provider>-->
</authentication-manager>

myUserDetailssService

@Service("myUserDetailsService")
@Transactional(readOnly=true)
public class MyUserDetailsService implements UserDetailsService {

    @Autowired
    private UserService userDao;

    private static final Logger logger = LoggerFactory.getLogger(MyUserDetailsService.class);


    @Override
    public UserDetails loadUserByUsername(final String username) 
               throws UsernameNotFoundException {

        Users user = userDao.findByUserName(username);

        logger.info("myuserdetail user = ("+user.getPassword()+","+user.getUsername()+","+user.getEnabled()+")");

        Iterator iter = user.getUserRoleses().iterator();
        while(iter.hasNext()){
            UserRoles r = (UserRoles) iter.next();
            logger.info("role= "+r.getRole());
        }
        List<GrantedAuthority> authorities = buildUserAuthority(user.getUserRoleses());


        return this.buildUserForAuthentication(user, authorities);


    }


    // Converts com.psud.model.Users user to
    // org.springframework.security.core.userdetails.User

    private User buildUserForAuthentication(Users user, List<GrantedAuthority> authorities) {
        logger.info("myuserdetail2 user2 ");
        User u = new User(user.getUsername(), user.getPassword(),(( user.getEnabled() == 1)?true:false), 
                true, true, true, authorities);
        logger.info("myuserdetail2 user2");

        logger.info("myuserdetail2 user2 = "+u.getUsername());
        return u;
    }


    private List<GrantedAuthority> buildUserAuthority(Set<UserRoles> userRoles) {

        Set<GrantedAuthority> setAuths = new HashSet<GrantedAuthority>();

        // Build user's authorities
        for (UserRoles userRole : userRoles) {
            setAuths.add(new SimpleGrantedAuthority(userRole.getRole()));
        }

        List<GrantedAuthority> Result = new ArrayList<GrantedAuthority>(setAuths);

        return Result;
    }
}



root*.xml


    <!-- Root Context: defines shared resources visible to all other web components -->
    <bean id="test" class="com.psud.gestiondroit.Test">
    </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/droits" />
        <property name="username" value="root" />
        <property name="password" value="" />
    </bean>

       <bean id="sessionFactory"
     class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
      <property name="dataSource" ref="dataSource" />
      <property name="packagesToScan" value="com.psud.gestiondroit.model" />

      <property name="hibernateProperties">
         <props>
            <prop key="hibernate.show_sql">true</prop>
            <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
         </props>
      </property>
   </bean>  



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


servlet*.xml

    <!-- Enables the Spring MVC @Controller programming model -->
    <annotation-driven />
    <context:annotation-config />
    <tx:annotation-driven transaction-manager="transactionManager"/>

    <!-- 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 -->
    <beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <beans:property name="prefix" value="/WEB-INF/views/" />
        <beans:property name="suffix" value=".jsp" />
    </beans:bean>

    <context:component-scan base-package="com.psud.gestiondroit" />

1 个答案:

答案 0 :(得分:0)

Hello gael this is my spring config files(root and servlet as generated by spring Tools on eclipse):

root*.xml


    <!-- Root Context: defines shared resources visible to all other web components -->
    <bean id="test" class="com.psud.gestiondroit.Test">
    </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/droits" />
        <property name="username" value="root" />
        <property name="password" value="" />
    </bean>

       <bean id="sessionFactory"
     class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
      <property name="dataSource" ref="dataSource" />
      <property name="packagesToScan" value="com.psud.gestiondroit.model" />

      <property name="hibernateProperties">
         <props>
            <prop key="hibernate.show_sql">true</prop>
            <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
         </props>
      </property>
   </bean>  



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


servlet*.xml

    <!-- Enables the Spring MVC @Controller programming model -->
    <annotation-driven />
    <context:annotation-config />
    <tx:annotation-driven transaction-manager="transactionManager"/>

    <!-- 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 -->
    <beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <beans:property name="prefix" value="/WEB-INF/views/" />
        <beans:property name="suffix" value=".jsp" />
    </beans:bean>

    <context:component-scan base-package="com.psud.gestiondroit" />