通过数据库身份验证,没有映射ID为“null”的PasswordEncoder - java

我成功地建立了内存中身份验证。但是,当我要用数据库构建它时,会出现此错误。

没有为id“null”映射的PasswordEncoder

这是后续教程-Spring Boot Tutorial for Beginners, 10 - Advanced Authentication using Spring Security | Mighty Java

有班

SpringSecurityConfiguration.java

@Configuration
@EnableWebSecurity
public class SpringSecurityConfiguration extends 
WebSecurityConfigurerAdapter{

@Autowired
private AuthenticationEntryPoint entryPoint;

@Autowired
private MyUserDetailsService userDetailsService;

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

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests().anyRequest().authenticated().and().httpBasic()
        .authenticationEntryPoint(entryPoint);
}

}

AuthenticationEntryPoint.java

@Configuration
public class AuthenticationEntryPoint extends BasicAuthenticationEntryPoint{


@Override
public void commence(HttpServletRequest request, HttpServletResponse response,
        AuthenticationException authException) throws IOException, ServletException {

    response.addHeader("WWW-Authenticate", "Basic realm -" +getRealmName());
    response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    PrintWriter writer = response.getWriter();
    writer.println("Http Status 401 "+authException.getMessage());
}

@Override
public void afterPropertiesSet() throws Exception {
    setRealmName("MightyJava");
    super.afterPropertiesSet();
}

}

MyUserDetailsS​​ervice .java

@Service
public class MyUserDetailsService implements UserDetailsService{

@Autowired
private UserRepository userRepository;

@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    User user = userRepository.findByUsername(username);
    if(user == null){
        throw new UsernameNotFoundException("User Name "+username +"Not Found");
    }
    return new org.springframework.security.core.userdetails.User(user.getUserName(),user.getPassword(),getGrantedAuthorities(user));
}

private Collection<GrantedAuthority> getGrantedAuthorities(User user){

    Collection<GrantedAuthority> grantedAuthority = new ArrayList<>();
    if(user.getRole().getName().equals("admin")){
        grantedAuthority.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
    }
    grantedAuthority.add(new SimpleGrantedAuthority("ROLE_USER"));
    return grantedAuthority;
}
}

UserRepository界面

public interface UserRepository extends JpaRepository<User, Long>{

@Query("FROM User WHERE userName =:username")
User findByUsername(@Param("username") String username);

}

角色.java

@Entity
public class Role extends AbstractPersistable<Long>{

private String name;

@OneToMany(targetEntity = User.class , mappedBy = "role" , fetch = FetchType.LAZY ,cascade = CascadeType.ALL)
private Set<User> users;

//getter and setter
}

User.java

@Entity
public class User extends AbstractPersistable<Long>{

//AbstractPersistable class ignore primary key and column annotation(@Column)

private String userId;
private String userName;
private String password;

@ManyToOne
@JoinColumn(name = "role_id")
private Role role;

@OneToMany(targetEntity = Address.class, mappedBy = "user",fetch= FetchType.LAZY ,cascade =CascadeType.ALL)
private Set<Address> address; //Instead of Set(Unordered collection and not allow duplicates) we can use list(ordered and allow duplicate values) as well

//getter and setter}

如果您有任何想法请告知。谢谢。

参考方案

我更改了MyUserDetailsS​​ervice类,添加了passwordEncoder方法。

增加线

BCryptPasswordEncoder encoder = passwordEncoder();

换线

//changed, user.getPassword() as encoder.encode(user.getPassword())
return new org.springframework.security.core.userdetails.User(--)

MyUserDetailsS​​ervice.java

@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

    BCryptPasswordEncoder encoder = passwordEncoder();
    User user = userRepository.findByUsername(username);
    if(user == null){
        throw new UsernameNotFoundException("User Name "+username +"Not Found");
    }
    return new org.springframework.security.core.userdetails.User(user.getUserName(),encoder.encode(user.getPassword()),getGrantedAuthorities(user));
}

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

Spring Boot如何在POST之后返回响应 - java

我想创建一个新客户并在创建客户后返回客户编号。客户编号必须是从50000开始的自动递增的唯一编号。到目前为止,我已经成功创建了一个客户,但是我不确定应该如何生成客户编号,将其保存到数据库中,并在触发POST时将其作为成功消息显示给用户。json下面是所需的响应;{ "customerNumber": "50002", …

Spring Security不允许加载CSS或JS资源 - java

该资源位于src / main / resources / static / css或src / main / resources / static / js下,我使用的是Spring Boot,安全级别为:@Configuration @EnableWebMvcSecurity @EnableGlobalAuthentication public clas…

Spring MVC中的输入验证 - java

我知道Commons Validator框架是Struts项目在服务器端和客户端验证输入值的事实上的标准。Spring MVC项目是否也是如此?我得到的印象可能不是,大多数Struts书籍和论坛都谈论Commons Validator框架,但是只有少数Spring书籍和论坛可以。在Spring MVC项目中验证输入的最佳实践是什么?干杯! 参考方案 在引入S…

Java:“自动装配”继承与依赖注入 - java

Improve this question 我通常以常见的简单形式使用Spring框架: 控制器服务存储库通常,我会在CommonService类中放一个通用服务,并使所有其他服务扩展到类中。一个开发人员告诉我,最好在每个服务中插入CommonClass而不是使用继承。我的问题是,有一个方法比另一个更好吗? JVM或性能是否会受到另一个影响?更新资料Comm…

Java GUI外观变化 - java

我是编程的新手,但是我正在准备编写Java程序。在计划时,我正在尝试为其找到合适的GUI。我发现带有GUI选项的this页面。我有两个问题:这些可以插入Java GUI构建器吗? 构建程序后更改GUI外观有多容易(或很难)? 参考方案 更改程序的外观很简单:UIManager.setLookAndFeel("fully qualified name…