I am stuck with this Java Spring boot problem. I have filled the autorities: this.getAuthorities(user) in the return statement of the loadUserByUsername method. but when I print out the Authentication object it says that the Granted Authorities is empty:
UsernamePasswordAuthenticationToken [Principal=mark, Credentials=[PROTECTED], Authenticated=true, Details=null, Granted Authorities=[]]
Does anyone have any idea?
Extra Info: User.getRole() == "Role_Default"
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userRepository.findByUsername(username);
if (user == null) throw new UsernameNotFoundException(username);
return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), this.getAuthorities(user));
}
@GetMapping(path = "authenticated")
@PreAuthorize("hasAuthority('ROLE_DEFAULT')")
public User getAuthenticatedUser() {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
System.out.println(auth);
User user = this.getUserByUsername(auth.getPrincipal().toString());
return user;
}
private Collection<GrantedAuthority> getAuthorities(User user) {
Collection<GrantedAuthority> authorities = new ArrayList<>();
authorities.add(new SimpleGrantedAuthority(user.getRole()));
return authorities;
}
I experienced this problem as well. I have a custom UserCredentials implementing org.springframework.security.core.userdetails.UserDetails
with getAuthorities() implementation returning values - but noting worked Authorities array was empty:
o.s.s.w.a.i.FilterSecurityInterceptor:317 - Re-authenticated UsernamePasswordAuthenticationToken [Principal=dto.UserCredentials@585027b7, Credentials=[PROTECTED], Authenticated=true, Details=null, **Granted Authorities=[]**] before authorizing
The problem was that my implementation of AuthenticationProvider was wrong, it returned :
new UsernamePasswordAuthenticationToken(userCredentials, authentication, Collections.emptyList());
Instead of the correct:
new UsernamePasswordAuthenticationToken(userCredentials, authentication, **userCredentials.getAuthorities()**);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.