Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

spring Authentication.setAuthenticated(boolean) java.lang.IllegalArgumentException: Cannot set this token to trusted

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 GrantedAuthoritys 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:

  • How to programmatically log user in with Spring Security 3.1
  • Programmatically login in a user using spring security

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?

like image 496
Josh Avatar asked Nov 14 '11 22:11

Josh


1 Answers

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.

like image 92
pap Avatar answered Sep 20 '22 11:09

pap