Home > database >  How to authenticate in MS Graph SDK with oauth2 token?
How to authenticate in MS Graph SDK with oauth2 token?

Time:02-25

I acquired the oauth2 token using the usual workflow via golang.org/x/oauth2 but can't authenticate graph sdk (github.com/microsoftgraph/msgraph-sdk-go). 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

CodePudding user response:

Fixed by changing the scope in the oauth2 config to https://graph.microsoft.com/.default. 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.

  • Related