Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,20 @@ if (response.IsSuccessStatusCode)
}
```

## Current-user request builders

The SDK can reuse `/users/{user-id}` request builders for `Me` by setting the user ID
to `CoreConstants.ReplacementConstants.UserIdTokenToReplace`. The default
`GraphClientFactory` pipeline rewrites this reserved `/users/TokenToReplace` path
to `/me` before sending the request; it does not resolve or fetch a user ID.
Batch request steps apply the same replacement before serialization.

If you supply your own `HttpClient` or middleware pipeline, include
`UriReplacementHandler<GraphUriReplacementHandlerOption>` configured with
`new GraphUriReplacementHandlerOption()` to retain this behavior. Custom request
adapters must provide equivalent rewriting. Ordinary user IDs and query values
are not replaced.

## Documentation and resources

* [Microsoft Graph API](https://graph.microsoft.com)
Expand Down
2 changes: 1 addition & 1 deletion global.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"sdk": {
"version": "10.0.202",
"version": "10.0.404",
"rollForward": "major"
}
}
21 changes: 21 additions & 0 deletions src/Microsoft.Graph.Core/CoreConstants.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,27 @@
/// </summary>
public const int PollingIntervalInMs = 5000;

/// <summary>
/// Constants used to reuse user request builders for the current user.
/// </summary>
public static class ReplacementConstants
{
/// <summary>
/// Reserved user ID used by current-user request builders.
/// </summary>
public const string UserIdTokenToReplace = "TokenToReplace";

/// <summary>
/// Synthetic users endpoint replaced before sending a request.
/// </summary>
public const string UsersEndpointWithReplaceToken = "/users/" + UserIdTokenToReplace;

/// <summary>
/// Current-user endpoint.
/// </summary>
public const string MeEndpoint = "/me";
}

/// <summary>
/// Header constants.
/// </summary>
Expand Down Expand Up @@ -98,7 +119,7 @@

internal const string Status = "status";

internal const string Headers = "headers";

Check warning on line 122 in src/Microsoft.Graph.Core/CoreConstants.cs

View workflow job for this annotation

GitHub Actions / Build

Rename this field to not shadow the outer class' member with the same name.

}

Expand Down
1 change: 1 addition & 0 deletions src/Microsoft.Graph.Core/Models/BatchRequestStep.cs
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ public BatchRequestStep(string requestId, HttpRequestMessage httpRequestMessage,
RequestId = (!string.IsNullOrEmpty(requestId)) ? requestId : throw new ArgumentNullException(nameof(requestId));

Request = httpRequestMessage ?? throw new ArgumentNullException(nameof(httpRequestMessage));
Request.RequestUri = new GraphUriReplacementHandlerOption().Replace(Request.RequestUri);

DependsOn = dependsOn;
}
Expand Down
1 change: 1 addition & 0 deletions src/Microsoft.Graph.Core/Requests/GraphClientFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,7 @@ public static HttpClient Create(
public static IList<DelegatingHandler> CreateDefaultHandlers(GraphClientOptions graphClientOptions = null)
{
var handlers = KiotaClientFactory.CreateDefaultHandlers();
handlers.Insert(0, new UriReplacementHandler<GraphUriReplacementHandlerOption>(new GraphUriReplacementHandlerOption()));
handlers.Add(new GraphTelemetryHandler(graphClientOptions));// add the telemetry handler last.

return handlers;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------

namespace Microsoft.Graph
{
using System;
using Microsoft.Kiota.Http.HttpClientLibrary.Middleware.Options;

/// <summary>
/// Replaces the reserved current-user path with the Microsoft Graph /me endpoint.
/// </summary>
public class GraphUriReplacementHandlerOption : IUriReplacementHandlerOption
{
private readonly bool enabled;

/// <summary>
/// Creates current-user URI replacement options.
/// </summary>
/// <param name="enabled">Whether current-user replacement is enabled.</param>
public GraphUriReplacementHandlerOption(bool enabled = true)
{
this.enabled = enabled;
}

/// <inheritdoc/>
public bool IsEnabled() => enabled;

/// <inheritdoc/>
public Uri Replace(Uri original)
{
if (!enabled || original == null || !original.IsAbsoluteUri)
{
return original;
}

var path = original.AbsolutePath;
var token = CoreConstants.ReplacementConstants.UsersEndpointWithReplaceToken;
var index = path.IndexOf(token, StringComparison.Ordinal);
while (index >= 0)
{
var end = index + token.Length;
if (end == path.Length || path[end] == '/')
{
return new UriBuilder(original)
{
Path = path.Substring(0, index) + CoreConstants.ReplacementConstants.MeEndpoint + path.Substring(end)

Check warning on line 47 in src/Microsoft.Graph.Core/Requests/Middleware/Options/GraphUriReplacementHandlerOption.cs

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Use span-based 'string.Concat' and 'AsSpan' instead of 'Substring'

See more on https://sonarcloud.io/project/issues?id=microsoftgraph_msgraph-sdk-dotnet-core&issues=AaHm9CZ7Y4qr0s_vYIED&open=AaHm9CZ7Y4qr0s_vYIED&pullRequest=1146
}.Uri;
}

index = path.IndexOf(token, end, StringComparison.Ordinal);
}

return original;
}
}
}
2 changes: 1 addition & 1 deletion src/Microsoft.Graph.Core/global.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"sdk": {
"version": "10.0.202",
"version": "10.0.404",
"rollForward": "major"
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,52 @@ public void BatchRequestContent_DefaultInitialize()
Assert.True(batchRequestContent.BatchRequestSteps.Count.Equals(0));
}

[Theory]
[InlineData(false, false)]
[InlineData(true, false)]
[InlineData(false, true)]
public async Task BatchRequestContent_ReplacesCurrentUserBeforeSerializationAsync(bool useRequestInformation, bool usePrebuiltStep)
{
const string url = "https://graph.microsoft.com/v1.0/users/TokenToReplace/messages?$select=subject";
using var content = new BatchRequestContent(client);
if (useRequestInformation)
{
var requestInfo = new RequestInformation
{
HttpMethod = Method.POST,
URI = new Uri(url)
};
requestInfo.Headers.Add("ConsistencyLevel", "eventual");
requestInfo.SetStreamContent(new MemoryStream(Encoding.UTF8.GetBytes("{\"subject\":\"test\"}")), "application/json");
await content.AddBatchRequestStepAsync(requestInfo, "current-user");
}
else
{
var request = new HttpRequestMessage(HttpMethod.Post, url)
{
Content = new StringContent("{\"subject\":\"test\"}", Encoding.UTF8, "application/json")
};
request.Headers.Add("ConsistencyLevel", "eventual");
if (usePrebuiltStep)
{
content.AddBatchRequestStep(new BatchRequestStep("current-user", request));
}
else
{
content.AddBatchRequestStep(request);
}
}

using var stream = await content.GetBatchRequestContentAsync();
using var document = await JsonDocument.ParseAsync(stream);
var step = document.RootElement.GetProperty("requests")[0];
Assert.Equal("/me/messages?$select=subject", step.GetProperty("url").GetString());
Assert.Equal("POST", step.GetProperty("method").GetString());
Assert.Equal("test", step.GetProperty("body").GetProperty("subject").GetString());
Assert.Equal("eventual", step.GetProperty("headers").GetProperty("ConsistencyLevel").GetString());
Assert.Equal("https://graph.microsoft.com/v1.0/me/messages?$select=subject", content.BatchRequestSteps.Values.Single().Request.RequestUri.AbsoluteUri);
}

[Fact]
public void BatchRequestContent_InitializeWithSerializer()
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,8 @@ public void Should_CreatePipeline_Without_CompressionHandler()
[Fact]
public void Should_CreatePipeline_Without_HttpMessageHandlerInput()
{
using UriReplacementHandler<UriReplacementHandlerOption> uriReplacementHandler = (UriReplacementHandler<UriReplacementHandlerOption>)GraphClientFactory.CreatePipeline(handlers, new MockRedirectHandler());
using UriReplacementHandler<GraphUriReplacementHandlerOption> graphUriReplacementHandler = (UriReplacementHandler<GraphUriReplacementHandlerOption>)GraphClientFactory.CreatePipeline(handlers, new MockRedirectHandler());
using UriReplacementHandler<UriReplacementHandlerOption> uriReplacementHandler = (UriReplacementHandler<UriReplacementHandlerOption>)graphUriReplacementHandler.InnerHandler;
using RetryHandler retryHandler = (RetryHandler)uriReplacementHandler.InnerHandler;
using RedirectHandler redirectHandler = (RedirectHandler)retryHandler.InnerHandler;
using ParametersNameDecodingHandler odataQueryHandler = (ParametersNameDecodingHandler)redirectHandler.InnerHandler;
Expand Down Expand Up @@ -101,7 +102,8 @@ public void Should_CreatePipeline_Without_HttpMessageHandlerInput()
[Fact]
public void CreatePipelineWithHttpMessageHandlerInput()
{
using UriReplacementHandler<UriReplacementHandlerOption> uriReplacementHandler = (UriReplacementHandler<UriReplacementHandlerOption>)GraphClientFactory.CreatePipeline(handlers, new MockRedirectHandler());
using UriReplacementHandler<GraphUriReplacementHandlerOption> graphUriReplacementHandler = (UriReplacementHandler<GraphUriReplacementHandlerOption>)GraphClientFactory.CreatePipeline(handlers, new MockRedirectHandler());
using UriReplacementHandler<UriReplacementHandlerOption> uriReplacementHandler = (UriReplacementHandler<UriReplacementHandlerOption>)graphUriReplacementHandler.InnerHandler;
using RetryHandler retryHandler = (RetryHandler)uriReplacementHandler.InnerHandler;
using RedirectHandler redirectHandler = (RedirectHandler)retryHandler.InnerHandler;
using ParametersNameDecodingHandler odataQueryHandler = (ParametersNameDecodingHandler)redirectHandler.InnerHandler;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------

namespace Microsoft.Graph.DotnetCore.Core.Test.Requests.Middleware
{
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Kiota.Abstractions;
using Microsoft.Kiota.Abstractions.Authentication;
using Microsoft.Kiota.Http.HttpClientLibrary.Middleware.Options;
using Xunit;

public class GraphUriReplacementHandlerTests
{
[Theory]
[InlineData("https://graph.microsoft.com/v1.0/users/TokenToReplace", "https://graph.microsoft.com/v1.0/me")]
[InlineData("https://graph.microsoft.us/beta/users/TokenToReplace/messages?$filter=subject%20eq%20%27a%2Fb%27", "https://graph.microsoft.us/beta/me/messages?$filter=subject%20eq%20%27a%2Fb%27")]
[InlineData("https://localhost:8443/custom/v1.0/users/TokenToReplace/photo/$value#fragment", "https://localhost:8443/custom/v1.0/me/photo/$value#fragment")]
[InlineData("https://graph.microsoft.com/v1.0/users/TokenToReplace/messages/a%2Fb?value=%252F", "https://graph.microsoft.com/v1.0/me/messages/a%2Fb?value=%252F")]
[InlineData("https://graph.microsoft.com/v1.0/users/actual-id/messages", "https://graph.microsoft.com/v1.0/users/actual-id/messages")]
[InlineData("https://graph.microsoft.com/v1.0/users/TokenToReplaceExtra", "https://graph.microsoft.com/v1.0/users/TokenToReplaceExtra")]
[InlineData("https://graph.microsoft.com/v1.0/me?next=/users/TokenToReplace", "https://graph.microsoft.com/v1.0/me?next=/users/TokenToReplace")]
[InlineData("https://graph.microsoft.com/v1.0/users/tokentoreplace", "https://graph.microsoft.com/v1.0/users/tokentoreplace")]
public async Task DefaultPipelineReplacesOnlyReservedUserPathAsync(string url, string expected)
{
using var httpClient = GraphClientFactory.Create(finalHandler: new FakeSuccessHandler());
using var response = await httpClient.GetAsync(url);

Assert.Equal(expected, response.RequestMessage.RequestUri.AbsoluteUri);
}

[Fact]
public async Task RequestOptionCanDisableReplacementAsync()
{
using var httpClient = GraphClientFactory.Create(finalHandler: new FakeSuccessHandler());
using var adapter = new BaseGraphRequestAdapter(new AnonymousAuthenticationProvider(), httpClient: httpClient);
var requestInfo = new RequestInformation
{
HttpMethod = Method.GET,
URI = new Uri("https://graph.microsoft.com/v1.0/users/TokenToReplace")
};
requestInfo.AddRequestOptions(new[] { new GraphUriReplacementHandlerOption(false) });
using var request = await adapter.ConvertToNativeRequestAsync<HttpRequestMessage>(requestInfo);
using var response = await httpClient.SendAsync(request);

Assert.Equal(requestInfo.URI, response.RequestMessage.RequestUri);
}

[Fact]
public async Task KiotaRequestOptionStillAppliesAsync()
{
using var httpClient = GraphClientFactory.Create(finalHandler: new FakeSuccessHandler());
using var adapter = new BaseGraphRequestAdapter(new AnonymousAuthenticationProvider(), httpClient: httpClient);
var requestInfo = new RequestInformation
{
HttpMethod = Method.GET,
URI = new Uri("https://graph.microsoft.com/v1.0/users/TokenToReplace/messages")
};
requestInfo.AddRequestOptions(new[]
{
new UriReplacementHandlerOption(true, new[] { new KeyValuePair<string, string>("/messages", "/events") })
});
using var request = await adapter.ConvertToNativeRequestAsync<HttpRequestMessage>(requestInfo);
using var response = await httpClient.SendAsync(request);

Assert.Equal("https://graph.microsoft.com/v1.0/me/events", response.RequestMessage.RequestUri.AbsoluteUri);
}

[Fact]
public async Task ExplicitCustomPipelineIsNotReplacedAsync()
{
using var httpClient = GraphClientFactory.Create(Array.Empty<DelegatingHandler>(), finalHandler: new FakeSuccessHandler());
const string url = "https://graph.microsoft.com/v1.0/users/TokenToReplace";
using var response = await httpClient.GetAsync(url, CancellationToken.None);

Assert.Equal(url, response.RequestMessage.RequestUri.AbsoluteUri);
}
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"sdk": {
"version": "10.0.202",
"version": "10.0.404",
"rollForward": "major"
}
}
Loading