How to create a Graph Client from a String accessToken using Java?

Jin Nguyen 0 Reputation points
2023-10-26T16:09:14.0533333+00:00

I followed this flow and able to retrieve an access token using certificate.

https://learn.microsoft.com/en-us/entra/identity-platform/v2-oauth2-auth-code-flow

I tried the access token on Postman and it worked:

Authorization: Bearer

Microsoft Security Microsoft Entra Microsoft Entra ID
Microsoft Security Microsoft Entra Other
{count} votes

1 answer

Sort by: Most helpful
  1. James Hamil 27,211 Reputation points Microsoft Employee Moderator
    2023-10-27T20:32:05.72+00:00

    Hi @Jin Nguyen , to create a Graph Client from a String accessToken using Java, you can use the following code snippet:

    import com.microsoft.graph.authentication.IAuthenticationProvider;
    import com.microsoft.graph.authentication.TokenCredentialAuthProvider;
    import com.microsoft.graph.models.User;
    import com.microsoft.graph.requests.GraphServiceClient;
    import com.azure.identity.ClientSecretCredential;
    import com.azure.identity.ClientSecretCredentialBuilder;
    
    public class GraphClient {
        public static GraphServiceClient<Request> createGraphClient(String clientId, String clientSecret, String tenantId) {
            ClientSecretCredential clientSecretCredential = new ClientSecretCredentialBuilder()
                    .clientId(clientId)
                    .clientSecret(clientSecret)
                    .tenantId(tenantId)
                    .build();
    
            IAuthenticationProvider authProvider = new TokenCredentialAuthProvider(clientSecretCredential);
            return GraphServiceClient.builder().authenticationProvider(authProvider).buildClient();
        }
    }
    

    Replace clientId, clientSecret, and tenantId with your own values.

    Please let me know if you have any questions and I can help you further.

    If this answer helps you please mark "Accept Answer" so other users can reference it.

    Thank you,

    James


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.