使用自定义登录表单的UserDetailsS​​ervice进行Spring安全性jdbc身份验证

时间:2016-10-24 03:13:11

标签: java spring spring-mvc spring-security

人们我需要一些关于这个主题的帮助..我真的很新使用Spring Security而且我正在尝试使用带有数据库身份验证的自定义登录表单,但我没有得到积极的结果。

当我在我的网页上点击按钮登录时,我的应用程序正在抛出此异常:

enter image description here

org.springframework.security.authentication.InternalAuthenticationServiceException
at org.springframework.security.authentication.dao.DaoAuthenticationProvider.retrieveUser(DaoAuthenticationProvider.java:125)
at org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider.authenticate(AbstractUserDetailsAuthenticationProvider.java:143)
at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:167)
at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:192)
at org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter.attemptAuthentication(UsernamePasswordAuthenticationFilter.java:93)
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:217)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:120)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.csrf.CsrfFilter.doFilterInternal(CsrfFilter.java:120)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:64)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:53)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:91)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:213)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:176)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:262)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:528)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1099)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:670)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1520)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1476)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.NullPointerException
at com.alcaldia.lineatransportealcaldiafalcon.service.CustomUserDetailsService.loadUserByUsername(CustomUserDetailsService.java:28)
at org.springframework.security.authentication.dao.DaoAuthenticationProvider.retrieveUser(DaoAuthenticationProvider.java:114)

以下是对应代码:  customUserDetailsS​​ervice

@Service("customUserDetailsService")
public class CustomUserDetailsService implements UserDetailsService{

@Autowired
private UserService userService;

@Transactional(readOnly=true)
public UserDetails loadUserByUsername(String ssoId)
        throws UsernameNotFoundException {
    //User user = userService.findBySso(ssoId);
    User user = userService.findBySso(ssoId);
    System.out.println("User : "+user);
    if(user==null){
        System.out.println("User not found");
        throw new UsernameNotFoundException("Username not found");
    }
        return new org.springframework.security.core.userdetails.User(user.getSsoId(), user.getPassword(), 
             user.getState().equals("Active"), true, true, true, getGrantedAuthorities(user));
}


private List<GrantedAuthority> getGrantedAuthorities(User user){
    List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();

    for(UserProfile userProfile : user.getUserProfiles()){
        System.out.println("UserProfile : "+userProfile);
        authorities.add(new SimpleGrantedAuthority("ROLE_"+userProfile.getType()));
    }
    System.out.print("authorities :"+authorities);
    return authorities;
}

}

UserService

public interface UserService {

User findById(int id);

User findBySso(String sso);

}

UserServiceImpl

@Service("userService")
public class UserServiceImpl implements UserService{

private static Log logger = LogFactory.getLog(UserServiceImpl.class);
@Autowired
private UserDao dao;

@Transactional
public User findById(int id) {
    return dao.findById(id);
}

@Transactional
public User findBySso(String sso) {
    System.err.println("ESTOY EN EL USERSERVICEIMPL");
    logger.error("ESTOY EN EL USERSERVICEIMPL   " + sso);
    logger.error("****************************");
    return dao.findBySSO(sso);
} 
}

userDAO的     public interface UserDao {

User findById(int id);

User findBySSO(String sso);

}

在UserDAOImpl

@Repository("userDao")
public class UserDaoImpl extends AbstractDao<Integer, User> implements UserDao {

private static Log logger = LogFactory.getLog(UserDaoImpl.class);

public User findById(int id) {
    return getByKey(id);
}

public User findBySSO(String sso) {
    System.err.println("ESTOY EN EL userdaoimpl");
    logger.error("ESTOY EN EL userdaoimpl   " + sso);
    logger.error("****************************");
    Criteria crit = createEntityCriteria();
    crit.add(Restrictions.eq("ssoId", sso));
    return (User) crit.uniqueResult();
}

}

AbstractDao的

public abstract class AbstractDao<PK extends Serializable, T> {

private final Class<T> persistentClass;

@SuppressWarnings("unchecked")
public AbstractDao(){
    this.persistentClass =(Class<T>) ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[1];
}

@PersistenceContext
EntityManager em;


@SuppressWarnings("unchecked")
public T getByKey(PK key) {
    return (T) em.find(persistentClass, key);
    //return (T) getSession().get(persistentClass, key);

}

public void persist(T entity) {
    em.persist(entity);
}

public void delete(T entity) {
    em.remove(entity);
}

protected Criteria createEntityCriteria(){
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<T> criteria = cb.createQuery(persistentClass);

    return (Criteria) criteria;
} 
}

和我的安全协议

<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-4.1.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-4.0.xsd">

<http auto-config="true" >
    <intercept-url pattern="/" access="permitAll" />
    <intercept-url pattern="/home" access="permitAll" />
    <intercept-url pattern="/admin**" access="hasRole('ADMIN')" />
    <intercept-url pattern="/dba**" access="hasRole('ADMIN') and     hasRole('DBA')" />
    <form-login  login-page="/login"
                 username-parameter="ssoId"
                 password-parameter="password"
                 authentication-failure-url="/Access_Denied" />
    <csrf/>
</http>

<authentication-manager >
    <authentication-provider user-service-ref="customUserDetailsService"/>
</authentication-manager>
  <beans:bean id="customUserDetailsService" class="com.alcaldia.lineatransportealcaldiafalcon.service.CustomUserDetailsService" />

</beans:beans>

但我正在接受NPE ..我已经研究了另一个例子,但不知何故它们都没有为我工作:/这个例子它是唯一一个&#34;工作&#34;但它还没有完全发挥作用。

请帮帮我,我缺少什么?

编辑:我正在添加servlet-context.xml

<mvc:annotation-driven/>   

<context:component-scan base-package="com.alcaldia.lineatransportealcaldiafalcon.service" />

            

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
    <property name="driverClassName" value="net.sourceforge.jtds.jdbc.Driver" />
    <property name="url" value="jdbc:jtds:sqlserver://localhost/:1433;DatabaseName=learning" />
    <property name="username" value="sa" />
    <property name="password" value="Osman1994*" />
</bean>

<bean class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" id="entityManagerFactory">
  <property name="persistenceUnitName" value="persistenceUnit"/>
  <property name="dataSource" ref="dataSource"/>
</bean> -->

<!-- Configure the entity manager factory bean -->
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="dataSource" ref="dataSource"/>
    <property name="packagesToScan" value="com.alcaldia.lineatransportealcaldiafalcon.model"/>
    <property name="jpaVendorAdapter">
        <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>
    </property>
    <property name="jpaProperties">
        <props>
            <prop key="hibernate.dialect">org.hibernate.dialect.SQLServer2012Dialect</prop>
            <prop key="hibernate.show_sql">true</prop>
        </props>
    </property>
</bean>

<!-- Configure the transaction manager bean -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
    <property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>

<!-- Enable annotation driven transaction management -->
<tx:annotation-driven/>

<!-- Transaction Manager
<bean class="org.springframework.orm.jpa.JpaTransactionManager" id="transactionManager">
  <property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean> -->

<!-- Enable @Transactional annotation
<tx:annotation-driven/> -->

0 个答案:

没有答案