I am using the following method to make a programmatic login after registration
private void autoLogin(User user,
HttpServletRequest request)
{
GrantedAuthority[] grantedAuthorities = new GrantedAuthority[] { new GrantedAuthorityImpl(
"ROLE_ADMIN") };
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
user.getUsername(), user.getPassword(),grantedAuthorities);
// generate session if one doesn't exist
request.getSession();
token.setDetails(new WebAuthenticationDetails(request));
Authentication authenticatedUser = authenticationManager.authenticate(token);
SecurityContextHolder.getContext().setAuthentication(authenticatedUser);
}
the user is authenticated but always has the ROLE_ANONYMOUS I don't know why ? any ideas ?
verb. If someone in authority grants you something, or if something is granted to you, you are allowed to have it.
The most common way to provide granted authorities to a user by implementing custom UserDetailsService that build and return the GrantedAuthorities for our application. Here is the default User object return by Spring security including list of GrantedAuthorities .
Interface GrantedAuthority Represents an authority granted to an Authentication object. A GrantedAuthority must either represent itself as a String or be specifically supported by an AccessDecisionManager .
getAuthorities() method just returns a Collection<GrantedAuthority> object. You can use the appropriate Collection method to add your new authority to that collection. Selah. @Slavak That would really depend on what implementation you're using for UserDetails.
This behaviour looks very strange. Javi suggests to persist security context into session manually, but it should be done automatically by Spring Security's SecurityContextPersistenceFilter
.
One possible cause I can imagine is filters = "none"
in <intercept-url>
of your registration processing page.
filters = "none"
disables all security filters for the specified URL. As you can see, it may interfere with other features of Spring Security. So, the better approach is to keep filters enabled, but to configure them to allow access for all users. You have several options:
access
attribute (i.e. without <http use-expressions = "true" ...>
):
access = "ROLE_ANONYMOUS"
allows access for non-authenticated users, but denies for the authenticated onesaccess = "IS_AUTHENTICATED_ANONYMOUSLY, IS_AUTHENTICATED_FULLY, IS_AUTHENTICATED_REMEMBERED"
<http use-expressions = "true" ...>
) you simply write access = "true"
to allow access for all users (but other <intercept-url>
s should use this syntax too).If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With