简体   繁体   中英

error login with spring-security+hibernate

I'm trying to realize a login system with spring security + hibernate.

I have defined these file

spring-security

<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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.1.xsd">

<beans:import resource="classpath*:dispatcher-servlet.xml"/> 

<http auto-config="true" use-expressions="true">
    <intercept-url pattern="/" access="PermittAll"/>
    <intercept-url pattern="/login" access="permitAll"/>
    <intercept-url pattern="/logout" access="permitAll"/>
    <intercept-url pattern="/loginfailed" access="permitAll"/>
    <intercept-url pattern="/intro" access="hasRole('ROLE_MODERATOR')"/>
    <form-login login-page="/login"
                login-processing-url="/j_spring_security_check" 
                default-target-url="/intro"
                authentication-failure-url="/loginfailed" />
    <logout logout-success-url="/logout" />
</http>

<beans:bean id="userDetailsService" class="com.appDial.service.UserDetailsServiceImpl"></beans:bean>

<authentication-manager>
   <authentication-provider user-service-ref="userDetailsService"></authentication-  provider>
</authentication-manager>

</beans:beans>

web-xml

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"  "http://java.sun.com/dtd/web-app_2_3.dtd" >

 <web-app id="WebApp_1383925467813">
 <display-name>Archetype Created Web Application</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml,
             /WEB-INF/spring-security.xml
</param-value>
 </context-param>
<!-- Filter per 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>
     <listener>
     <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
       </listener>
        <servlet>
      <servlet-name>dispatcher</servlet-name>
          <servlet-class>
          org.springframework.web.servlet.DispatcherServlet
          </servlet-class>
       <load-on-startup>1</load-on-startup>
         </servlet>

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

<servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>/m/*</url-pattern>
</servlet-mapping>

 <servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>/t/*</url-pattern>
</servlet-mapping>

  <welcome-file-list>
   <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>


</web-app>

userDetailsService

package com.appDial.service;

import java.util.ArrayList;
import java.util.Collection;
 import java.util.List;

     import org.springframework.beans.factory.annotation.Autowired;
   import org.springframework.context.ApplicationContext;
   import org.springframework.context.support.ClassPathXmlApplicationContext;
   import org.springframework.security.core.GrantedAuthority;
     import org.springframework.security.core.authority.SimpleGrantedAuthority;
    import org.springframework.security.core.userdetails.User;
     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.appDial.hibernateGenerate.Pazienti;
 import com.appDial.hibernateGenerate.PazientiDAO;
 import com.appDial.persistence.PersistencePaziente;

   @Transactional(readOnly=true) 
    @Service("userDetailsService") 
      public class UserDetailsServiceImpl implements UserDetailsService {

@Autowired
private PazientiDAO dao;

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

    ApplicationContext ap = new ClassPathXmlApplicationContext("applicationContext.xml");
    PersistencePaziente pp = (PersistencePaziente) ap.getBean("persistencePaziente");
    Pazienti pazienti= (Pazienti) pp.findByUsername(username);

    if(pazienti==null){
    System.out.println("non trovato!");
        throw new UsernameNotFoundException("user not found");
    }

    System.out.println(""+pazienti.getNome()+"");

    boolean enabled = true;  
    boolean accountNonExpired = true;  
    boolean credentialsNonExpired = true;  
    boolean accountNonLocked = true;
    Integer id=2;

    return new User(  
            pazienti.getUsername(),
            pazienti.getPassword(),
            enabled,   
            accountNonExpired,   
            credentialsNonExpired,   
            accountNonLocked,  
            getAuthorities(id)  
    );  
}  

public Collection<? extends GrantedAuthority> getAuthorities(Integer role) {  
    List<GrantedAuthority> authList = getGrantedAuthorities(getRoles(role));  
    return authList;  
}  

public List<String> getRoles(Integer role) {  

    List<String> roles = new ArrayList<String>();  

    if (role.intValue() == 1) {  
        roles.add("ROLE_MODERATOR");  
        roles.add("ROLE_ADMIN");  
    } else if (role.intValue() == 2) {  
        roles.add("ROLE_MODERATOR");  
    }  
    return roles;  
}  

public static List<GrantedAuthority> getGrantedAuthorities(List<String> roles) {  
    List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();  

    for (String role : roles) {  
        authorities.add(new SimpleGrantedAuthority(role));  
    }  
    return authorities;  
}  

}

When I try to login, I am always given error and you do not create a connection to the database

@Transactional(readOnly=true) 
@Service("userDetailsService") 
public class UserDetailsServiceImpl implements UserDetailsService {

@Autowired
private PazientiDAO dao;

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

    ApplicationContext ap = new ClassPathXmlApplicationContext("applicationContext.xml");
    PersistencePaziente pp = (PersistencePaziente) ap.getBean("persistencePaziente");
    Pazienti pazienti= (Pazienti) pp.findByUsername(username);

    if(pazienti==null){
    System.out.println("non trovato!");
        throw new UsernameNotFoundException("user not found");
    }

    System.out.println(""+pazienti.getNome()+"");

    boolean enabled = true;  
    boolean accountNonExpired = true;  
    boolean credentialsNonExpired = true;  
    boolean accountNonLocked = true;
    Integer id=2;

    return new User(  
            pazienti.getUsername(),
            pazienti.getPassword(),
            enabled,   
            accountNonExpired,   
            credentialsNonExpired,   
            accountNonLocked,  
            getAuthorities(id)  
    );  
}  

Your service implementation is wrong. NEVER construct a new instance of an ApplicationContext in your code (when you start doing that all kinds of alarm bells should start to ring!). Use dependency injection to get the needed dependencies.

Your solution will eventually grind your database to a halt with all the database connections you are creating, each time a new sessionfactory and transactionmanager and eventually your application will grind to a halt due to memory issues or database locks. (I assume that that isn't what you want?).

I would expect something like the following

@Transactional(readOnly=true) 
@Service("userDetailsService") 
public class UserDetailsServiceImpl implements UserDetailsService {

@Autowired
private PazientiDAO dao;

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

    Pazienti pazienti= dao.findUser(username);

    if(pazienti==null){
        System.out.println("non trovato!");
        throw new UsernameNotFoundException("user not found");
    }

    System.out.println(""+pazienti.getNome()+"");

    boolean enabled = true;  
    boolean accountNonExpired = true;  
    boolean credentialsNonExpired = true;  
    boolean accountNonLocked = true;
    Integer id=2;

    return new User(  
            pazienti.getUsername(),
            pazienti.getPassword(),
            enabled,   
            accountNonExpired,   
            credentialsNonExpired,   
            accountNonLocked,  
            getAuthorities(id)  
    );  
}  

I assume you aren't injecting the PazientiDAO just because you can but because you want to use it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM