API将不会使用MSAL通过SPA传递的令牌对AAD进行身份validation

我正在尝试修改这里和这里引用的示例B2C代码,以对抗我们的组织AAD。

我有一个SPA应用程序,通过MSAL成功地通过AAD进行身份validation,并接收令牌。 SPA应用程序可以使用令牌从MS Graph API中提取数据 – 所以我确定该令牌是有效的。

SPA当前在本地运行@ localhost:9000。

我有第二个应用程序是运行@ localhost:3000的Nodejs API。 SPA应用程序调用API传递用于GraphAPI的相同标记。 API应用程序应该使用该令牌来validation用户并提供对API的访问; 然而,我只能回到401 – 未经授权。

(我使用Aurelia作为客户端代码,HTTP请求使用Aurelia的HTTP客户端)。

以下是用于调用API的SPA代码:

//Not entirely sure what to use as the scope here!! API is registered to allow user.read Graph API scope. this.config.msClient.acquireTokenSilent(["user.read"]).then(token => { console.log("Token acquired silently."); this.makeAPICall(token); }, error => { ... } ); makeAPICall(token) { this.http.configure(config => { config .withBaseUrl('http://localhost:3000/') .withDefaults({ headers: { 'Authorization': 'Bearer ' + token } } this.http.fetch("user/0") .then(response => { debugger; //response is 401 Unauthenticated at this point }, error => { ... }); } 

我已经在apps.dev.microsoft.com上为我的API注册了一个应用程序。 这里是我的服务器端(API)Nodejs代码:

 const express = require("express") const port = 3000 const passport = require("passport") var BearerStrategy = require("passport-azure-ad").BearerStrategy; var userList = [ {id: 1, first: "Mickey", last: "Mouse", age: 95}, {id: 2, first: "Donald", last: "Duck", age: 85}, {id: 3, first: "Pluto", last: "leDog", age: 70} ] var options = { identityMetadata: "https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration", clientID: "xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx", //My registered App Id passReqToCallback: false, validateIssuer: true, issuer: "xxxxxxx" //Our tenant name }; var strategy = new BearerStrategy(options, (token, done) => { console.log(token); done(null,{}, {scope: '*'}); }) const app = express() app.use(passport.initialize()) passport.use(strategy); //Allow CORS app.use((req, res, next) => { res.header("Access-Control-Allow-Origin","*"); res.header("Access-Control-Allow-Headers","Authorization, Origin, X-Requested-With, Content-Type,Accept"); next(); }) app.get("/",(request, response) => { //Unauthenticated -- always works response.send("Hello World!") }) app.get("/user/:id",passport.authenticate('oauth-bearer',{session: false }), (request, response) => { //Never seem to get here (when debugging) as authenticate always fails let id = request.params["id"]; let user = userList[id]; if(user) response.json(user); else response.send("No user found") }) app.listen(port, () => { console.log("Listening on port " + port) }) 

我敢肯定,我只是误解了这一切如何工作,但会感谢一些指导,我需要改变,以使其工作。

代币就像银行支票:只能由他们写的人来caching。 为MS Graph发布的令牌将具有Microsoft Graph的受众,并且只能由Microsoft Graph接受。 任何接收该标记的其他API X都应该拒绝它。 打算调用X的客户端应该为X请求一个令牌,不pipe它是否已经有另一个服务的令牌(如Microsoft图)。 这里有一个stream程的例子,用ADAL JS实现: https ://azure.microsoft.com/en-us/resources/samples/active-directory-angularjs-singlepageapp-dotnet-webapi/此时Azure AD v2由MSAL使用)无法为自定义API发出访问令牌:该function正在开发中,但是我们没有ETA,因此无法在生产环境中使用。 在此之前,这个拓扑结构不支持v2(因此MSAL JS)。 抱歉!