17

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:

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?

Community
  • 1
  • 1
Josh
  • 801
  • 3
  • 11
  • 16

1 Answers1

25

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.

pap
  • 27,064
  • 6
  • 41
  • 46
  • Awesome! thanks very much. Could I ask why both the `User` and `UsernamePasswordAuthenticationToken` constructors need a list of grantedauthorities? Anyway it works so I'll accept this when I can – Josh Nov 15 '11 at 14:44
  • 1
    It's two levels of abstraction that happen to collide here. UsernamePasswordAuthenticationToken is concrete version of a an entity that may or may not be authenticated (Authentication). A User is an implementation of a Principal (details of a user) existing independently of any authentication status. – pap Nov 15 '11 at 15:30
  • Ran into same issue, assumed that I needed to explicitly call `setAuthenticated()` method. – Mike R Nov 07 '13 at 22:34
  • So meaning after invoking Authentication authentication = new UsernamePasswordAuthenticationToken(tempUser, password, authorities); I can call authentication.isAuthenticated(), which is expected to return TRUE? – Lawrence Paje Jan 24 '19 at 10:39
  • note that user and password should not be null, otherwise isAuthenticated will return false even after calling the constructor with correct authorities – hello_earth Jan 04 '23 at 16:34