如何解决错误:该用户名不存在:使用Spring Security时
我正在使用Spring Boot + Spring Security构建后端,并使用Postman对其进行测试。 对于前端,我将使用Android应用程序。
已实施http basic auth
。
当我单击Postman中的Authentication选项卡并从下拉框中选择Basic Auth,然后在其中输入用户名和密码字段时,它就可以正常工作。但是,当我发送原始JSON请求正文时,出现以下错误:
org.springframework.security.authentication.InternalAuthenticationServiceException: User doesn't exist with this username:
我认为这是由此类引起的
CustomUserDetailsService.java
@Service
public class CustomUserDetailsService implements UserDetailsService {
@Autowired
private UserRepository userRepository;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userRepository.findByUsername(username);
CustomUserDetails userDetails = null;
if(user != null){
userDetails = new CustomUserDetails();
userDetails.setUser(user);
}else{
throw new UserNotFoundException("User doesn't exist with this username: " + username);
}
return userDetails;
}
}
但是我不确定为什么要与Postman auth下拉框配合使用。
这是我使用的更多代码:
SecurityConfiguration.java
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.userDetailsService(userDetailsService)
.passwordEncoder(encodePWD());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
http.csrf().disable();
http
.httpBasic()
.and()
.authorizeRequests()
.antMatchers("/rest/**").permitAll()
.and()
.authorizeRequests()
.antMatchers("/secure/**").hasAnyRole("ADMIN")
.anyRequest().authenticated()
.and()
.formLogin()
.permitAll();
}
@Bean
public BCryptPasswordEncoder encodePWD() {
return new BCryptPasswordEncoder();
}
}
CustomUserDetailsService.java
@Service
public class CustomUserDetailsService implements UserDetailsService {
@Autowired
private UserRepository userRepository;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userRepository.findByUsername(username);
CustomUserDetails userDetails = null;
if(user != null){
userDetails = new CustomUserDetails();
userDetails.setUser(user);
}else{
throw new UserNotFoundException("User doesn't exist with this username: " + username);
}
return userDetails;
}
}
CustomUserDetails.java
@Getter
@Setter
public class CustomUserDetails implements UserDetails {
private User user;
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return user.getRoles().stream().map(role -> new SimpleGrantedAuthority("ROLE_" + role.getRole())).collect(Collectors.toSet());
}
@Override
public String getPassword() {
return user.getPassword();
}
@Override
public String getUsername() {
return user.getUsername();
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
}
我还用它来登录用户并检查数据库中是否匹配一个。
@PostMapping("/loginuser")
ResponseEntity<Object> login(@RequestBody User user) {
List<User> userList = userRepository.findByUsernameAndPassword(user.getUsername(),user.getPassword());
if (userList.size() != 1) {
throw new UserNotFoundException("Entity not found");
} else {
return new ResponseEntity<>(userList.get(0),HttpStatus.OK);
}
}
是否甚至可以将https basic auth
用于休息服务器api?
还是我必须对带有OAuth和类似令牌的令牌使用某些身份验证?
更新
解决方法
如果使用“邮递员授权”选项卡,邮递员将构造相应的授权标头Authorization: Basic <credentials>
,其中credentials
是用户名和密码的Base64编码。
您可以在邮递员请求中单击标题并将其隐藏,然后看到该标题。
Spring Security HTTP基本认证需要此标头。如果仅将用户名和密码以JSON形式发布在请求的主体中,Spring Security HTTP基本身份验证将无法从标头中提取用户名。因此,user
等于null
并引发异常。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。