简体   繁体   English

Microsoft Graph API。获取用户活动

[英]Microsoft Graph API. Getting user activity

Currently I'm trying to create user activity from uwp application.目前我正在尝试从 uwp 应用程序创建用户活动。 But every time I encounter this response.但是每次遇到这种反应。

{
    "error": {
        "code": "AuthenticationError",
        "message": "Error authenticating with resource",
        "innerError": {
            "date": "2022-12-28T09:20:16",
            "request-id": "some id",
            "client-request-id": "some id"
        }
    }
}

Here is my c# code example.这是我的 c# 代码示例。 Request content string was taken from microsoft docs请求内容字符串取自微软文档

public sealed class UserActivityProvider : IUserActivityProvider
{
    private const string activityId = "SendMessageUserActivity";
    private static HttpClient httpClient = new HttpClient();

    public UserActivityProvider()
    {
    }

    private async Task<string> GetAccessTokenAsync(Account account)
    {
        var accessToken = string.Empty;

        var publicClientApplication = PublicClientApplicationBuilder.Create(MicrosoftConstants.ClientId)
           .WithRedirectUri(MicrosoftConstants.RedirectUri)
           .Build();

        var scopes = new string[]
        {
            "UserActivity.ReadWrite.CreatedByApp"
        };

        AuthenticationResult? authToken = null;

        try
        {
            authToken = await publicClientApplication.AcquireTokenSilent(scopes, account.Email).ExecuteAsync();
        }
        catch (Exception)
        {
            authToken = await publicClientApplication.AcquireTokenInteractive(scopes).ExecuteAsync();
        }

        if (authToken != null)
        {
            accessToken = authToken.AccessToken;
        }

        return accessToken;
    }

    public async Task CreateUserActivityAsync(Account account, CreatingMessageUserActivityParameters userActivityParameters)
    {
        var accessToken = await GetAccessTokenAsync(account);
        if (accessToken != string.Empty)
        {
            var contentForCreatingActivity = new StringContent("{\r\n  \"appActivityId\": \"SendMessageUserActivity\",\r\n  \"activitySourceHost\": \"https://www.contoso.com\",\r\n  \"userTimezone\": \"Africa/Casablanca\",\r\n  \"appDisplayName\": \"Contoso, Ltd.\",\r\n  \"activationUrl\": \"https://www.contoso.com/article?id=12345\",\r\n  \"contentUrl\": \"https://www.contoso.com/article?id=12345\",\r\n  \"fallbackUrl\": \"https://www.contoso.com/article?id=12345\",\r\n  \"contentInfo\": {\r\n    \"@context\": \"https://schema.org\",\r\n    \"@type\": \"Article\",\r\n    \"author\": \"Jennifer Booth\",\r\n    \"name\": \"How to Tie a Reef Knot\"\r\n  },\r\n  \"visualElements\": {\r\n    \"attribution\": {\r\n      \"iconUrl\": \"https://www.contoso.com/icon\",\r\n      \"alternateText\": \"Contoso, Ltd.\",\r\n      \"addImageQuery\": false\r\n    },\r\n    \"description\": \"How to Tie a Reef Knot. A step-by-step visual guide to the art of nautical knot-tying.\",\r\n    \"backgroundColor\": \"#ff0000\",\r\n    \"displayText\": \"Contoso How-To: How to Tie a Reef Knot\",\r\n    \"content\": {\r\n      \"$schema\": \"https://adaptivecards.io/schemas/adaptive-card.json\",\r\n      \"type\": \"AdaptiveCard\",\r\n      \"body\": [\r\n        {\r\n          \"type\": \"TextBlock\",\r\n          \"text\": \"Contoso MainPage\"\r\n        }\r\n      ]\r\n    }\r\n  }\r\n}", Encoding.UTF8, "application/json");
            httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken);
            var response = await httpClient.PutAsync($"https://graph.microsoft.com/beta/me/activities/{activityId}", contentForCreatingActivity);
            var stringifiedResponse = await response.Content.ReadAsStringAsync();
        }
    }
}

And here is also get method for retrieving all activities and it's also return bad request这里还有获取所有活动的方法,它也会返回错误的请求

public async Task<string?> IsUserActivityExistsAsync(Account account)
{
    string? resultSubject = null;

    var accessToken = await GetAccessTokenAsync(account);
    if (accessToken != string.Empty)
    {
        httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken);
        var response = await httpClient.GetAsync("https://graph.microsoft.com/v1.0/me/activities");
        var stringifiedResponse = await response.Content.ReadAsStringAsync();
    }

    return resultSubject;
}

All articles referencing that I have to provide correct scope but I took that scope from official microsoft docs and there wouldn't be a mistake.所有引用我必须提供正确的 scope 的文章,但我从官方 Microsoft 文档中获取了 scope,不会有错误。

Response for getting activities获取活动的响应

{
  "error": {
    "code": "UnknownError",
    "message": "{\"ErrorCode\":2,\"ErrorMessage\":\"Substrate operation failed. Url: https://substrate.office.com/api/v2.0/users('******(73)')/CurrentCollections('******(10)') Status: Unauthorized. Error Code: invalid_tenant Error Message: The tenant for tenant guid 'tenant' does not exist., SubstrateError: null\"}",
    "innerError": {
      "date": "2022-12-29T05:44:57",
      "request-id": "id",
      "client-request-id": "id"
    }
  }
}

Response for adding activities添加活动的响应

{
  "error": {
    "code": "UnknownError",
    "message": "{\"ErrorCode\":35,\"ErrorMessage\":\"General error occurred. Contact product team.\"}",
    "innerError": {
      "date": "2022-12-29T05:59:02",
      "request-id": "id",
      "client-request-id": "id"
    }
  }
}

Please make sure that UserActivity.ReadWrite.CreatedByApp MS Graph API permissions are assigned to your app in Azure AD as Delegated type (not Application)请确保在 Azure AD 中将UserActivity.ReadWrite.CreatedByApp MS Graph API 权限分配给您的应用程序作为委托类型(而非应用程序)

As you said you are getting empty data when you decoded the access token in jwt.ms, which means you are doing something wrong while acquiring access token, follow the doc to get token via Interactive provider , and then again check by decoding in jwt.ms.正如你所说,当你在 jwt.ms 中解码访问令牌时,你得到的是空数据,这意味着你在获取访问令牌时做错了,按照文档通过Interactive provider获取令牌,然后再次通过解码 jwt 进行检查。小姐。

var scopes = new[] { "User.Read" };

// Multi-tenant apps can use "common",
// single-tenant apps must use the tenant ID from the Azure portal
var tenantId = "common";

// Value from app registration
var clientId = "YOUR_CLIENT_ID";

// using Azure.Identity;
var options = new InteractiveBrowserCredentialOptions
{
    TenantId = tenantId,
    ClientId = clientId,
    AuthorityHost = AzureAuthorityHosts.AzurePublicCloud,
    // MUST be http://localhost or http://localhost:PORT
    // See https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/wiki/System-Browser-on-.Net-Core
    RedirectUri = new Uri("http://localhost"),
};

// https://learn.microsoft.com/dotnet/api/azure.identity.interactivebrowsercredential
var interactiveCredential = new InteractiveBrowserCredential(options);

var graphClient = new GraphServiceClient(interactiveCredential, scopes);

暂无
暂无

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

相关问题 从使用 Microsoft Graph API 发送的电子邮件中打开附加的 Excel 文件时出错。 错误“Excel 无法打开文件,因为...” - Getting error when opening an attached Excel file from the email sent using Microsoft Graph API. Error "Excel cannot open the file because the.." Microsoft Graph API-以其他用户身份发送电子邮件 - Microsoft Graph API - Sending email as another user 使用UWP中的microsoft Graph API为登录用户获取特定日期的会议邀请和事件 - Getting meeting invites & events for the specific day for the logged in user using microsoft Graph API in UWP Graph API-在Microsoft图形控制台应用程序中获取权限不足 - Graph API - Getting Insufficient privileges in microsoft graph console application 尝试使用Microsoft Graph API v1.0查询用户的office365个人资料照片时获取“ErrorAccessDenied” - Getting “ErrorAccessDenied” while trying to query for a user's office365 profile photo using Microsoft Graph API v1.0 从 Graph API 获取指定用户 - Getting a specified user from Graph API Microsoft Graph API Microsoft 登录 - Microsoft Graph API Microsoft Login Microsoft Graph API:出现错误“Authorization_IdentityNotFound” - Microsoft Graph API: Getting error “Authorization_IdentityNotFound” C# - Microsoft Graph API - 从自定义列表中获取图片 - C# - Microsoft Graph API - Getting Pictures from Customlist Microsoft Graph API 测试 - 代表用户获取访问权限 - Microsoft Graph API tests - get access on behalf of user
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM