ウェブサイト検索

C# - React-TypeScriptウェブアプリでMsal.jsを使用した.net core API呼び出しのOAuth2認証が失敗する


私は、.NET Core APIと通信する必要があるクライアントのTypeScript Reactウェブアプリケーションを持っています。クライアント側ではmsal.jsが統合されています。AADにログインし、ユーザーアカウントとアクセストークンを取得し、それをBearerとしてAPI呼び出しに渡すことはできます。しかし、APIレベルでの認証は失敗します。

クライアント側:

config: Msal.Configuration = buildConfiguration({ auth: {
        clientId: 'clientId',
        authority: 'authority',
        validateAuthority: true,
        navigateToLoginRequestUrl: false
    } });

 request = {
        scopes: ["user.read"] 
     };

    userAgentApp : Msal.UserAgentApplication = new Msal.UserAgentApplication(this.config);

private _accessToken: string = '';
    public async GetAccessToken(): Promise<string>{
        if(this._accessToken == '')
        {
            await this.userAgentApp.acquireTokenSilent(this.request)
                .then((tokenResponse) => this._accessToken = tokenResponse.accessToken)
                .catch((error) => console.log(error))
        }

        return this._accessToken;
    }

    public login() {
        console.log("before login");

        this.userAgentApp.handleRedirectCallback((error, response) => 
        { 
            console.error(error)
        });

        this.userAgentApp.loginRedirect(this.request);

        console.log("after login")
    }

// Calling the api
  axios.defaults.headers.common = {'Authorization': `Bearer ${accessToken}`}
      const travelExpensesResponse = await axios.get("https://localhost:44350/api/reisekostenantrag")

APIについて

// Start.cs ConfigureServices
  services.AddAuthentication(sharedOptions =>
            {
                sharedOptions.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
            })
 .AddJwtBearer(options =>
            {
                options.Audience = "clientId";
                options.Authority = "authority";
            });

私は SecurityTokenInvalidSignatureException: IDX10511: 署名の検証に失敗しました を取得しています。

  1. 問題はどこにあるのでしょうか?
  2. クライアントアプリから .NET Core API にトークンを渡す方法を示すサンプルはありますか?

回答 #1

問題は、そのトークンに user.read というスコープが付与されていたことで、これは Graph API のスコープです。

そこで、解決策は Azure にサーバーアプリを登録し、カスタムスコープを作成することでした。

その後、クライアントアプリで:

 request = {
        scopes: ["api://clientid/access_as_user"] 
     };