我使用自定义AuthenticationProvider
实现了Spring Security。我通过提供List
GrantedAuthority
来设置权限。当我稍后从List
检索此SecurityContextHolder
时,它似乎与我最初设置的不同。
以下是一些重现问题的示例代码:
验证码
/*
3 Granted Authorites are set
1. ABCD
2. EFGH, IJKL
3. WXYZ
*/
List<GrantedAuthority> userAuthorities =
AuthorityUtils.createAuthorityList(new String[]{"ABCD","EFGH, IJKL","WXYZ"});
检索代码
List<GrantedAuthority> retrievedUserAuthorities = (List<GrantedAuthority>) SecurityContextHolder.getContext().getAuthentication().getAuthorities();
/*
Retrieved Granted Authorities contains 4!!!
1. ABCD
2. EFGH
3. IJKL
4. WXYZ
*/
如何解决此问题?
以下是我的自定义AuthenticationProvider
的最小版本:
package com.test;
import java.util.List;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
public class CustomAuthenticationProvider implements AuthenticationProvider{
@Override
public Authentication authenticate(Authentication authentication)
throws AuthenticationException {
List<GrantedAuthority> userAuthorities =
AuthorityUtils.createAuthorityList(new String[]{"ABCD","EFGH, IJKL","WXYZ"});
User user =
new User("programmer@stackoverflow.com", "", true,
true, true, true, userAuthorities);
return new UsernamePasswordAuthenticationToken(user, null, userAuthorities);
}
@Override
public boolean supports(Class<?> authentication) {
return true;
}
}
Spring版本 4.2.5.RELEASE ,使用的Spring Security版本为 4.0.4.RELEASE 。