springcloud security oauth2, 资源服务器从mysql查询用户信息需要userId,如果通过oauth2认证服务器认证了,之后资源服务器要后从哪里可以拿到userId呢

springcloud security oauth2, 资源服务器从mysql查询用户信息需要userId,如果通过oauth2认证服务器认证了,之后资源服务器要后从哪里可以拿到userId呢

问题描述:

资源服务器从mysql查询用户信息需要userId,如果通过oauth2认证服务器认证了,之后资源服务器要要从哪里可以拿到userId呢

  1. 资源服务器将token发送给认证服务器去check_token;
  2. 认证服务器将check_token的结果返回,结果里面是要带userId或者userName的

spring已经把上面的技术细节做了封装,参考范例写就好了
官方文档:https://howtodoinjava.com/spring-boot2/oauth2-auth-server/

你关心的如何取用户信息,封装到 SecurityContextHolder.getContext().getAuthentication().getPrincipal() 这个方法里面了

具体的细节可以看看如下文章:
https://segmentfault.com/a/1190000012557493

 /**
     * 获得上下文中的用户信息
     */
    private String getUserId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (!(authentication instanceof OAuth2Authentication)) {
            return null;
        }
        OAuth2Authentication oAuth2Authentication = (OAuth2Authentication) authentication;
        Authentication userAuthentication = oAuth2Authentication.getUserAuthentication();
        return userAuthentication.getName();
    }

建议使用jwt,从token中获取用户信息。