【发布时间】:2017-10-20 20:36:01
【问题描述】:
我有一个使用 MSAL 从 AAD 获取令牌的 SPA 应用程序。因为 MSAL 与 v2 端点一起使用,并且因为 v2 端点当前不支持为自定义 API 颁发令牌,所以我将 ID 令牌传递给我的 api,并且基本上将我的 api 视为同一个应用程序。 (虽然这有异味,但它确实有效——至少使用 Nodejs API)。
SPA 应用
let idToken = Msal.Storage('localStorage').getItem(Msal.Constants.idTokenKey);
this.http.configure(config => {
config.withBaseUrl("http://localhost:3001/")
config.withDefaults({headers: {'Authorization': 'Bearer ' + idToken}})
});
//Call API
this.http.fetch("account")
...
Node.js API
//Using express/passport
var BearerStrategy = require("passport-azure-ad").BearerStrategy;
var options = {
identityMetadata: "https://login.microsoftonline.com/tenantid/.well-known/openid-configuration/",
clientID: "xxxxxxx-xxxx-xxxxxxx-xxxxx",
passReqtoCallback: false,
validateIssuer: true,
issuer: "http://login.microsoftonline.com/{tenantid}/v2.0"
};
app.get("/account",passport.authenticate('oauth-bearer',{session: false}),...
以上所有工作。一旦用户通过 SPA 进行身份验证,令牌就会被传递,并且对 Node API 的调用就会起作用。
我现在正在尝试用 .Net WebAPI 替换 Nodejs API。我有以下内容:
Startup.cs
app.UseWindowsAzureActiveDirectoryBearerAuthentication(
new WindowsAzureActiveDirectoryBearerAuthenticationOptions
{
TokenValidationParameters = new TokenValidationParameters
{
//Same ID as used for ClientID in Nodejs
ValidAudience = "xxxxxx-xxxxx-xxxxx-xxxxx",
ValidIssuer = "https://login.microsoftonline.com/{tenantid}/v2.0",
ValidateIssuer = true,
AuthenticationType = "WebApi" //Tried both with and without this
},
Tenant = "{tenantid}" //have tried both id and name
}
)
AccountController.cs
[Authorize]
[Route("account")]
public IHttpActionResult AccountProfile(){
//Get Account information
....
return Ok(profile);
}
但是,当我指向 SPA 应用程序调用 .Net api 时,我总是得到 Authorization has been denied for this request 。
我有什么遗漏吗?
编辑
顺便说一下,我检查了正在使用的令牌。
我用于 clientID (Nodejs) 和 ValidAudience (.Net) 的值与令牌中的 aud 声明完全匹配。 issuer (Nodejs) 和 ValidIssuer (.Net) 与令牌中的 iss 声明完全匹配。最后,在我插入 {tenantid} 的代码中的任何位置,那里的实际值与令牌中的 tid 声明完全匹配。
【问题讨论】:
-
您需要使用 MSAL 吗? ADAL 目前似乎更容易集成。
标签: asp.net-web-api azure-active-directory msal