我有一个ASP.NET MVC Web应用程序,需要检查用户是否是Azure Active Directory中特定组的成员。要实现这一点,我将使用Microsoft Graph API,因此我下载了他们的示例,以便从here进行试用,并使其正常运行。
我的下一步是使用自己的AppId,AppSecret和RedirectUri运行它,这就是我遇到麻烦的地方。在Azure中,我为AAD进行了“App registrations”,并确保添加了该应用程序。我打开了应用程序并复制了AppId的“应用程序ID”,创建了一个密钥并将其用作AppSecret。我检查了所有权限并按了“授予权限”并将我的URL添加到了回复URL。我还将权限属性从https://login.microsoftonline.com/common/v2.0更改为https://login.windows.net/xxxxxx.onmicrosoft.com。
当我运行应用程序并按“登录”时,我将正确进入登录界面,但是当我尝试登录时它会崩溃。在下面的代码中运行AcquireTokenByAuthorizationCodeAsync时会发生崩溃:
AuthorizationCodeReceived = async (context) =>
{
var code = context.Code;
string signedInUserID = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;
ConfidentialClientApplication cca = new ConfidentialClientApplication(
appId,
redirectUri,
new ClientCredential(appSecret),
new SessionTokenCache(signedInUserID, context.OwinContext.Environment["System.Web.HttpContextBase"] as HttpContextBase));
string[] scopes = graphScopes.Split(new char[] { ' ' });
AuthenticationResult result = await cca.AcquireTokenByAuthorizationCodeAsync(scopes, code);
},
AuthenticationFailed = (context) =>
{
context.HandleResponse();
context.Response.Redirect("/Error?message=" + context.Exception.Message);
return Task.FromResult(0);
}
我在AuthenticationFailed中收到的错误消息如下所示:
AADSTS70001:此API版本不支持应用程序“xxxxxxxx-4f81-4508-8dcb-df5b94f2290f”。跟踪ID:xxxxxxxx-d04c-4793-ad14-868810f00c00相关ID:xxxxxxxx-ab83-4805-baea-8f590991ec0c时间戳:2017-06-13 10:43:08Z
有人可以向我解释错误信息的含义吗?我应该尝试不同的版本吗?我尝试过使用Microsoft.Graph v1.3.0 / Microsoft.Graph.Core v1.4.0和Microsoft.Graph v1.4.0 / Microsoft.Graph.Core v1.5.0。
答案 0 :(得分:2)
您正在尝试将MSAL与v1端点一起使用。使用ConfidentialClientApplication
就可以看出这一点。您需要使用ADAL(Azure AD身份验证库)。 或者在https://apps.dev.microsoft.com注册v2的应用。
您可以从NuGet获取ADAL:https://www.nuget.org/packages/Microsoft.IdentityModel.Clients.ActiveDirectory/
您可以在此处找到使用ADAL的示例应用:https://github.com/Azure-Samples/active-directory-dotnet-webapp-webapi-openidconnect
你的OnAuthorizationCodeReceived需要看起来像这样:
private async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedNotification context)
{
var code = context.Code;
ClientCredential credential = new ClientCredential(clientId, appKey);
string userObjectID = context.AuthenticationTicket.Identity.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
AuthenticationContext authContext = new AuthenticationContext(Authority, new NaiveSessionCache(userObjectID));
// If you create the redirectUri this way, it will contain a trailing slash.
// Make sure you've registered the same exact Uri in the Azure Portal (including the slash).
Uri uri = new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path));
AuthenticationResult result = await authContext.AcquireTokenByAuthorizationCodeAsync(code, uri, credential, graphResourceId);
}