使用Hibernate进行Spring Security 3数据库身份验证

时间:2010-04-21 13:32:07

标签: database hibernate authentication spring-security

我需要从数据库验证用户,Spring Security文档没有告诉如何使用hibernate进行身份验证。这可能吗?我该怎么做?

3 个答案:

答案 0 :(得分:133)

您必须制作自己的自定义身份验证提供程序。

示例代码:

从Hibernate加载用户的服务:

import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;    

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

  @Autowired private UserDao dao;
  @Autowired private Assembler assembler;

  @Transactional(readOnly = true)
  public UserDetails loadUserByUsername(String username)
      throws UsernameNotFoundException, DataAccessException {

    UserDetails userDetails = null;
    UserEntity userEntity = dao.findByName(username);
    if (userEntity == null)
      throw new UsernameNotFoundException("user not found");

    return assembler.buildUserFromUserEntity(userEntity);
  }
}

将您的实体转换为spring用户对象的服务:

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.User;

@Service("assembler")
public class Assembler {

  @Transactional(readOnly = true)
  User buildUserFromUserEntity(UserEntity userEntity) {

    String username = userEntity.getName();
    String password = userEntity.getPassword();
    boolean enabled = userEntity.isActive();
    boolean accountNonExpired = userEntity.isActive();
    boolean credentialsNonExpired = userEntity.isActive();
    boolean accountNonLocked = userEntity.isActive();

    Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
    for (SecurityRoleEntity role : userEntity.getRoles()) {
      authorities.add(new GrantedAuthorityImpl(role.getRoleName()));
    }

    User user = new User(username, password, enabled,
      accountNonExpired, credentialsNonExpired, accountNonLocked, authorities, id);
    return user;
  }
}

基于命名空间的application-context-security.xml类似于:

<http>
  <intercept-url pattern="/login.do*" filters="none"/>
  <intercept-url pattern="/**" access="IS_AUTHENTICATED_ANONYMOUSLY" />
  <form-login login-page="/login.do"
              authentication-failure-url="/login.do?error=failed"
              login-processing-url="/login-please.do" />
  <logout logout-url="/logoff-please.do"
          logout-success-url="/logoff.html" />
</http>

<beans:bean id="daoAuthenticationProvider"
 class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
  <beans:property name="userDetailsService" ref="userDetailsService"/>
</beans:bean>

<beans:bean id="authenticationManager"
    class="org.springframework.security.authentication.ProviderManager">
  <beans:property name="providers">
    <beans:list>
      <beans:ref local="daoAuthenticationProvider" />
    </beans:list>
  </beans:property>
</beans:bean>

<authentication-manager>
  <authentication-provider user-service-ref="userDetailsService">
    <password-encoder hash="md5"/>
  </authentication-provider>
</authentication-manager>

答案 1 :(得分:4)

如果您正在使用JDBC可访问数据库,则可以使用以下身份验证提供程序,并避免创建自定义数据库。它减少了9行XML所需的代码:

<authentication-provider>
    <jdbc-user-service data-source-ref="dataSource" users-by-username-query="select username,password from users where username=?" authorities-by-username-query="select u.username, r.authority from users u, roles r where u.userid = r.userid and u.username =?" />
</authentication-provider>

然后您可以按如下方式设置您的dataSource

<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/DB_NAME" />
    <property name="username" value="root" />
    <property name="password" value="password" />
</bean>

看一下这篇文章:http://codehustler.org/blog/spring-security-tutorial-form-login/ 它涵盖了您需要了解的有关自定义Spring Security表单登录的所有信息。

答案 2 :(得分:1)

java配置看起来像这样

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsServiceImpl userDetailsService;

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth)
            throws Exception {

        DaoAuthenticationProvider daoAuthenticationProvider =
                new DaoAuthenticationProvider();
        daoAuthenticationProvider
                .setUserDetailsService(userDetailsService);

        auth.authenticationProvider(daoAuthenticationProvider);
    }
}