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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2683308/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 07:41:49  来源:igfitidea点击:

Spring Security 3 database authentication with Hibernate

databasehibernateauthenticationspring-security

提问by newbie

I need to authenticate users from database, Spring Security documents don't tell how to authenticate with hibernate. Is that possible and how can I do that?

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

回答by Kdeveloper

You have to make your own custom authentication-provider.

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

Example code:

示例代码:

Service to load Users from Hibernate:

从 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);
  }
}

Service to convert your entity to a spring user object:

将您的实体转换为 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;
  }
}

The namespace-based application-context-security.xml would look something like:

基于命名空间的 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>

回答by Alessandro Giannone

If you're using a JDBC accessible database, then you could use the following authentication-provider and avoid creating a custom one. It cuts down the code required to 9 lines of XML:

如果您使用的是 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>

You can then setup your dataSource as follows

然后,您可以按如下方式设置数据源

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

Have a look at this post: http://codehustler.org/blog/spring-security-tutorial-form-login/It covers everything you need to know about customising Spring Security form-login.

看看这篇文章:http: //codehustler.org/blog/spring-security-tutorial-form-login/它涵盖了关于定制 Spring Security 表单登录你需要知道的一切。

回答by petter

A java configuration could look something like this

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);
    }
}