最近用spring security + oauth2 做认证和授权,碰到个非常懊恼的问题,从安全上下文获取用户信息,永远只给你返回个用户名。因为在很多地方,要用到用户id, 不可能又用用户名去数据库查id吧,这就非常蛋腾了。
百度了人民群众的意见,折腾了老半天,终于把它搞掂了。
终极大法就是重写源码里面默认的实现方法。
源码就不贴了, 这贴修改的,供各位参考参考:
一 、 重写DefaultUserAuthenticationConverter里面的convertUserAuthentication方法:
@Component
@Slf4j
public class SetAdditionalInfoToTokenConverter extends DefaultUserAuthenticationConverter {
/**
* 这个方法把额外的信息添加进jwt token (默认只添加用户名,权限)
* 这里额外添加了用户id
* 方法将会在授权服务器起作用
* @param authentication
* @return
*/
@Override
public Map<String, ?> convertUserAuthentication(Authentication authentication) {
Map<String, Object> response = new LinkedHashMap<String, Object>();
// response.put(USERNAME, authentication.getName()); 源码里面的,不知道USERNAME是什么,注释掉吧
Object principal = authentication.getPrincipal();
//不要强制转换principal, 用json转化,不然各种莫名其妙的坑
String jsonStr=JSON.toJSONString(principal);
JSONObject jsonObject=JSON.parseObject(jsonStr);
//加上自定义的用户名和id
long id=jsonObject.getLong("id");
response.put("id", id);
String username=jsonObject.getString("username");
response.put("username",username);
if (authentication.getAuthorities() != null && !authentication.getAuthorities().isEmpty()) {
response.put(AUTHORITIES, AuthorityUtils.aut