我在我的web项目中使用SpringSecurity。当我尝试使用用户名和密码登录时,我的堆栈跟踪中出现以下错误:
class org.springframework.security.core.userdetails.User cannot be cast to class com.cesi.cuberil.service.JwtUser (org.springframework.security.core.userdetails.User and com.cesi.cuberil.service.JwtUser are in unnamed module of loader 'app')
at com.cesi.cuberil.controller.AuthController.login(AuthController.java:116) ~[classes/:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
at java.base/java.lang.reflect.Method.invoke(Method.java:566) ~[na:na]
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:197) ~[spring-web-5.3.2.jar:5.3.2]
下面,我将把类放在我认为问题产生的地方。这是我的JwtUser.java:
package com.cesi.cuberil.service;
import com.cesi.cuberil.model.User;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import java.util.Collection;
@Data
public class JwtUser implements UserDetails {
private final String username;
private final String password;
private final boolean enabled;
private final Collection<? extends GrantedAuthority> authorities;
private static final long serialVersionUID = 1L;
private User user;
public JwtUser(String username, String password, Boolean enabled, Collection<? extends GrantedAuthority> authorities) {
this.username = username;
this.password = password;
this.enabled = enabled;
this.authorities = authorities;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return authorities;
}
@Override
public String getPassword() {
return password;
}
@Override
public String getUsername() {
return username;
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return enabled;
}
}
这是我的AuthController.java:
@RestController
@RequestMapping("/api/v1/auth")
@AllArgsConstructor
public class AuthController {
@Autowired
AuthenticationManager authenticationManager;
@Autowired
PasswordEncoder encoder;
@Autowired
JwtUtils jwtUtils;
@PostMapping("/login")
public ResponseEntity<?> login(@Valid @RequestBody LoginRequest loginRequest) {
Authentication authentication = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword()));
SecurityContextHolder.getContext().setAuthentication(authentication);
String jwt = jwtUtils.generateJwtToken(authentication);
JwtUser myUserDetails = (JwtUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
List<String> roles = myUserDetails.getAuthorities().stream()
.map(item -> item.getAuthority())
.collect(Collectors.toList());
return ResponseEntity.ok(new JwtResponse(jwt, myUserDetails.getUser().getUserId(), myUserDetails.getUsername(), myUserDetails.getUser().getEmail(), roles));
}
}
这是我的UserDetailsServiceImpl.java:
@Service
@AllArgsConstructor
public class UserDetailsServiceImpl implements UserDetailsService {
@Autowired
private UserRepository userRepository;
public User getByUsername(String username) {
return userRepository.findByUsername(username);
}
@Override
@Transactional(readOnly = true)
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = this.getByUsername(username);
if (user == null) {
throw new UsernameNotFoundException("user not found");
} else {
List<GrantedAuthority> listAuthorities = new ArrayList<GrantedAuthority>();
listAuthorities.add(new SimpleGrantedAuthority("ROLE_USER"));
return new org.springframework.security.core.userdetails.User(username, user.getPassword(), true, true, true, true, listAuthorities);
}
}
}
作为参考,我使用了java11和最新版本的Spring Boot。
发布于 2021-01-11 07:22:37
我认为应该返回JwtUser
实例,而不是org.springframework.security.core.userdetails.User
。因为JwtUser
已经实现了UserDetails
接口。
Here's一个示例。
发布于 2021-01-11 07:25:26
只有在这两个类之间存在继承关系时,才能从一个对象转换到另一个对象。在您的示例中,这两个类实现了相同的接口,但是类org.springframework.security.core.userdetails.User和您的JwtUser之间没有继承关系。
发布于 2021-01-11 19:32:28
我认为这里的问题是对Spring Security的错误使用。您在SecurityContextHolder中设置身份验证,直接调用AuthenticationManager,稍后甚至调用主体,而不是从SecurityContextHolder调用身份验证。我建议您更多地使用标准方式,使用LoginAuthentication并在Spring Security配置中添加successHandler()事件,在该事件中,您可以编写自己的实现,在响应对象中写入JwtResponse。
https://stackoverflow.com/questions/65659155
复制相似问题