@@ -34,19 +34,21 @@ using Microsoft.AspNetCore.Authentication;
3434
3535public class AuthenticationProcessor (IHttpContextAccessor httpContextAccessor )
3636{
37- public string ? GetAccessToken ()
37+ public async Task < string ?> GetAccessToken ()
3838 {
39+ if (httpContextAccessor .HttpContext is null )
40+ {
41+ throw new Exception (" HttpContext not available" );
42+ }
43+
3944 // 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" );
4347
4448 // Approach 2: Authenticate the user and call 'GetTokenValue'
4549 /*
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");
5052 */
5153
5254 return accessToken ;
@@ -123,7 +125,7 @@ public class TokenHandler(IHttpContextAccessor httpContextAccessor) :
123125 {
124126 if (httpContextAccessor .HttpContext is null )
125127 {
126- throw new Exception (" HttpContext.Current not available. " );
128+ throw new Exception (" HttpContext not available" );
127129 }
128130
129131 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
186188
187189``` csharp
188190using 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}" );
190192using var response = await client .SendAsync (request );
191193```
192194
193195Example:
194196
195197``` csharp
196198using var request = new HttpRequestMessage (HttpMethod .Get , " /weather-forecast" );
197- using var client = ClientFactory .CreateClient (" ExternalApi" );
199+ var client = ClientFactory .CreateClient (" ExternalApi" );
198200using var response = await client .SendAsync (request );
199201```
200202
@@ -879,7 +881,7 @@ public class AuthenticationStateHandler(
879881
880882 if (authStateProvider is null )
881883 {
882- throw new Exception (" AuthenticationStateProvider not available. " );
884+ throw new Exception (" AuthenticationStateProvider not available" );
883885 }
884886
885887 var authState = await authStateProvider .GetAuthenticationStateAsync ();
0 commit comments