【问题标题】:Spring security custom UserDetails not authenticatingSpring Security 自定义 UserDetails 未进行身份验证
【发布时间】:2018-10-09 11:58:41
【问题描述】:

在试验 Spring Boot、安全性和数据时。

我刚遇到这种情况:

我在内存数据库中使用 H2,并在启动时与一个使用 liquibase 的用户一起使用它 带有用户名和密码。

现在我希望 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;
    }

但我的测试一直失败,

身份验证不应为空

并尝试登录会给我

凭据错误

我的 UserDetailsS​​ervice 自定义实现需要什么?

这是失败的测试:

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

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

【问题讨论】:

    标签: java spring spring-security mockmvc


    【解决方案1】:

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

    auth.setPasswordEncoder(passwordEncoder());
    

    定义 passwordEncoder bean。

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
    

    【讨论】:

    • 但我没有在 H2 上保存编码密码。我将它保存为管理员,root
    • 根据您的回答,我制作了一个自定义密码编码器,它不对密码进行编码,而是将它们作为明文进行比较。现在它的工作
    猜你喜欢
    • 2014-04-20
    • 2014-12-13
    • 2019-02-07
    • 2016-08-05
    • 2020-12-05
    • 2015-04-27
    • 2014-01-12
    • 2016-09-05
    • 2021-04-21
    相关资源
    最近更新 更多