我不能说这是否是首选的解决方案,但在尝试自己解决相同的问题之后,我最终扩展了
DefaultUserAuthenticationConverter
是的。
所以你可以这样做
@Bean
public JwtAccessTokenConverter accessTokenConverter() {
DefaultAccessTokenConverter defaultConverter = new DefaultAccessTokenConverter();
defaultConverter.setUserTokenConverter(new CustomUserAuthenticationConverter());
JwtAccessTokenConverter jwtConverter = new JwtAccessTokenConverter();
converter.setAccessTokenConverter(defaultConverter);
return converter;
}
那么DefaultUserAuthenticationConverter的可扩展性不是很强,因为大多数方法和属性都是私有的。但这里有一个例子
public class CustomUserAuthenticationConverter extends DefaultUserAuthenticationConverter {
private static final String CUST_PROP = "custProp";
@Override
public Authentication extractAuthentication(Map<String, ?> map) {
if (map.containsKey(USERNAME) && map.containsKey(CUST_PROP)) {
String username = (String) map.get(USERNAME);
String custProp = (String) map.get(CUST_PROP);
CustomPrincipal principal = new CustomPrincipal();
pricipal.setUsername(username);
pricipal.setCustomProp(custProp);
Collection<? extends GrantedAuthority> authorities = getAuthorities(map);
return new UsernamePasswordAuthenticationToken(user, "N/A", authorities);
}
return null;
}
private Collection<? extends GrantedAuthority> getAuthorities(Map<String, ?> map) {
//Copy this method from DefaultUserAuthenticationConverter or create your own.
}
}