Skip to content

Commit eb65bfb

Browse files
committed
Update the samples to use keyed services to create HttpClient instances
1 parent 8673009 commit eb65bfb

File tree

6 files changed

+37
-39
lines changed

6 files changed

+37
-39
lines changed

Directory.Build.targets

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,7 @@
117117
<DefineConstants>$(DefineConstants);SUPPORTS_CERTIFICATE_LOADER</DefineConstants>
118118
<DefineConstants>$(DefineConstants);SUPPORTS_JSON_ELEMENT_DEEP_EQUALS</DefineConstants>
119119
<DefineConstants>$(DefineConstants);SUPPORTS_JSON_ELEMENT_PROPERTY_COUNT</DefineConstants>
120+
<DefineConstants>$(DefineConstants);SUPPORTS_KEYED_HTTP_CLIENT_RESOLUTION</DefineConstants>
120121
<DefineConstants>$(DefineConstants);SUPPORTS_TYPE_DESCRIPTOR_TYPE_REGISTRATION</DefineConstants>
121122
<DefineConstants>$(DefineConstants);SUPPORTS_X509_CHAIN_POLICY_CLONING</DefineConstants>
122123
<DefineConstants>$(DefineConstants);SUPPORTS_X509_CHAIN_POLICY_VERIFICATION_TIME_MODE</DefineConstants>

sandbox/OpenIddict.Sandbox.AspNet.Client/Controllers/HomeController.cs

Lines changed: 7 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
using System.Threading.Tasks;
77
using System.Web;
88
using System.Web.Mvc;
9+
using Microsoft.Extensions.DependencyInjection;
910
using Microsoft.Owin.Security;
1011
using Microsoft.Owin.Security.Cookies;
1112
using OpenIddict.Client;
@@ -15,23 +16,12 @@
1516

1617
namespace OpenIddict.Sandbox.AspNet.Client.Controllers;
1718

18-
public class HomeController : Controller
19+
public class HomeController([FromKeyedServices("ApiClient")] HttpClient client, OpenIddictClientService service) : Controller
1920
{
20-
private readonly IHttpClientFactory _httpClientFactory;
21-
private readonly OpenIddictClientService _service;
22-
23-
public HomeController(
24-
IHttpClientFactory httpClientFactory,
25-
OpenIddictClientService service)
26-
{
27-
_httpClientFactory = httpClientFactory;
28-
_service = service;
29-
}
30-
3121
[HttpGet, Route("~/")]
3222
public async Task<ActionResult> Index(CancellationToken cancellationToken) => View(new IndexViewModel
3323
{
34-
Providers = from registration in await _service.GetClientRegistrationsAsync(cancellationToken)
24+
Providers = from registration in await service.GetClientRegistrationsAsync(cancellationToken)
3525
where !string.IsNullOrEmpty(registration.ProviderName)
3626
where !string.IsNullOrEmpty(registration.ProviderDisplayName)
3727
select registration
@@ -45,9 +35,7 @@ public async Task<ActionResult> GetMessage(CancellationToken cancellationToken)
4535
var result = await context.Authentication.AuthenticateAsync(CookieAuthenticationDefaults.AuthenticationType);
4636
var token = result.Properties.Dictionary[Tokens.BackchannelAccessToken];
4737

48-
using var client = _httpClientFactory.CreateClient();
49-
50-
using var request = new HttpRequestMessage(HttpMethod.Get, "https://localhost:44349/api/message");
38+
using var request = new HttpRequestMessage(HttpMethod.Get, "api/message");
5139
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
5240

5341
using var response = await client.SendAsync(request, cancellationToken);
@@ -56,7 +44,7 @@ public async Task<ActionResult> GetMessage(CancellationToken cancellationToken)
5644
return View("Index", new IndexViewModel
5745
{
5846
Message = await response.Content.ReadAsStringAsync(),
59-
Providers = from registration in await _service.GetClientRegistrationsAsync(cancellationToken)
47+
Providers = from registration in await service.GetClientRegistrationsAsync(cancellationToken)
6048
where !string.IsNullOrEmpty(registration.ProviderName)
6149
where !string.IsNullOrEmpty(registration.ProviderDisplayName)
6250
select registration
@@ -75,7 +63,7 @@ public async Task<ActionResult> RefreshToken(CancellationToken cancellationToken
7563
return new HttpStatusCodeResult(400);
7664
}
7765

78-
var result = await _service.AuthenticateWithRefreshTokenAsync(new()
66+
var result = await service.AuthenticateWithRefreshTokenAsync(new()
7967
{
8068
CancellationToken = cancellationToken,
8169
RefreshToken = token,
@@ -99,7 +87,7 @@ public async Task<ActionResult> RefreshToken(CancellationToken cancellationToken
9987
return View("Index", new IndexViewModel
10088
{
10189
Message = result.AccessToken,
102-
Providers = from registration in await _service.GetClientRegistrationsAsync(cancellationToken)
90+
Providers = from registration in await service.GetClientRegistrationsAsync(cancellationToken)
10391
where !string.IsNullOrEmpty(registration.ProviderName)
10492
where !string.IsNullOrEmpty(registration.ProviderDisplayName)
10593
select registration

sandbox/OpenIddict.Sandbox.AspNet.Client/Startup.cs

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
using System;
2+
using System.Net.Http;
23
using System.Threading.Tasks;
34
using System.Web.Mvc;
45
using Autofac;
@@ -101,6 +102,16 @@ public void Configuration(IAppBuilder app)
101102
});
102103
});
103104

105+
// Register a named HTTP client that will be used to call the demo resource API.
106+
services.AddHttpClient("ApiClient")
107+
.ConfigureHttpClient(static client => client.BaseAddress = new Uri("https://localhost:44349/"));
108+
109+
services.AddKeyedScoped("ApiClient", static (provider, name) =>
110+
{
111+
var factory = provider.GetRequiredService<IHttpClientFactory>();
112+
return factory.CreateClient((string) name!);
113+
});
114+
104115
// Create a new Autofac container and import the OpenIddict services.
105116
var builder = new ContainerBuilder();
106117
builder.Populate(services);

sandbox/OpenIddict.Sandbox.AspNetCore.Client/Controllers/HomeController.cs

Lines changed: 5 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -10,23 +10,12 @@
1010

1111
namespace OpenIddict.Sandbox.AspNetCore.Client.Controllers;
1212

13-
public class HomeController : Controller
13+
public class HomeController([FromKeyedServices("ApiClient")] HttpClient client, OpenIddictClientService service) : Controller
1414
{
15-
private readonly IHttpClientFactory _httpClientFactory;
16-
private readonly OpenIddictClientService _service;
17-
18-
public HomeController(
19-
IHttpClientFactory httpClientFactory,
20-
OpenIddictClientService service)
21-
{
22-
_httpClientFactory = httpClientFactory;
23-
_service = service;
24-
}
25-
2615
[HttpGet("~/")]
2716
public async Task<ActionResult> Index(CancellationToken cancellationToken) => View(new IndexViewModel
2817
{
29-
Providers = from registration in await _service.GetClientRegistrationsAsync(cancellationToken)
18+
Providers = from registration in await service.GetClientRegistrationsAsync(cancellationToken)
3019
where !string.IsNullOrEmpty(registration.ProviderName)
3120
where !string.IsNullOrEmpty(registration.ProviderDisplayName)
3221
select registration
@@ -39,8 +28,6 @@ public async Task<ActionResult> GetMessage(CancellationToken cancellationToken)
3928
// authentication options shouldn't be used, a specific scheme can be specified here.
4029
var token = await HttpContext.GetTokenAsync(Tokens.BackchannelAccessToken);
4130

42-
using var client = _httpClientFactory.CreateClient("ApiClient");
43-
4431
using var request = new HttpRequestMessage(HttpMethod.Get, "api/message");
4532
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
4633

@@ -50,7 +37,7 @@ public async Task<ActionResult> GetMessage(CancellationToken cancellationToken)
5037
return View("Index", new IndexViewModel
5138
{
5239
Message = await response.Content.ReadAsStringAsync(),
53-
Providers = from registration in await _service.GetClientRegistrationsAsync(cancellationToken)
40+
Providers = from registration in await service.GetClientRegistrationsAsync(cancellationToken)
5441
where !string.IsNullOrEmpty(registration.ProviderName)
5542
where !string.IsNullOrEmpty(registration.ProviderDisplayName)
5643
select registration
@@ -74,7 +61,7 @@ public async Task<ActionResult> RefreshToken(CancellationToken cancellationToken
7461
return BadRequest();
7562
}
7663

77-
var result = await _service.AuthenticateWithRefreshTokenAsync(new()
64+
var result = await service.AuthenticateWithRefreshTokenAsync(new()
7865
{
7966
CancellationToken = cancellationToken,
8067
RefreshToken = token,
@@ -100,7 +87,7 @@ public async Task<ActionResult> RefreshToken(CancellationToken cancellationToken
10087
return View("Index", new IndexViewModel
10188
{
10289
Message = result.AccessToken,
103-
Providers = from registration in await _service.GetClientRegistrationsAsync(cancellationToken)
90+
Providers = from registration in await service.GetClientRegistrationsAsync(cancellationToken)
10491
where !string.IsNullOrEmpty(registration.ProviderName)
10592
where !string.IsNullOrEmpty(registration.ProviderDisplayName)
10693
select registration

sandbox/OpenIddict.Sandbox.AspNetCore.Client/Startup.cs

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
using System.Net.Http;
12
using System.Security.Cryptography;
23
using System.Security.Cryptography.X509Certificates;
34
using Microsoft.AspNetCore.Authentication.Cookies;
@@ -198,6 +199,9 @@ public void ConfigureServices(IServiceCollection services)
198199
// access tokens, the client certificate MUST be attached to outgoing HTTP requests
199200
// and the mTLS subdomain (for which TLS client authentication is enabled) MUST be used.
200201
services.AddHttpClient("ApiClient")
202+
#if SUPPORTS_KEYED_HTTP_CLIENT_RESOLUTION
203+
.AddAsKeyed()
204+
#endif
201205
#if SUPPORTS_PEM_ENCODED_KEY_IMPORT
202206
.ConfigureHttpClient(static client => client.BaseAddress = new Uri("https://mtls.dev.localhost:44395/"))
203207
.ConfigurePrimaryHttpMessageHandler(static () => new HttpClientHandler
@@ -209,6 +213,14 @@ public void ConfigureServices(IServiceCollection services)
209213
.ConfigureHttpClient(static client => client.BaseAddress = new Uri("https://localhost:44395/"));
210214
#endif
211215

216+
#if !SUPPORTS_KEYED_HTTP_CLIENT_RESOLUTION
217+
services.AddKeyedScoped("ApiClient", static (provider, name) =>
218+
{
219+
var factory = provider.GetRequiredService<IHttpClientFactory>();
220+
return factory.CreateClient((string) name!);
221+
});
222+
#endif
223+
212224
services.AddMvc();
213225
}
214226

sandbox/OpenIddict.Sandbox.AspNetCore.Server/Program.cs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -153,6 +153,7 @@ static async Task RegisterApplicationsAsync(IServiceProvider provider)
153153
{
154154
ApplicationType = ApplicationTypes.Web,
155155
ClientId = "mvc",
156+
ClientSecret = "emCimpdc9SeOaZzN5jzm4_eek-STF6VenfVlKO1_qt0",
156157
ClientType = ClientTypes.Confidential,
157158
ConsentType = ConsentTypes.Systematic,
158159
DisplayName = "MVC client application",
@@ -206,8 +207,6 @@ static async Task RegisterApplicationsAsync(IServiceProvider provider)
206207
"""))
207208
}
208209
},
209-
#else
210-
ClientSecret = "emCimpdc9SeOaZzN5jzm4_eek-STF6VenfVlKO1_qt0",
211210
#endif
212211
RedirectUris =
213212
{

0 commit comments

Comments
 (0)