使用UserDetailsS​​ervice和Hibernate登录SpringSecurity表单

时间:2012-07-06 11:38:22

标签: spring hibernate spring-mvc spring-security

我一直在使用Spring Security在SpringMVC中创建有用的表单登录。我是新手,也是Hibernate。我想创建一个简单的表单登录,它可以提供对我的Web应用程序的访问。

我使用SpringSource Tool Suite创建了我的项目并选择了Spring Template Project。它使用Maven,我也使用带有注释和hibernate.cfg.xml的Hibernate类生成。在我的数据库(HSQLDB)中,我有三个表:users,roles和users_roles。第三个包含user_id和role_id,因此它存储有关用户角色的信息。我已经通过Hibernate成功生成了类。

我已经开始编写实现UserDetailsS​​ervice的类了。但我不知道如何正确地做到这一点。在spring-security.xml我已经定义了这样的bean:

<bean id="userDetailsService" class="hutter.pl.services.HutterUserDetailsService" />

我想使用sha-256和saltSource进行散列。

<bean class="org.springframework.security.authentication.dao.ReflectionSaltSource" id="saltSource">
    <property name="userPropertyToUse" value="username"/>
</bean>

<security:authentication-manager>   
    <security:authentication-provider user-service-ref="userDetailsService">
        <security:password-encoder hash="sha-256">
            <security:salt-source ref="saltSource" />
        </security:password-encoder> 
    </security:authentication-provider>
</security:authentication-manager>

我是否应该使用此解决方案:https://stackoverflow.com/a/1654488/845220? Hibernate已经生成了类:RolesHome,Roles,Users,UsersHome,UsersRoles,UsersRolesHome。但我真的不知道如何使用这些Hibernates类来授权用户。

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

    @Transactional(readOnly = true)
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {   
        UsersHome usersHome = new UsersHome();
       //Users user = ...       
       //...            
       return null;     
    }   
}

你能给我一些提示吗?

修改 我尝试将方法public Users findByLogin(String login)添加到UsersHome类。

   public Users findByLogin(String login) {
    log.debug("getting Users instance with login: " + login);
    try {
        Users instance = entityManager.find(Users.class, login);
        log.debug("get successful");
        return instance;
    } catch (RuntimeException re) {
        log.error("get failed", re);
        throw re;
    }
}

我的UserDetailsS​​ervice的主体看起来像:

UsersHome usersHome = new UsersHome();
Users user = usersHome.findByLogin(username);

但我已经有了这个问题:

 ERROR: my.package.dao.UsersHome - get failed
 java.lang.NullPointerException
at my.package.dao.UsersHome.findByLogin(UsersHome.java:72)
at my.package.services.HutterUserDetailsService.loadUserByUsername(MyUserDetailsService.java:19)

1 个答案:

答案 0 :(得分:7)

我认为您不需要自己实现UserService。您可以将jdbc-user-service与数据源一起使用:

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
  <property name="driverClassName" value="com.mysql.jdbc.Driver" />
  <property name="url" value="jdbc:mysql://localhost:3306/mydb" />
  <property name="username" value="root" />
  <property name="password" value="password" />
</bean>

<authentication-manager>
  <authentication-provider>
    <jdbc-user-service data-source-ref="dataSource"
      users-by-username-query="select username,password, enabled from users where username=?"
      authorities-by-username-query="select u.username, ur.authority from users u, user_roles ur  where u.user_id = ur.user_id and u.username =?" 
    />
  </authentication-provider>
</authentication-manager>

使用属性users-by-username-queryusers-by-username-query,您可以定义spring安全性用于从数据源接收用户和权限的查询。

如果

,则必须实施自己的UserService
  • 您想要返回自定义的UserDetails对象(稍后可以通过SecurityContextHolder访问)
  • 用户对象和权限的接收过于复杂和/或无法通过jdbc-user-service
  • 的简单查询进行定义

UserDetailsS​​ervice的可能实现可能如下所示:

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

  @PersistenceContext
  private EntityManager entityManager;

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

    // this works only if username is the primary key of user
    // if thats not the case you have to create a query object to receive the user by username
    User user = entityManager.find(User.class, username); 

    List<GrantedAuthority> roles = .... // get roles for user, depends on your table structure

    if (user == null) {
      // user not found
      throw new UsernameNotFoundException();
    }
    return new MyUserDetails(user, roles);
  }

  private static class MyUserDetails implements UserDetails {
    private User user;
    private List<Role> roles;

    public MyUserDetails(Usere user, List<GrantedAuthority> roles) {
      this.user = user;
      this.roles = roles;
    }

    public Collection<GrantedAuthority> getAuthorities() {
      return roles;
    }

    public String getPassword() {
      return user.getPassword();
    }

    public String getUsername() {
      return user.getUsername();
    }

    // return true for the missing boolean methods..
  }
}

(语法未选中)

对于第一次测试,它可以帮助禁用密码编码器并将未加密的密码存储在数据库中。这可以避免由于错误配置的PasswordEncoders而导致身份验证无法正常工作的问题。一旦您的用户服务运行,您就可以再次添加PasswordEncoder并将散列密码存储在数据库中。

希望它有所帮助: - )