Skip to content

Commit

Permalink
Merge pull request #55 from akunzai/floating-dependencies
Browse files Browse the repository at this point in the history
Floating dependencies
  • Loading branch information
akunzai committed Jun 11, 2021
2 parents 548f986 + 80e41e2 commit 9e5c603
Show file tree
Hide file tree
Showing 11 changed files with 115 additions and 40 deletions.
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,11 @@

All notable changes to this project will be documented in this file.

## 2.3.0 (2021-06-11)

- Floating latest dependencies for .NET Core 3.1 and .NET 5
- Fixed [ConfigurePrimaryHttpMessageHandler<T>() not loading handler](https://github.com/dotnet/extensions/issues/851)

## 2.2.0 (2021-05-26)

- Update dependencies [#51](https://github.com/akunzai/GSS.Authorization.OAuth/pull/51)
Expand Down
2 changes: 1 addition & 1 deletion src/Directory.Build.props
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
<PublishRepositoryUrl>true</PublishRepositoryUrl>
<EmbedUntrackedSources>true</EmbedUntrackedSources>
<Nullable>enable</Nullable>
<Version>2.2.0</Version>
<Version>2.3.0</Version>
</PropertyGroup>

<PropertyGroup Condition="'$(Configuration)' == 'Release' ">
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<TargetFrameworks>netstandard2.0;netcoreapp3.1;net5.0</TargetFrameworks>
<Description>OAuth 1.0 authorized HttpClient, friendly with HttpClientFactory</Description>
<PackageTags>OAuth;HttpClient;HttpHandler</PackageTags>
<RootNamespace>GSS.Authorization.OAuth</RootNamespace>
Expand All @@ -12,8 +12,19 @@
</ItemGroup>

<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Http" Version="2.2.0" />
<PackageReference Include="System.Threading.Tasks.Extensions" Version="4.5.4" />
</ItemGroup>

<ItemGroup Condition=" '$(TargetFramework)' == 'netstandard2.0' ">
<PackageReference Include="Microsoft.Extensions.Http" Version="2.2.0" />
</ItemGroup>

<ItemGroup Condition=" '$(TargetFramework)' == 'netcoreapp3.1' ">
<PackageReference Include="Microsoft.Extensions.Http" Version="3.1.*" />
</ItemGroup>

<ItemGroup Condition=" '$(TargetFramework)' == 'net5.0' ">
<PackageReference Include="Microsoft.Extensions.Http" Version="5.0.*" />
</ItemGroup>

</Project>
14 changes: 7 additions & 7 deletions src/GSS.Authorization.OAuth.HttpClient/OAuthHttpHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ public OAuthHttpHandler(IOptions<OAuthHttpHandlerOptions> options, IRequestSigne
if (request == null)
throw new ArgumentNullException(nameof(request));
var tokenCredentials = await _options.TokenCredentialProvider(request).ConfigureAwait(false);
var queryString = QueryHelpers.ParseQuery(request.RequestUri.Query);
var queryString = QueryHelpers.ParseQuery(request.RequestUri?.Query);
if (_options.SignedAsBody && request.Content != null && string.Equals(request.Content.Headers?.ContentType?.MediaType,
ApplicationFormUrlEncoded, StringComparison.OrdinalIgnoreCase))
{
Expand All @@ -43,15 +43,15 @@ public OAuthHttpHandler(IOptions<OAuthHttpHandlerOptions> options, IRequestSigne
}
}

var parameters = _signer.AppendAuthorizationParameters(request.Method, request.RequestUri, _options,
var parameters = _signer.AppendAuthorizationParameters(request.Method, request.RequestUri!, _options,
formData, tokenCredentials);
var values = new List<KeyValuePair<string, string>>();
var values = new List<KeyValuePair<string?, string?>>();
foreach (var parameter in parameters)
{
if (!queryString.ContainsKey(parameter.Key))
{
values.AddRange(parameter.Value.Select(value =>
new KeyValuePair<string, string>(parameter.Key, value)));
new KeyValuePair<string?, string?>(parameter.Key, value)));
}
}

Expand All @@ -60,7 +60,7 @@ public OAuthHttpHandler(IOptions<OAuthHttpHandlerOptions> options, IRequestSigne
}
else if (_options.SignedAsQuery)
{
var parameters = _signer.AppendAuthorizationParameters(request.Method, request.RequestUri, _options,
var parameters = _signer.AppendAuthorizationParameters(request.Method, request.RequestUri!, _options,
queryString, tokenCredentials);
var values = new List<string>();
foreach (var parameter in parameters)
Expand All @@ -71,13 +71,13 @@ public OAuthHttpHandler(IOptions<OAuthHttpHandlerOptions> options, IRequestSigne
}
}

request.RequestUri = new UriBuilder(request.RequestUri) { Query = "?" + string.Join("&", values) }.Uri;
request.RequestUri = new UriBuilder(request.RequestUri!) { Query = "?" + string.Join("&", values) }.Uri;
}
else
{
request.Headers.Authorization = _signer.GetAuthorizationHeader(
request.Method,
request.RequestUri,
request.RequestUri!,
_options,
queryString,
tokenCredentials);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<TargetFrameworks>netstandard2.0;netcoreapp3.1;net5.0</TargetFrameworks>
<Description>OAuth 2.0 authorized HttpClient, friendly with HttpClientFactory</Description>
<PackageTags>OAuth;OAuth2;HttpClient;HttpHandler</PackageTags>
<RootNamespace>GSS.Authorization.OAuth2</RootNamespace>
Expand All @@ -12,9 +12,22 @@
</ItemGroup>

<ItemGroup>
<PackageReference Include="System.Threading.Tasks.Extensions" Version="4.5.4" />
</ItemGroup>

<ItemGroup Condition=" '$(TargetFramework)' == 'netstandard2.0' ">
<PackageReference Include="Microsoft.Extensions.Caching.Memory" Version="2.2.0" />
<PackageReference Include="Microsoft.Extensions.Http" Version="2.2.0" />
<PackageReference Include="System.Threading.Tasks.Extensions" Version="4.5.4" />
</ItemGroup>

<ItemGroup Condition=" '$(TargetFramework)' == 'netcoreapp3.1' ">
<PackageReference Include="Microsoft.Extensions.Caching.Memory" Version="3.1.*" />
<PackageReference Include="Microsoft.Extensions.Http" Version="3.1.*" />
</ItemGroup>

<ItemGroup Condition=" '$(TargetFramework)' == 'net5.0' ">
<PackageReference Include="Microsoft.Extensions.Caching.Memory" Version="5.0.*" />
<PackageReference Include="Microsoft.Extensions.Http" Version="5.0.*" />
</ItemGroup>

</Project>
6 changes: 2 additions & 4 deletions src/GSS.Authorization.OAuth2.HttpClient/OAuth2HttpHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -53,8 +53,6 @@ public OAuth2HttpHandler(IAuthorizer authorizer, IMemoryCache memoryCache)
try
{
var accessToken = await _authorizer.GetAccessTokenAsync(cancellationToken).ConfigureAwait(false);
if (accessToken == null)
return AccessToken.Empty;
if (accessToken.ExpiresInSeconds > 0)
{
_memoryCache.Set(_cacheKey, accessToken, accessToken.ExpiresIn);
Expand All @@ -73,10 +71,10 @@ public OAuth2HttpHandler(IAuthorizer authorizer, IMemoryCache memoryCache)

private static void TrySetAuthorizationHeaderToRequest(AccessToken accessToken, HttpRequestMessage request)
{
if (!string.IsNullOrWhiteSpace(accessToken?.Token))
if (!string.IsNullOrWhiteSpace(accessToken.Token))
{
request.Headers.Authorization =
new AuthenticationHeaderValue(AuthorizerDefaults.Bearer, accessToken?.Token);
new AuthenticationHeaderValue(AuthorizerDefaults.Bearer, accessToken.Token);
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@

<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Hosting" Version="5.0.0" />
<PackageReference Include="Microsoft.Extensions.Http" Version="5.0.0" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Globalization;
using System.Linq;
using System.Net;
Expand Down Expand Up @@ -43,19 +42,19 @@ public async Task HttpClient_AccessProtectedResourceWithAuthorizationHeader_Shou
{
// Arrange
var services = new ServiceCollection()
.AddOAuthHttpClient<OAuthHttpClient>((_, options) =>
.AddOAuthHttpClient<OAuthHttpClient>((_, handlerOptions) =>
{
options.ClientCredentials = new OAuthCredential(
handlerOptions.ClientCredentials = new OAuthCredential(
_configuration["OAuth:ClientId"],
_configuration["OAuth:ClientSecret"]);
options.TokenCredentials = _tokenCredentials;
handlerOptions.TokenCredentials = _tokenCredentials;
if (_mockHttp != null)
{
var timestamp = DateTimeOffset.UtcNow.ToUnixTimeSeconds()
.ToString(CultureInfo.InvariantCulture);
var nonce = generateNonce();
options.TimestampProvider = () => timestamp;
options.NonceProvider = () => nonce;
handlerOptions.TimestampProvider = () => timestamp;
handlerOptions.NonceProvider = () => nonce;
}
})
.ConfigurePrimaryHttpMessageHandler(_ => (HttpMessageHandler)_mockHttp ?? new HttpClientHandler())
Expand Down Expand Up @@ -83,20 +82,20 @@ public async Task HttpClient_AccessProtectedResourceWithQueryString_ShouldAuthor
{
// Arrange
var services = new ServiceCollection()
.AddOAuthHttpClient<OAuthHttpClient>((_, options) =>
.AddOAuthHttpClient<OAuthHttpClient>((_, handlerOptions) =>
{
options.ClientCredentials = new OAuthCredential(
handlerOptions.ClientCredentials = new OAuthCredential(
_configuration["OAuth:ClientId"],
_configuration["OAuth:ClientSecret"]);
options.TokenCredentials = _tokenCredentials;
options.SignedAsQuery = true;
handlerOptions.TokenCredentials = _tokenCredentials;
handlerOptions.SignedAsQuery = true;
if (_mockHttp != null)
{
var timestamp = DateTimeOffset.UtcNow.ToUnixTimeSeconds()
.ToString(CultureInfo.InvariantCulture);
var nonce = generateNonce();
options.TimestampProvider = () => timestamp;
options.NonceProvider = () => nonce;
handlerOptions.TimestampProvider = () => timestamp;
handlerOptions.NonceProvider = () => nonce;
}
})
.ConfigurePrimaryHttpMessageHandler(_ => (HttpMessageHandler)_mockHttp ?? new HttpClientHandler())
Expand Down Expand Up @@ -136,20 +135,20 @@ public async Task HttpClient_AccessProtectedResourceWithFormBody_ShouldAuthorize
{
// Arrange
var services = new ServiceCollection()
.AddOAuthHttpClient<OAuthHttpClient>((_, options) =>
.AddOAuthHttpClient<OAuthHttpClient>((_, handlerOptions) =>
{
options.ClientCredentials = new OAuthCredential(
handlerOptions.ClientCredentials = new OAuthCredential(
_configuration["OAuth:ClientId"],
_configuration["OAuth:ClientSecret"]);
options.TokenCredentials = _tokenCredentials;
options.SignedAsBody = true;
handlerOptions.TokenCredentials = _tokenCredentials;
handlerOptions.SignedAsBody = true;
if (_mockHttp != null)
{
var timestamp = DateTimeOffset.UtcNow.ToUnixTimeSeconds()
.ToString(CultureInfo.InvariantCulture);
var nonce = generateNonce();
options.TimestampProvider = () => timestamp;
options.NonceProvider = () => nonce;
handlerOptions.TimestampProvider = () => timestamp;
handlerOptions.NonceProvider = () => nonce;
}
})
.ConfigurePrimaryHttpMessageHandler(_ => (HttpMessageHandler)_mockHttp ?? new HttpClientHandler())
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
using System;
using System.Net.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Http;
using Microsoft.Extensions.Options;
using RichardSzalay.MockHttp;
using Xunit;

namespace GSS.Authorization.OAuth.HttpClient.Tests
Expand Down Expand Up @@ -134,6 +136,29 @@ public void AddOAuthHttpClient_WithValidConfigureOptions_ShouldAddInServiceProvi
// Assert
Assert.NotNull(client);
}

[Fact]
public void AddOAuthHttpClient_WithGenericConfigurePrimaryHttpMessageHandler_ShouldAddInHttpMessageHandlerBuilderActions()
{
// Arrange
var mockHttp = new MockHttpMessageHandler();
var collection = new ServiceCollection();
var builder = collection
.AddSingleton(mockHttp)
.AddOAuthHttpClient<OAuthHttpClient>((_, options) =>
{
options.ClientCredentials = new OAuthCredential("foo", "bar");
options.TokenCredentials = new OAuthCredential("foo", "bar");
}).ConfigurePrimaryHttpMessageHandler<MockHttpMessageHandler>();
var services = builder.Services.BuildServiceProvider();

// Act
var optionsMonitor = services.GetRequiredService<IOptionsMonitor<HttpClientFactoryOptions>>();

// Assert
var httpClientFactoryOptions = optionsMonitor.Get(builder.Name);
Assert.Contains(httpClientFactoryOptions.HttpMessageHandlerBuilderActions, x => x.Target?.ToString()?.Contains("MockHttpMessageHandler") == true);
}

[Fact]
public void AddNamedOAuthHttpClient_WithValidConfigureOptions_ShouldAddInHttpClientFactory()
Expand Down Expand Up @@ -243,7 +268,7 @@ public void AddNamedOAuthHttpClient_WithCustomConfigureOptions_ShouldAddInServic
}

[Fact]
public void AddTypedOAuthHttpClients_WithDifferenctSigners_ShouldAddInServiceProvider()
public void AddTypedOAuthHttpClients_WithDifferentSigners_ShouldAddInServiceProvider()
{
// Arrange
var collection = new ServiceCollection();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@

<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Hosting" Version="5.0.0" />
<PackageReference Include="Microsoft.Extensions.Http" Version="5.0.0" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@
using System.Net;
using System.Net.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Http;
using Microsoft.Extensions.Options;
using RichardSzalay.MockHttp;
using Xunit;

namespace GSS.Authorization.OAuth2.HttpClient.Tests
Expand Down Expand Up @@ -103,9 +105,33 @@ public void AddOAuth2HttpClient_WithValidConfigureOptions_ShouldNotThrows()
// Assert
Assert.NotNull(authorizerOptions);
}

[Fact]
public void AddOAuth2HttpClient_WithGenericConfigurePrimaryHttpMessageHandler_ShouldAddInHttpMessageHandlerBuilderActions()
{
// Arrange
var mockHttp = new MockHttpMessageHandler();
var collection = new ServiceCollection();
var builder = collection
.AddSingleton(mockHttp)
.AddOAuth2HttpClient<OAuth2HttpClient, ClientCredentialsAuthorizer>((_, options) =>
{
options.AccessTokenEndpoint = new Uri("https://example.com");
options.ClientId = "foo";
options.ClientSecret = "bar";
}).ConfigurePrimaryHttpMessageHandler<MockHttpMessageHandler>();
var services = builder.Services.BuildServiceProvider();

// Act
var optionsMonitor = services.GetRequiredService<IOptionsMonitor<HttpClientFactoryOptions>>();

// Assert
var httpClientFactoryOptions = optionsMonitor.Get(builder.Name);
Assert.Contains(httpClientFactoryOptions.HttpMessageHandlerBuilderActions, x => x.Target?.ToString()?.Contains("MockHttpMessageHandler") == true);
}

[Fact]
public void AddOAuth2HttpClient_WithoutCredentials_ShouldThorwsForResourceOwnerCredentialsAuthorizer()
public void AddOAuth2HttpClient_WithoutCredentials_ShouldThrowsForResourceOwnerCredentialsAuthorizer()
{
// Arrange
var collection = new ServiceCollection();
Expand All @@ -124,7 +150,7 @@ public void AddOAuth2HttpClient_WithoutCredentials_ShouldThorwsForResourceOwnerC
}

[Fact]
public void AddOAuth2HttpClient_WithCredentials_ShouldNotThorwsForResourceOwnerCredentialsAuthorizer()
public void AddOAuth2HttpClient_WithCredentials_ShouldNotThrowsForResourceOwnerCredentialsAuthorizer()
{
// Arrange
var collection = new ServiceCollection();
Expand Down Expand Up @@ -214,7 +240,7 @@ public void AddTypedOAuth2HttpClient_WithClientCredentialsAuthorizer_ShouldAddIn
}

[Fact]
public void AddOAuth2HttpClients_WithDifferenctAuthorizers_ShouldAddAuthroizersInServiceProvider()
public void AddOAuth2HttpClients_WithDifferentAuthorizers_ShouldAddAuthorizersInServiceProvider()
{
// Arrange
var collection = new ServiceCollection();
Expand Down

0 comments on commit 9e5c603

Please sign in to comment.