spring Authentication.setAuthenticated(boolean)java.lang.IllegalArgumentException:无法将此标记设置为trusted

时间:2011-11-14 22:24:46

标签: spring spring-security

我有以下代码(尝试以编程方式记录用户):

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);

当我尝试运行时,我得到以下内容:

java.lang.IllegalArgumentException: Cannot set this token to trusted - use constructor which takes a GrantedAuthority list instead

请注意,我在UserAuthentication对象中都使用了authorities GrantedAuthority个{{1}}列表。我不确定我应该在哪里使用它们。我正在尝试复制another SO question的答案,但我遇到了上面发布的异常。其他类似的问题并没有完全回答我的问题:

经过一些搜索后,我发现答案的最近点是the forum at springsource.org,那个人正在使用deprecated method,但这是一种类似的方法。如何以编程方式记录用户?

1 个答案:

答案 0 :(得分:13)

您不必明确调用authentication.setAuthenticated(true)(事实上,您不被允许)。构造函数为您做到了。

但是,您正在调用错误的构造函数。你应该打电话:

Authentication authentication 
    = new UsernamePasswordAuthenticationToken(tempUser, password, authorities);

检查javadoc的UsernamePasswordAuthenticationToken。