问题
In my spring boot application,
After successful login I set the authentication details (with user roles in authorities) in the context
// Perform the authentication
Authentication authentication = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(
authenticationRequest.getUsername(),
authenticationRequest.getPassword()
)
);
SecurityContextHolder.getContext().setAuthentication(authentication);
But when I try to access the roles again in other parts of the code with below line the authorities are null. Otherwise, it has all other security details in it.
What am I missing?
SecurityContextHolder.getContext().getAuthentication().getAuthorities()
回答1:
I think that you should add the roles when creating the UsernamePasswordAuthenticationToken
, like this:
new UsernamePasswordAuthenticationToken(
authenticationRequest.getUsername(),
authenticationRequest.getPassword(),
roles
)
This is the signature of the method you should use:
UsernamePasswordAuthenticationToken(Object principal, Object credentials,
Collection<? extends GrantedAuthority> authorities)
回答2:
After successful login I set the authentication details (with user roles in authorities) in the context
You should not set authentication details like roles as you mention after successful authentication in the context. I will explain basic flow:
- Authentication request comes with username and password parameters.
- UsernamePasswordAuthenticationFilter will retrieve credentials and create UsernamePasswordAuthenticationToken(username,password), and gives to authenticationmanager.
- authenticationmanager delegates to appropriate authentication provider which supports UsernamePasswordAuthenticationToken authentication request object.(You can have your own authentication provider implementation.)
- Supporting authentication provider will retrieve user details(including authorities, not authenticated yet) by entered username from let's say DB and compares submitted password to retrieved user's password.If success then user details along with authorities is passed to UsernamePasswordAuthenticationToken which would be constructed with 3 arguments like:
new UsernamePasswordAuthenticationToken(userDetails,null,roles)
which in the constructor sets authentication flag to true. - Authentication manager popultates security context with that token(step 4)
So successful login indicates implicitly that roles are there too. Do you have userDetailsService implementation registered with authentication provider or authentication manager? Would be glad to help you more...
来源:https://stackoverflow.com/questions/61011907/springboot-security-authorities-missing-in-other-part-of-the-code