我正在尝试使用getAuthentication来获取当前用户,问题是它提供了错误java.lang.String cannot be cast to User
。我不知道为什么它给了我这个错误...
我的域用户代码:
public class User implements UserDetails {
@Id
private String username;
...}
UserDetailsServiceImpl:
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
@Autowired
UserRepository userRepository;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userRepository.findByUsername(username);
if(user == null)
throw new UsernameNotFoundException("Incorrect username");
return user;
}
}
我的控制器......:
@BasePathAwareController
public class IdentityController {
@RequestMapping("/identity")
public @ResponseBody
PersistentEntityResource getAuthenticatedUserIdentity(PersistentEntityResourceAssembler resourceAssembler){
Object obj = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
User user = (User) obj;
return resourceAssembler.toResource(user);
}
}
AuthenticationConfig文件:
@Configuration
@Profile("!Test")
public class AuthenticationConfig extends GlobalAuthenticationConfigurerAdapter {
@Autowired
UserDetailsServiceImpl userDetailsService;
@Autowired
UserRepository userRepository;
@Override
public void init(AuthenticationManagerBuilder auth) throws Exception {
auth
.userDetailsService(userDetailsService)
.passwordEncoder(User.passwordEncoder);
String rootUser = System.getenv("ROOT_USER");
String rootPassword = System.getenv("ROOT_PASSWORD");
if(rootUser == null || rootPassword == null) {
throw new IllegalStateException("Environment variable user or password not defined.");
}else if(!userRepository.exists(rootUser)) {
User user = new User();
user.setUsername(rootUser);
user.setPassword(rootPassword);
userRepository.save(user);
}
}
}
一些线索?我正在使用mongodb。
已解答:我在WebSecurityConfig中没有.antMatchers(HttpMethod.GET,"/identity").authenticated()
,显然用户没有登录。此外,我没有.httpBasic()