java - 没有为具有数据库身份验证的 id "null"映射的 PasswordEncoder

标签 java spring-boot spring-security

我成功地建立了内存认证。但是当我要使用数据库构建它时,会出现这个错误。

There is no PasswordEncoder mapped for the id "null"



这是后续教程 - 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();
}

}

我的用户详细信息服务.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;
}
}

用户存储接口(interface)
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
}

用户.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();
}

关于java - 没有为具有数据库身份验证的 id "null"映射的 PasswordEncoder,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49617349/

相关文章:

java - 考虑在您的配置中定义类型为 'com.ensat.services.ProductService' 的 bean

Nginx 反向代理 Websocket 身份验证 - HTTP 403

spring-boot - "JdbcSQLIntegrityConstraintViolationException: Unique index or primary key violation"升级到Spring Boot 2.7后出现异常

java - Apache Geode CacheListenerAdapter 不工作

java - 如何在分布在多个文件上的 Spring Security 中订购多个 <http> 元素

java - UserDetailsS​​ervice 的异常处理

java - 当我告诉它运行 Java 14 时,为什么 Gradle 会尝试使用 Java 8?

java - 调用 Web 服务时出现 org.xml.sax.SAXParseException 错误

java - 比较 JTable 中的 2 列的日期

java - 如何使 CardLayout 能够处理任意数量的卡片?