#spring #spring-boot #spring-security
Вопрос:
Вот мой код в этом я пытаюсь войти в систему, используя идентификатор и пароль, сохраненные в базе данных MongoDB, мое соединение с БД в порядке, так как я пытался извлечь все данные из БД, но при использовании системы безопасности я получаю ошибку кодировщик паролей, определенный для идентификатора, равен нулю.
Класс Менеджера безопасности
package com.casestudy.APIGateway.SecurityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import com.casestudy.APIGateway.Service.MySecurityDetailsService;
public class SecurityManager extends WebSecurityConfigurerAdapter {
@Autowired
MySecurityDetailsService userDetailsService;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService);
}
@Bean
@SuppressWarnings("deprecation")
public PasswordEncoder encodePasswrd() {
return NoOpPasswordEncoder.getInstance();
}
}
UserDetailsServiceClass
package com.casestudy.APIGateway.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import java.util.Optional;
import com.casestudy.APIGateway.DAO.SecurityDatabase;
import com.casestudy.APIGateway.Model.SecurityData;
@Service
public class MySecurityDetailsService implements UserDetailsService{
@Autowired
SecurityDatabase userRepo;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
Optional<SecurityData> user =userRepo.findById(username);
System.out.println(user);
user.orElseThrow(()->new UsernameNotFoundException("User Not Found" username));
return user.map(MySecurityDetails::new).get();
}
}
Класс пользовательских данных
package com.casestudy.APIGateway.Service;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import com.casestudy.APIGateway.Model.SecurityData;
import com.example.database.mongodbSpringSecurity.entity.User;
public class MySecurityDetails implements UserDetails{
private String username;
private String password;
private List<GrantedAuthority> authorities;
public MySecurityDetails(SecurityData user) {
this.username = user.get_Id();
this.password = user.getPassword();
this.authorities = Arrays.stream(user.getRole().split(","))
.map(SimpleGrantedAuthority::new).collect(Collectors.toList());
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
// TODO Auto-generated method stub
return authorities;
}
@Override
public String getPassword() {
// TODO Auto-generated method stub
return password;
}
@Override
public String getUsername() {
// TODO Auto-generated method stub
return username;
}
@Override
public boolean isAccountNonExpired() {
// TODO Auto-generated method stub
return true;
}
@Override
public boolean isAccountNonLocked() {
// TODO Auto-generated method stub
return true;
}
@Override
public boolean isCredentialsNonExpired() {
// TODO Auto-generated method stub
return true;
}
@Override
public boolean isEnabled() {
// TODO Auto-generated method stub
return true;
}
}
my entity class is as follows
package com.casestudy.APIGateway.Model;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.stereotype.Component;
@Component
@Document(collection = "Security")
public class SecurityData {
@Id
private String _Id;
private String Password;
private String Role;
public SecurityData() {
super();
// TODO Auto-generated constructor stub
}
public SecurityData(String _Id, String password, String role) {
super();
this._Id = _Id;
Password = password;
Role = role;
}
public String get_Id() {
return _Id;
}
public void set_Id(String _Id) {
this._Id = _Id;
}
public String getPassword() {
return Password;
}
public void setPassword(String password) {
Password = password;
}
public String getRole() {
return Role;
}
public void setRole(String role) {
Role = role;
}
}