How to authenticate in MS Graph SDK with oauth2 token?


I acquired the oauth2 token using the usual workflow via but can’t authenticate graph sdk ( My app allows both multi-tenant AD and personal accounts.

I implemented azcore.TokenCredential interface:

type azureTokenCredential struct {
    token oauth2.Token

func (c azureTokenCredential) GetToken(_ context.Context, _ policy.TokenRequestOptions) (*azcore.AccessToken, error) {
    return &azcore.AccessToken{
        Token:     c.token.AccessToken,
        ExpiresOn: c.token.Expiry,
    }, nil

And that’s how I use it:

cred := azureTokenCredential{token: token}
auth, err := a.NewAzureIdentityAuthenticationProvider(cred)
if err != nil {
    return "", errors.WithStack(err)
adapter, err := msgraphsdk.NewGraphRequestAdapter(auth)
if err != nil {
    return "", errors.WithStack(err)
client := msgraphsdk.NewGraphServiceClient(adapter)
u, err := client.Me().Get(nil)

I get the following error when I sign in with an AD account:

The server returned an unexpected status code and no error factory is registered for this code: 401


Fixed by changing the scope in the oauth2 config to Now when a user signs in it sees a consent screen. I also added necessary Microsoft Graph permissions from the API permissions screen of my App Registration page.

Answered By – chingis

Answer Checked By – Katrina (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.