Spring安全自定义UserDetails未进行身份验证

时间:2018-04-29 02:02:17

标签: java spring spring-security mockmvc

在试验弹簧启动,安全性和数据时。

我刚遇到这种情况:

我在内存数据库中使用H2,并在启动时使用liquibase对一个用户进行poblate 用户名和密码。

现在我希望spring security能够对H2进行身份验证。为此,我有这个代码:

@Override
protected void configure(final AuthenticationManagerBuilder auth) throws Exception {
    auth.userDetailsService(userDetailsServiceImp);
 }

并实现userDetails如下:

@Override
public UserDetails loadUserByUsername(String username) {
//this works, the user with pass is pulled
    com.fix.demo.logic.user.User byUsername = 
userRepository.findByUsername(username); 
    if (byUsername == null) {
        System.out.println("No user found with username: ");
        return null; //trow ex here
    }
    User user = new User(byUsername.getUsername(),
            byUsername.getPassword(), true, true,
            true, true, getAuthorities(Collections.singletonList("user")));
    //System.out.println(user.toString());
    //System.out.println(byUsername.toString()+ "   "+byUsername.getPassword());
        return user;
    }

但我的测试仍然失败

  

身份验证不应为null

尝试登录会给我

  

不良凭据

我的UserDetailsS​​ervice的自定义实现有哪些必要?

这是失败的测试:

@Test
public void loginWithValidUserThenAuthenticated() throws Exception {
    FormLoginRequestBuilder login = formLogin()
            .user("admin")
            .password("root");

    mockMvc.perform(login)
            .andExpect(authenticated().withUsername("admin"));
}

1 个答案:

答案 0 :(得分:0)

其中一个原因是,密码可能是我编码的,您需要告诉spring安全性使用编码器。将以下行添加到配置覆盖。

auth.setPasswordEncoder(passwordEncoder());

定义passwordEncoder bean。

@Bean
public PasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder();
}
相关问题