Issue
I have method annotated with @PreAuthorize that uses custom bean
@PreAuthorize("@preAuthUtils.test(authentication)")
public void method(){
...
}
That bean does nothing just printing out the auth and user (principle)
@Component(value = "preAuthUtils")
public class PreAuthUtils {
public boolean test(UsernamePasswordAuthenticationToken x) {
System.out.println("type: " + x.getClass().getSimpleName());
System.out.println("string: " + x.toString());
final var user = x.getPrincipal();
System.out.println("type: " + user.getClass().getSimpleName());
System.out.println("string: " + user.toString());
return true;
}
}
Output (after request)
type: UsernamePasswordAuthenticationToken
string: UsernamePasswordAuthenticationToken [Principal=johndoe, Credentials=[PROTECTED], Authenticated=true, Details=WebAuthenticationDetails [RemoteIpAddress=127.0.0.1, SessionId=null], Granted Authorities=[ROLE_USER, ROLE_CUSTOMER]]
type: String
string: johndoe
The question is why the user is type of String? and not my custom "DefaultUserDetails" class that implements UserDetails?
Because I need to get the id and info about user to make decisions wheather to authenticate or restrict the user, i spent 6 hours i just want to cry
Solution
I finally find out.
This all due to my JWT filter that actually authenticates the user...
Here the principal is the userDetails (IN WAS STRING ..)
final var authentication = new UsernamePasswordAuthenticationToken(principal, null, authorities);
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(context));
SecurityContextHolder.getContext().setAuthentication(authentication);
Answered By - user19926584
Answer Checked By - David Goodson (JavaFixing Volunteer)