I have the following code (attempting to log a user in programatically):
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
authorities.add(new GrantedAuthorityImpl("ROLE_ADMIN"));
...
User tempUser = new User(correctUsername,
correctPassword,
true, true, true, true, // logging them in...
authorities // type is List<GrantedAuthority>
);
...
Authentication authentication
= new UsernamePasswordAuthenticationToken(tempUser, authorities);
// I'm using authorities again (List<GrantedAuthority>)
// is this the right spot for it?
...
// this is the line causing the error
authentication.setAuthenticated(true);
When I try to run that I get the following:
java.lang.IllegalArgumentException: Cannot set this token to trusted - use constructor which takes a GrantedAuthority list instead
Note that I'm using the authorities
list of GrantedAuthority
s both in the User
and Authentication
objects. I'm not sure where I should be using those. I'm trying to replicate the answer for another SO question but am running into the exception posted above. Other similar questions that didn't quite answer my question:
After some searching the closest I've found to an answer was at the forum at springsource.org, and that person's using a deprecated method, but it's a similar approach. How can I log a user in programatically?
You dont have to explicitly call authentication.setAuthenticated(true)
(in fact, you are not allowed). The constructor does that for you.
You are, however, invoking the wrong constructor. You should be calling:
Authentication authentication
= new UsernamePasswordAuthenticationToken(tempUser, password, authorities);
Check the javadoc for UsernamePasswordAuthenticationToken.
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