Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
527 views
in Technique[技术] by (71.8m points)

vuejs2 - Authenticate Vue with WebAPI using AzureAD

I am trying to query the data from AzureAD protected WebAPI from Vue using vue-msal.

WebApi: 58ca819e- is webapi app id registered in AzureAD

"AzureAd": {
    "Instance": "https://login.microsoftonline.com/",
    "ClientId": "58ca819e-",
    "TenantId": "3a0cf09b-"
  },

Msal plugin in main.js: be7e77ba is spa client app id registered in AzureAD

import msal from 'vue-msal'
Vue.use(msal, {
  auth: {
    clientId: 'be7e77ba-x',
    tenantId: '3a0cf09b-x',
    redirectUri: 'http://localhost:8080/callback'
  },   
  cache: {
    cacheLocation: 'localStorage',
  },
});

In the component: $msal.acquireToken is called for access token on 2 scopes Microsoft Graph user.read and WebAPI api://58ca819e-/access_as_user where 58ca819e- is WebAPI app id registed in AzureAD.

if (!this.$msal.isAuthenticated()) {        
      this.$msal.signIn();    
    }
    else{
      this.$msal
        .acquireToken({scopes: ["user.read", 'api://58ca819e-x/access_as_user']})
        .then((res)=>{
          console.log(res.accessToken)
          this.token = res
        })
        .catch(err=>console.error(err))
    }

The received access token contains only Microsoft Graph but not WebAPI scopes. The token is invalid for the WebAPI.

"scp": "openid profile User.Read email",

When only WebAPI scope is provided, the generated token containing "scp": "access_as_user", can access the WebAPI:

this.$msal.acquireToken({scopes: ['api://58ca819e-x/access_as_user']})
or
this.$msal.acquireToken({scopes: ['api://58ca819e-x/access_as_user','user.read']})

Looks like only 1 scope is used? Can we ask the access token for >1 scopes?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

No!

A token can only correspond to one scope. The access token is issued according to the api audience you want to access, and it is unique! A token can only have one audience, and you cannot use multiple scopes to request access tokens.

You should put the api you want to access in the scope. For example, if you want to access MS graph api, you can put https://graph.microsoft.com/.default. If you want to access a custom api, you can put in api://{back-end app client api}/scope name.

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...