且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从 OAuth2 授权服务器/用户端点获取自定义用户信息

更新时间:2023-09-08 09:20:28

解决方案是实现自定义UserInfoTokenServices

https://github.com/spring-projects/spring-boot/blob/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/resource/UserInfoTokenServices.java

只需将您的自定义实现作为 Bean 提供,它将被用来代替默认实现.

Just Provide your custom implementation as a Bean and it will be used instead of the default one.

在这个 UserInfoTokenServices 中,您可以按照自己的意愿构建 principal.

Inside this UserInfoTokenServices you can build the principal like you want to.

此 UserInfoTokenServices 用于从授权服务器的 /users 端点的响应中提取 UserDetails.正如你在

This UserInfoTokenServices is used to extract the UserDetails out of the response of the /usersendpoint of your authorization server. As you can see in

private Object getPrincipal(Map<String, Object> map) {
    for (String key : PRINCIPAL_KEYS) {
        if (map.containsKey(key)) {
            return map.get(key);
        }
    }
    return "unknown";
}

默认仅提取PRINCIPAL_KEYS 中指定的属性.这正是你的问题.您必须提取的不仅仅是用户名或您的财产名称.所以寻找更多的钥匙.

Only the properties specified in PRINCIPAL_KEYS are extracted by default. And thats exactly your problem. You have to extract more than just the username or whatever your property is named. So look for more keys.

private Object getPrincipal(Map<String, Object> map) {
    MyUserDetails myUserDetails = new myUserDetails();
    for (String key : PRINCIPAL_KEYS) {
        if (map.containsKey(key)) {
            myUserDetails.setUserName(map.get(key));
        }
    }
    if( map.containsKey("email") {
        myUserDetails.setEmail(map.get("email"));
    }
    //and so on..
    return myUserDetails;
}

接线:

@Autowired
private ResourceServerProperties sso;

@Bean
public ResourceServerTokenServices myUserInfoTokenServices() {
    return new MyUserInfoTokenServices(sso.getUserInfoUri(), sso.getClientId());
}

!!更新 Spring Boot 1.4 事情变得更容易了!!

使用 Spring Boot 1.4.0 a PrincipalExtractor 被引入.应实现此类以提取自定义主体(请参阅 Spring Boot 1.4 发行说明).

With Spring Boot 1.4.0 a PrincipalExtractor was introduced. This class should be implemented to extract a custom principal (see Spring Boot 1.4 Release Notes).