1

Why I am not able to call graphClient more then once?

Code:

public static void initializeGraphAuth(String authorizationCode) {
            
            List<String> scopes = new ArrayList<>();
            scopes.add("https://graph.microsoft.com/mail.read");    
            // Create the auth provider
            final AuthorizationCodeCredential authCodeCredential = new AuthorizationCodeCredentialBuilder().clientId(AzureConstants.CLIENT_ID).clientSecret(AzureConstants.CLIENT_SECRET).authorizationCode(authorizationCode)      .redirectUrl(AzureConstants.REDIRECT_URI).build();
            
            authProvider = new TokenCredentialAuthProvider(scopes, authCodeCredential);
    
            // Create default logger to only log errors
            DefaultLogger logger = new DefaultLogger();
            logger.setLoggingLevel(LoggerLevel.ERROR);
    
            // Build a Graph client
            graphClient = GraphServiceClient.builder().authenticationProvider(authProvider).logger(logger).buildClient();
        }
        public static User getUserDetails() {
            return graphClient.me().buildRequest().get();
        }
    
        public static List<Group> getUserGroups() {
            GroupCollectionPage groups = graphClient.me().transitiveMemberOfAsGroup().buildRequest().get();
            return groups.getCurrentPage();
        }

In main app I am calling getUserDetails() and getUserGroups() methods to get users details and group details respectively. Able to get User details but not group details below is the error

com.microsoft.aad.msal4j.MsalInteractionRequiredException: AADSTS54005: OAuth2 Authorization code was already redeemed, please retry with a new valid code or use an existing refresh token.
Trace ID: 48d1fee1-cb8b-48c6-a7ec-91e2b2057500
Correlation ID: c58388ec-417c-4398-82ee-68910568f4df

If i call only one method either getUserDetails or getUserGroups its is working fine, but when i call both methods in code it is giving error

How can i use graphClient object to get user and group details both??

Thanks for your help

Mahesh
  • 11
  • 1
  • 4

1 Answers1

1

When your application uses authorization codes to obtain tokens, this behavior is to be expected.

In this situation, refresh tokens can be used to obtain extra tokens for other resources.

  • Refresh tokens can be used several times across multiple resources, whereas authorization codes can only be used once.
  • When Credential uses a refresh token, it also updates the access token when the access token expires.

You can receive a new access token using a refresh token by using the Google OAuth2 client library.

For more information on this, you can refer OAuth 2.0 and the Google OAuth Client Library for Java

REFERENCES:

  1. OAuth2 Authorization code was already redeemed - Microsoft Q&A
  2. How to get an access token using a refresh token in Java? - Stack Overflow
SwethaKandikonda
  • 7,513
  • 2
  • 4
  • 18