How to turn a String accessToken to a TokenCredential for use in Java SDK

GZ 40 Reputation points
2024-09-16T21:33:47.9033333+00:00

Hi,

I am performing an Oauth2.0 flow and am able to get a access and refresh token via a Authorization Code flow. I would then like to use the access token to call the Graph API. The issue is that the accessToken I have is a String, while the API takes a TokenCredential. I made the following class, but it feels a bit odd that this capability does not come 'out of the box' with the API:


import com.azure.core.credential.AccessToken;
import com.azure.core.credential.TokenCredential;
import com.azure.core.credential.TokenRequestContext;
import reactor.core.publisher.Mono;

public class ManualTokenCredential implements TokenCredential {

    private final AccessToken accessToken;

    public ManualTokenCredential(AccessToken accessToken) {
        this.accessToken = accessToken;
    }

    @Override
    public Mono<AccessToken> getToken(TokenRequestContext request) {
        return Mono.fromCallable(() -> accessToken);
    }
}

See https://video2.skills-academy.com/en-us/answers/questions/1555278/how-can-i-initialize-graphserviceclient-by-providi for a C# answer, but I need one in Java.

What is the 'correct' way to do this?

Microsoft Graph
Microsoft Graph
A Microsoft programmability model that exposes REST APIs and client libraries to access data on Microsoft 365 services.
11,879 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Yakun Huang-MSFT 4,240 Reputation points Microsoft Vendor
    2024-09-17T02:44:37.0033333+00:00

    Hello GZ,

    Thank you for reaching Microsoft Support!

    You can use the graph sdk to access the Graph Api. After creating the graphClient object, you can directly call the corresponding methods through the object to access the Api. For details, see this document.

    Hope this helps.

    If the answer is helpful, please click Accept Answer and kindly upvote it. If you have any further questions about this answer, please click Comment.


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.