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

Jos*_*osh 9 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);
Run Code Online (Sandbox Code Playgroud)

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

java.lang.IllegalArgumentException: Cannot set this token to trusted - use constructor which takes a GrantedAuthority list instead
Run Code Online (Sandbox Code Playgroud)

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

经过一些搜索后,我发现答案最接近的是Springsource.org的论坛,而且那个人使用了一种弃用的方法,但这是一种类似的方法.如何以编程方式记录用户?

pap*_*pap 14

您不必明确调用authentication.setAuthenticated(true)(事实上​​,您不被允许).构造函数为您完成此操作.

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

Authentication authentication 
    = new UsernamePasswordAuthenticationToken(tempUser, password, authorities);
Run Code Online (Sandbox Code Playgroud)

检查javadoc的UsernamePasswordAuthenticationToken.