не удалось получить фотографию из графического API из веб-приложения переднего плана SPA - PullRequest
0 голосов
/ 04 августа 2020

Я использую ADAL js для аутентификации пользователя, и я могу успешно аутентифицировать пользователя. Я могу получить токен для api графика и прочитать профиль пользователя со следующим URL-адресом.

        GET
https://graph.microsoft.com/v1.0/me

Но я не могу прочитать изображение профиля пользователя:

https://graph.microsoft.com/v1.0/me/photo/$value

Я получаю следующая ошибка

  Object { code: "NoPermissionsInAccessToken", message: "The token contains no permissions, or permissions can not be understood.", innerError: {…} }

Я установил необходимые разрешения:

введите описание изображения здесь Есть ли способ проверить, почему я могу получить профиль, но не фото.

Содержимое JWT, отправленное в заголовке до получения ошибки 401:

        {
          "typ": "JWT",
          "nonce": "IenxIPCU1ue14Z9bIIxEidRBBCTnL52w4Q",
          "alg": "RS256",
          "x5t": "huN95IvPf34GzBDZ1GXGirnM",
          "kid": "huN95hq34GzBGXGirnM"
        }

Тело Токен JWT:

        {
          "aud": "https://graph.microsoft.com",
          "iss": "https://sts.windows.net/6f1dc6d4-8e90-4593/",
          "iat": 1596560469,
          "nbf": 1596560469,
          "exp": 1596564369,
          "acct": 1,
          "acr": "1",
          "aio": "ATQAy/8QAAAAf64iQ9pAkP+bk/JnXpSNXFPVFqvW/urra8A2QueWm2xaJZM+",
          "altsecid": "5::100320A47F8DD5",
          "amr": [
            "wia"
          ],
          "app_displayname": "graphdemo-dev",
          "appid": "dsfkj32-4350-44a4-dd33-f45b7172b0cd",
          "appidacr": "0",
          "email": "email@domain.com",
          "family_name": "faily",
          "given_name": "given",
          "idp": "https://sts.windows.net/deff24bb-2089-4400378b2/",
          "in_corp": "true",
          "ipaddr": "70.50.13.18",
          "oid": "dskfs77s-5bc6-4fbe-b59a-11fbc2",
          "platf": "3",
          "puid": "A9BDE43D",
          "scp": "profile User.Read User.Read.All User.ReadBasic.All User.ReadWrite User.ReadWrite.All",
          "sub": "r4-9Ra9nHTjU-g1PvuXwh18",
          "tenant_region_scope": "NA",
          "tid": "d4-8e90-4599-af70-13a4289b3",
          "unique_name": "email@domain.com",
          "uti": "MDGPXbP3lUJMyAA",
          "ver": "1.0",
          "xms_tcdt": 8700342
        }

Примечание: я удалил и обновил конфиденциальные данные со случайными символами.

Когда я пробовал в Graph Explorer:

        Need admin approval
        Graph explorer (official site)
        microsoft.com
        Graph explorer (official site) needs permission to access resources in your organization that only an admin can grant. Please ask an admin to grant permission to this app before you can use it.
        import AuthenticationContext from 'adal-angular/lib/adal.js';

        // KPMG
        const config = {
          tenant: process.env.VUE_APP_AZUREAD_TENANTID,
          clientId: process.env.VUE_APP_AZUREAD_CLIENTID,
          cacheLocation: process.env.VUE_APP_CACHE_LOCATION,
          redirectUri: process.env.VUE_APP_REDIRECT_URI
        };


        export default {
          authenticationContext: null,
          /**
           * @return {Promise}
           */
          initialize() {
            this.authenticationContext = new AuthenticationContext(config);

            return new Promise((resolve, reject) => {
              if (this.authenticationContext.isCallback(window.location.hash) || window.self !== window.top) {
                // redirect to the location specified in the url params.
                this.authenticationContext.handleWindowCallback();
              }
              else {
                // try pull the user out of local storage
                const user = this.authenticationContext.getCachedUser();
                if (user) {
                  this.authenticationContext.config.extraQueryParameter = 'login_hint=' + user.userName;
                  resolve();
                }
                else {
                  // no user at all - go sign in..
                  this.signIn();
                }
              }
            });
          },

I используйте приведенный ниже код, чтобы получить токен api графика

         acquireGraphApiToken() {
            return new Promise((resolve, reject) => {
              this.authenticationContext.acquireToken('https://graph.microsoft.com', (error, graphApiToken) => {
                if (error || !graphApiToken) {
                  this.signOut();
                  return reject(error);
                } else {
                  return resolve(graphApiToken);
                }
              });
            });
          },

1 Ответ

0 голосов
/ 05 августа 2020

Для Microsoft Graph Explorer вам необходимо войти в систему с учетной записью администратора и получить согласие администратора следующим образом:

enter image description here

Do the admin consent:

enter image description here

And from the screenshot above, you can see the access token. After you finish the admin consent, you can decode the access token to see if it includes the required permissions.

For you own Azure AD application, I see that you have done the admin consent based on your screenshot. It's hard to say where the problem is. So my suggestion is to try the конечная точка согласия администратора :

// Line breaks are for legibility only.
GET https://login.microsoftonline.com/{tenant}/v2.0/adminconsent?
client_id=6731de76-14a6-49ae-97bc-6eba6914391e
&state=12345
&redirect_uri=http://localhost/myapp/permissions
&scope=
https://graph.microsoft.com/calendars.read
https://graph.microsoft.com/mail.send

Получите доступ к этому URL-адресу в браузере с помощью учетной записи администратора и sh согласия. Если проблема все еще существует, вы можете создать новое приложение Azure AD и добавить только необходимое разрешение User.Read (не добавляйте другие разрешения).

...