@@ -34,19 +34,21 @@ using Microsoft.AspNetCore.Authentication;
34
34
35
35
public class AuthenticationProcessor (IHttpContextAccessor httpContextAccessor )
36
36
{
37
- public string ? GetAccessToken ()
37
+ public async Task < string ?> GetAccessToken ()
38
38
{
39
+ if (httpContextAccessor .HttpContext is null )
40
+ {
41
+ throw new Exception (" HttpContext not available" );
42
+ }
43
+
39
44
// Approach 1: Call 'GetTokenAsync'
40
- var accessToken = httpContextAccessor .HttpContext ?
41
- .GetTokenAsync (" access_token" ).Result ??
42
- throw new Exception (" No access token" );
45
+ var accessToken = await httpContextAccessor .HttpContext
46
+ .GetTokenAsync (" access_token" );
43
47
44
48
// Approach 2: Authenticate the user and call 'GetTokenValue'
45
49
/*
46
- var authResult = httpContextAccessor.HttpContext?
47
- .AuthenticateAsync().Result;
48
- var accessToken = authResult?.Properties?
49
- .GetTokenValue("access_token");
50
+ var authResult = await httpContextAccessor.HttpContext.AuthenticateAsync();
51
+ var accessToken = authResult?.Properties?.GetTokenValue("access_token");
50
52
*/
51
53
52
54
return accessToken ;
@@ -123,7 +125,7 @@ public class TokenHandler(IHttpContextAccessor httpContextAccessor) :
123
125
{
124
126
if (httpContextAccessor .HttpContext is null )
125
127
{
126
- throw new Exception (" HttpContext.Current not available. " );
128
+ throw new Exception (" HttpContext not available" );
127
129
}
128
130
129
131
var accessToken = await httpContextAccessor .HttpContext .GetTokenAsync (" access_token" );
@@ -186,15 +188,15 @@ At this point, an <xref:System.Net.Http.HttpClient> created by a component can m
186
188
187
189
``` csharp
188
190
using var request = new HttpRequestMessage (HttpMethod .Get , " {REQUEST URI}" );
189
- using var client = ClientFactory .CreateClient (" {HTTP CLIENT NAME}" );
191
+ var client = ClientFactory .CreateClient (" {HTTP CLIENT NAME}" );
190
192
using var response = await client .SendAsync (request );
191
193
```
192
194
193
195
Example:
194
196
195
197
``` csharp
196
198
using var request = new HttpRequestMessage (HttpMethod .Get , " /weather-forecast" );
197
- using var client = ClientFactory .CreateClient (" ExternalApi" );
199
+ var client = ClientFactory .CreateClient (" ExternalApi" );
198
200
using var response = await client .SendAsync (request );
199
201
```
200
202
@@ -879,7 +881,7 @@ public class AuthenticationStateHandler(
879
881
880
882
if (authStateProvider is null )
881
883
{
882
- throw new Exception (" AuthenticationStateProvider not available. " );
884
+ throw new Exception (" AuthenticationStateProvider not available" );
883
885
}
884
886
885
887
var authState = await authStateProvider .GetAuthenticationStateAsync ();
0 commit comments