简体   繁体   English

获取 Microsoft Graph API 的有效访问令牌

[英]Obtaining a valid access token for Microsoft Graph API

I am working on an ASP.NET MVC5 Web App that uses Azure ADAL libraries to authenticate users, it works fine, however, when I manually send requests to graph, ex: GET https://graph.microsoft.com/v1.0/me or GET https://graph.microsoft.com/v1.0/groups ?$filter=from/displayName eq 'whatever'.我正在开发一个使用 Azure ADAL 库对用户进行身份验证的 ASP.NET MVC5 Web 应用程序,它工作正常,但是,当我手动向图形发送请求时,例如:GET https://graph.microsoft.com/v1.0 /me或 GET https://graph.microsoft.com/v1.0/groups ?$filter=from/displayName eq 'whatever'。

I have tried updating the App Registration in Azure as to add the required Graph permissions, and I have also tried creating new app registrations, no matter what I do my requests will always respond 401 Unauthorized, is there anything I am missing?我尝试更新 Azure 中的应用注册以添加所需的 Graph 权限,并且我也尝试创建新的应用注册,无论我做什么,我的请求总是会响应 401 Unauthorized,有什么我遗漏的吗?

EDIT: Example response from Postman编辑:来自邮递员的示例响应

{
  "error": {
    "code": "InvalidAuthenticationToken",
    "message": "Access token validation failure.",
    "innerError": {
      "request-id": "a142576b-acce-4e59-8a8d-adede61aaf59",
      "date": "2017-04-05T13:27:36"
    }
  }
}

EDIT: C# Request Example编辑:C# 请求示例

public async Task<GroupGraph> GetGroupIdByDisplayName(string displayName)
{
    var accessToken = await authenticationService.GetTokenUserOnly();
    GroupGraph groupGraphResponse = null;
    using (var client = new HttpClient())
    {
        using (var request = new HttpRequestMessage(HttpMethod.Get, $"https://graph.microsoft.com/v1.0/groups?$filter=from/displayName eq '{displayName}'"))
            {
                request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
                using (var response = client.SendAsync(request).Result)
                {
                    if (response.IsSuccessStatusCode)
                    {
                        using (var content = response.Content)
                        {
                            var result = await content.ReadAsStringAsync();
                            groupGraphResponse = JsonConvert.DeserializeObject<GroupGraph>(result);
                        }
                    }
                }
            }
        }
        return groupGraphResponse;
    }

EDIT: The way I obtain the token编辑:我获取令牌的方式

public async Task<string> GetTokenUserOnly()
    {
        string signedInUserID = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
        string tenantID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
        string userObjectID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;

        // get a token for the Graph without triggering any user interaction (from the cache, via multi-resource refresh token, etc)
        ClientCredential clientcred = new ClientCredential(clientId, appKey);
        // initialize AuthenticationContext with the token cache of the currently signed in user, as kept in the app's database
        AuthenticationContext authenticationContext = new AuthenticationContext(aadInstance + tenantID, new TableTokenCache(signedInUserID));
        //AuthenticationResult authenticationResult = await authenticationContext.AcquireTokenSilentAsync(graphResourceID, clientcred, new UserIdentifier(userObjectID, UserIdentifierType.UniqueId));
        AuthenticationResult authenticationResult = authenticationContext.AcquireToken(graphResourceID, clientcred);
        return authenticationResult.AccessToken;
    }

You can't use ADAL to get tokens for graph.您不能使用 ADAL 来获取图形的令牌。 microsoft .com.微软.com。 ADAL is for graph. ADAL 用于图形。 windows .net.视窗.net。

In order to get tokens for the Graph library (graph.windows.com) look into the Nuget Package Microsoft.Graph.为了获取 Graph 库 (graph.windows.com) 的令牌,请查看 Nuget 包 Microsoft.Graph。 Microsoft also has some documentation on how to pull user info using Graph. Microsoft 也有一些关于如何使用 Graph 提取用户信息的文档

Be forewarned though, using Graph Libraries and ADAL libraries side by side can lead to some weird side effects, such as the credential cache being cleared.但请注意,同时使用图形库和 ADAL 库可能会导致一些奇怪的副作用,例如凭据缓存被清除。

It seems you are using the client credential grant flow to acquire the access token for graph api( graphResourceID is https://graph.microsoft.com ?) :您似乎正在使用客户端凭据授予流程来获取图形 api 的访问令牌( graphResourceIDhttps://graph.microsoft.com ?):

  AuthenticationResult authenticationResult = authenticationContext.AcquireToken(graphResourceID, clientcred);

So you need to grant app permission in azure ad portal :因此,您需要在 azure 广告门户中授予应用权限:

在此处输入图片说明

For error "Access token validation failure" , you could use online tool like http://jwt.calebb.net/ to decode your access token , check the audience or lifetime of the access token .对于错误“访问令牌验证失败”,您可以使用诸如http://jwt.calebb.net/ 之类的在线工具来解码您的访问令牌,检查访问令牌的受众或生命周期。

To obtain a valid token for Microsoft Graph API you can use Azure.Identity .要获取 Microsoft Graph API 的有效令牌,您可以使用Azure.Identity

To use any implementation of TokenCredential we need to build our own IAuthenticationProvider .要使用TokenCredential任何实现,我们需要构建我们自己的IAuthenticationProvider

public class TokenCredentialAuthenticationProvider : IAuthenticationProvider
{
    private readonly TokenCredential _tokenCredential;

    public TokenCredentialAuthenticationProvider(TokenCredential tokenCredential)
    {
        _tokenCredential = tokenCredential;
    }
    public async Task AuthenticateRequestAsync(HttpRequestMessage request)
    {
        var accessToken = await _tokenCredential.GetTokenAsync(new TokenRequestContext(new[] { "https://graph.microsoft.com" }), CancellationToken.None);
        request.Headers.Authorization = new AuthenticationHeaderValue("bearer", accessToken.Token);
    }
}

Now we can for instance use AzureCliCredential to acquire an access token.例如,现在我们可以使用 AzureCliCredential 来获取访问令牌。

Open Powershell and type in az login in order to login with your Azure AD account.打开 Powershell 并输入az login以使用您的 Azure AD 帐户登录。

In Azure you could also use Managed Identity to get a token based on a Azure resource eg Azure App Service.在 Azure 中,您还可以使用Managed Identity来获取基于 Azure 资源(例如 Azure 应用服务)的令牌。 Here need to use ManagedIdentityToken .这里需要使用ManagedIdentityToken

Usage:用法:

var client = new GraphServiceClient(new TokenCredentialAuthenticationProvider(new AzureCliCredential()));
var user = await client.Me.Request().GetAsync();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从 Azure Active Directory 获取我的 API 和 Microsoft Graph 的有效访问令牌? - How to Get a valid access token for my API and Microsoft Graph from Azure Active Directory? Microsoft Graph API-无法刷新访问令牌 - Microsoft Graph API - cannot refresh access token Microsoft graph api:即使在获得管理员同意后,令牌也不包含权限 - Microsoft graph api: Token does not contain permissions even after obtaining admin consent 无法为 microsoft api 获取有效的访问令牌 - can't acquire a valid access token for microsoft api 什么是为Microsoft Graph API生成访问令牌的限制 - What is limit of genrating access token for Microsoft Graph API 如何从Microsoft Graph API获取访问令牌? - How do I get an access token from Microsoft Graph API? Microsoft Graph Access令牌包含对联系人API的错误权限 - Microsoft Graph Access Token contains wrong permission for contacts API 获取 Microsoft Teams 机器人的访问令牌以与图形 API 一起使用 - Get an access token for a bot with Microsoft Teams for use with graph API 如何使用 Microsoft Graph API 为应用设置访问令牌生命周期 - How to set the access token lifetime for an app using the Microsoft Graph API Microsoft Graph API返回“访问令牌验证错误” - Microsoft Graph API Returning “Access Token Validation Error”
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM