如何使用Pac4J的Google2Client为用户Profile添加应用专属属性
为Google2Client返回的用户Profile添加应用专属属性
原问题
我正在开发一个JEE 8应用,希望采用Google的OAuth2认证机制简化新用户注册流程。项目环境如下:
- deltaspike 1.9.5
- pac4j 3.8.3(使用Google2Client)
- Java 11
- Wildfly 23
客户端初始化代码:
Google2Client google2Client = new Google2Client(); google2Client.setKey("API_KEY"); google2Client.setSecret("API_SECRET"); google2Client.setScope(Google2Scope.EMAIL_AND_PROFILE); google2Client.setName("google");
请问如何为Google2Client返回的已授权用户Profile添加应用所需的专属属性?我了解到可通过ProfileCreator实现,但需要示例代码。
解决方案(自实现)
通过继承OAuth20ProfileCreator重写方法实现自定义属性添加,具体代码如下:
自定义ProfileCreator类
public class MyCustomProfileCreator extends OAuth20ProfileCreator { @Override protected void addAccessTokenToProfile(OAuth20Profile profile, OAuth2AccessToken accessToken) { // 先执行父类原有逻辑 super.addAccessTokenToProfile(profile, accessToken); // 添加应用专属属性 profile.addAttribute("testkey", "testvalue"); } public MyCustomProfileCreator(OAuth20Configuration configuration, IndirectClient client) { super(configuration, client); } }
在Google客户端中配置自定义ProfileCreator
String mycallbackurl = BaseUrl + "/mybackend/resources/callback?client_name=google"; google2Client.setCallbackUrl(mycallbackurl); google2Client.setKey(KEY); google2Client.setSecret(SECRET); google2Client.setScope(Google2Scope.EMAIL_AND_PROFILE); google2Client.setName("google"); // 设置自定义的ProfileCreator google2Client.setProfileCreator(new MyCustomProfileCreator(google2Client.getConfiguration(), google2Client));
内容的提问来源于stack exchange,提问作者Shannon
相关产品推荐
相关产品推荐

