我正在尝试调整此处和此处引用的示例 B2C 代码,以针对我们的组织 AAD 工作。
我有一个 SPA 应用程序,它通过 MSAL 成功通过 AAD 进行身份验证并接收令牌。SPA 应用程序可以使用令牌从 MS Graph API 中提取数据——所以我确定令牌是有效的。
SPA 当前在本地运行@localhost:9000。
我有第二个应用程序,它是一个运行 @ localhost:3000 的 Nodejs API。SPA 应用程序调用 API,传递用于 GraphAPI 的相同令牌。API 应用程序应该使用该令牌来验证用户并提供对 API 的访问;但是,我只得到一个 401 - Unauthorized。
(我将 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)
})
我确定我只是误解了这一切是如何工作的,但希望能得到一些指导,了解我需要改变什么才能使其正常工作。