google-signinprofilepac4j

How to add application specific attributes to Profile using Pac4J with Google2Client?


I am working on a JEE 8 application, where i want to use Googles authentication mechanism (OAuth2) for an easier registration process of new users.

This is my project setup:

the client is initialized in the following way:

Google2Client google2Client = new Google2Client();
google2Client.setKey("API_KEY");
google2Client.setSecret("API_SECRET");
google2Client.setScope(Google2Scope.EMAIL_AND_PROFILE);
google2Client.setName("google")

Can somebody please give me a hint where i could enhanced the authorized user profile, that is returned by the google2client with attributed, that are necessary for my application? I found some pieces of information, that a ProfileCreator could be used somehow. I would be very happy, getting some examplecode. This would also help others to support pac4j (its a great framework).

kind regards

Shane

UPDATE

I solved it by extending OAuth20ProfileCreator

public class MyCustomProfilecreator extends OAuth20ProfileCreator {

    @Override
    protected void addAccessTokenToProfile(OAuth20Profile profile, OAuth2AccessToken accessToken) {
        
        super.addAccessTokenToProfile(profile, accessToken);
        profile.addAttribute("testkey", "testvalue");
        }

    public CustomProfilecreator(OAuth20Configuration configuration, IndirectClient client) {
        super(configuration, client);
    }
}

and then set it in the google client:

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");
google2Client.setProfileCreator(new MyCustomProfilecreator(google2Client.getConfiguration(), google2Client));

Solution

  • If you use Java 11, you should use pac4j v5.7.1: https://www.pac4j.org/docs/alldocs.html

    For the Google2Client, the OAuth20ProfileCreator relies on the Google2ProfileDefinition: https://github.com/pac4j/pac4j/blob/5.7.x/pac4j-oauth/src/main/java/org/pac4j/oauth/profile/google2/Google2ProfileDefinition.java

    You can see in this class the logic and retrieved attributes.