この記事では、Microsoft Graph とアプリのみの認証を使用して 、Build Go アプリで作成したアプリケーションにアプリ専用認証を追加します。
Azure Identity Client Module for Go には、OAuth2 トークン フローを実装する多くのTokenCredential クラスが用意されています。
Microsoft Graph SDK for Go では、これらのクラスを使用して Microsoft Graph への呼び出しを認証します。
アプリ専用認証用に Graph クライアントを構成する
このセクションでは、 ClientSecretCredential クラスを使用して、 クライアント資格情報フローを使用してアクセス トークンを要求します。
次の関数を ./graphhelper/graphhelper.go に追加します。
func (g *GraphHelper) InitializeGraphForAppAuth() error { clientId := os.Getenv("CLIENT_ID") tenantId := os.Getenv("TENANT_ID") clientSecret := os.Getenv("CLIENT_SECRET") credential, err := azidentity.NewClientSecretCredential(tenantId, clientId, clientSecret, nil) if err != nil { return err } g.clientSecretCredential = credential // Create an auth provider using the credential authProvider, err := auth.NewAzureIdentityAuthenticationProviderWithScopes(g.clientSecretCredential, []string{ "https://graph.microsoft.com/.default", }) if err != nil { return err } // Create a request adapter using the auth provider adapter, err := msgraphsdk.NewGraphRequestAdapter(authProvider) if err != nil { return err } // Create a Graph client using request adapter client := msgraphsdk.NewGraphServiceClient(adapter) g.appClient = client return nil }ヒント
goimportsを使用している場合は、graphhelper.go のimportステートメントから一部のモジュールが削除される場合があります。 ビルドするには、モジュールをもう一度追加する必要がある場合があります。graphapponlytutorial.go の空の
initializeGraph関数を次のように置き換えます。func initializeGraph(graphHelper *graphhelper.GraphHelper) { err := graphHelper.InitializeGraphForAppAuth() if err != nil { log.Panicf("Error initializing Graph for app auth: %v\n", err) } }
このコードでは、 DeviceCodeCredential オブジェクトと GraphServiceClient オブジェクトの 2 つのプロパティを初期化します。
InitializeGraphForUserAuth関数は、DeviceCodeCredentialの新しいインスタンスを作成し、そのインスタンスを使用してGraphServiceClientの新しいインスタンスを作成します。 API 呼び出しが userClientを介して Microsoft Graph に対して行われるたびに、提供された資格情報を使用してアクセス トークンを取得します。
ClientSecretCredential をテストする
次に、 ClientSecretCredentialからアクセス トークンを取得するコードを追加します。
次の関数を ./graphhelper/graphhelper.go に追加します。
func (g *GraphHelper) GetAppToken() (*string, error) { token, err := g.clientSecretCredential.GetToken(context.Background(), policy.TokenRequestOptions{ Scopes: []string{ "https://graph.microsoft.com/.default", }, }) if err != nil { return nil, err } return &token.Token, nil }graphapponlytutorial.go の空の
displayAccessToken関数を次のように置き換えます。func displayAccessToken(graphHelper *graphhelper.GraphHelper) { token, err := graphHelper.GetAppToken() if err != nil { log.Panicf("Error getting user token: %v\n", err) } fmt.Printf("App-only token: %s", *token) fmt.Println() }go run graphapponlytutorialを実行してアプリをビルドして実行します。 オプションの入力を求められたら、「1」と入力します。 アプリケーションにアクセス トークンが表示されます。Go Graph App-Only Tutorial Please choose one of the following options: 0. Exit 1. Display access token 2. List users 3. Make a Graph call 1 App-only token: eyJ0eXAiOiJKV1QiLCJub25jZSI6IlVDTzRYOWtKYlNLVjVkRzJGenJqd2xvVUcwWS...ヒント
検証とデバッグ のみを目的として、 https://jwt.msで Microsoft のオンライン トークン パーサーを使用してアプリ専用アクセス トークンをデコードできます。 トークンの解析は、Microsoft Graph を呼び出すときにトークン エラーが発生した場合に役立ちます。 たとえば、トークン内の
role要求に、想定される Microsoft Graph アクセス許可スコープが含まれていることを確認します。