Repository navigation
Description
Which Version of Microsoft Identity Web are you using ?
Microsoft Identity Web 0.1.2-preview
Where is the issue?
- Web App
- Sign-in users
- [ X] Sign-in users and call web APIs
- Web API
- Protected web APIs (Validating tokens)
- Protected web APIs (Validating scopes)
- Protected web APIs call downstream web APIs
- Token cache serialization
- [X ] In Memory caches
- Session caches
- Distributed caches
This is a new application that is a server-side Razor application calling a protected Web API. The application works as expected locally, but fails with a NullReferenceException when running as an Azure App Service. The failure occurs when trying to retrieve a token for a user (GetAccessTokenForUserAsync). The request to get a token for the user occurs in a lower-level HttpClient service when retrieving the token to add as an Authorization header. The HttpClient service is injected into the Blazor page (Inject). As a test, I've added code to the OnGet() method of the Blazor page (which runs on first access of a page from the site), and the same code works as expected both locally and in Azure (GetAccessTokenForUserAsync returns a valid token with no exception).
I have confirmed that the following values are correctly configured:
- TenantId
- ClientId
- ClientSecret
I have confirmed the application has been registered correctly in Azure AD with valid value(s) for:
- RedirectURIs
- Scopes
Given I can run the application locally with no exceptions, I don't think I have missing or invalid configuration. I also don't think this issue has anything to do with the Web API itself, this exception occurs simply trying to get a token from the cache and/or from MSAL prior to communication with the (protected) Web API.
Repro
Startup.cs
services
.AddSignIn(
openIdOptions => Configuration.Bind("AppAzureAd", openIdOptions),
identityOptions => Configuration.Bind("AppAzureAd", identityOptions)
)
.AddWebAppCallsProtectedWebApi(
Configuration.GetSection("Api:Scopes").Get<List<string>>(),
openIdOptions => Configuration.Bind("AppAzureAd", openIdOptions),
identityOptions =>
{
Configuration.Bind("AppAzureAd", identityOptions);
identityOptions.EnablePiiLogging = environment.IsDevelopment();
}
)
.AddInMemoryTokenCaches()
.AddTokenAcquisition();Blazor Page method that works as expected (no exceptions, token acquired) on first page request:
public async Task<IActionResult> OnGet()
{
if (!User.Identity.IsAuthenticated)
return Challenge();
try
{
var token = await tokenAcquisition.GetAccessTokenForUserAsync(apiOptions.Value.Scopes);
}
catch (MsalUiRequiredException ex)
{
//can't get a token from the token store, MUST assume a sign-out path as requests to API will NOT be authenticated
logger.LogError(ex, ex.Message);
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
return Challenge();
}
return Page();
}HttpClient setting the authorization header (GetAccessTokenForUserAsync works locally, but fails in Azure):
private async Task AddAuthorizationHeaderAsync(HttpRequestMessage request)
{
request.Headers.Authorization = new AuthenticationHeaderValue(JwtBearerDefaults.AuthenticationScheme, await AcquireTokenAsync());
}
private async Task<string> AcquireTokenAsync()
{
string token;
try
{
token = await tokenAcquisition.GetAccessTokenForUserAsync(apiOptions.Value.Scopes);
}
catch (MsalUiRequiredException ex)
{
//can't get a token from the token store, MUST assume a sign-out path as requests to API will NOT be authenticated
logger.LogError(ex, ex.Message);
throw;
}
return token;
}Expected behavior
I expect to be able to acquire a valid token for the user at any point during the "request" lifecycle.
Actual behavior
The following stack trace:
[2020-05-12T21:55:47.258Z] Error: System.NullReferenceException: Object reference not set to an instance of an object.
at Microsoft.Identity.Web.TokenAcquisition.CreateRedirectUri()
at Microsoft.Identity.Web.TokenAcquisition.BuildConfidentialClientApplicationAsync()
at Microsoft.Identity.Web.TokenAcquisition.GetOrBuildConfidentialClientApplicationAsync()
at Microsoft.Identity.Web.TokenAcquisition.GetAccessTokenForUserAsync(IEnumerable`1 scopes, String tenant)
...Possible Solution
At a minimum, better exception handling that leads me to the actual error.
Activity
bgavrilMS commentedon May 13, 2020
Possibly a duplicate of #136
Gary Grubbs (@gwgrubbs) - do you have a stack trace?
gwgrubbs commentedon May 13, 2020
I don't think it's a duplicate as the stack trace indicates a different point in the stack for the exception.
Stack trace for #136:
Stack trace for my issue (included in "Actual behavior" of submitted ticket):
From review of #136, I thought the issue may be related to this line in
CreateRedirectUrimethod ofTokenAcquisition.cs:where a root issue of a null HttpContext may be the similarity between #136 and this issue.
jaimunday commentedon May 28, 2020
I also have this same issue (works perfectly locally but Azure Web App fails).
I notice it was tagged for the new preview but removed now? Do you know which preview this would be added into instead please?
jmprieur commentedon May 28, 2020
Gary Grubbs (@gwgrubbs)
gwgrubbs commentedon May 28, 2020
Jean-Marc Prieur (@jmprieur)
I do think there is a case with Blazor that may be an issue across the board. As described in the issue report, everything works as expected in the OnGet() method of the Blazor page; i.e. I can use
GetAccessTokenForUserAsyncand successfully retrieve an AD token. This is because this is the original request to the server, at which time HttpContext is available. In the service methods that I have where it doesn't work, the methods are executed via requests made over a web socket where HttpContext is not available. So I'm concluding that anything in Microsoft.Identity.Web that depends on HttpContext will not work in Blazor applications when the requests are made over web socket.The reason (I believe) it works locally is that HttpContext is available for subsequent requests by the way local development environments work - it fails in Azure by the way browsers communicate via web socket to the App Service.
I also implemented a rather clunky workaround where in the OnGet() method I set a property on the model with the value of the AD Token that I then inject as a CascadingParameter into the components, which is then passed to my service method as a method arg. A lot of plumbing/passing of the AD Token where it would be ideal to use Microsoft.Identity.Web to request a token when/where needed.
isaacrlevin commentedon Jul 9, 2020
Gary Grubbs (@gwgrubbs) you are right with the bit about HttpContext. The workaround is to have a service that caches the token for you. I am doing this here
https://github.com/isaacrlevin/PresenceLight/blob/main/src/PresenceLight.Worker/Startup.cs#L69
This is using Microsoft.Identity.Client so it won't work here directly. Need to modify the process to get the token but it IS doable
14 remaining items
jennyf19 commentedon Jul 22, 2020
Gary Grubbs (@gwgrubbs) Can you try this branch it should handle the user context for you...proof of concept inspired by this sample
dansmitt commentedon Jul 22, 2020
jennyf19 works so far :)
dansmitt commentedon Jul 22, 2020
jennyf19 Sometimes I get an Exception:
blazor.server.js:19 [2020-07-22T14:44:30.900Z] Error: System.NullReferenceException: Object reference not set to an instance of an object.
at Microsoft.Identity.Web.HttpContextExtensions.GetTokenUsedToCallWebAPI(HttpContext httpContext) in C:\src\Microsoft.Identity.Web\HttpContextExtensions.cs:line 29
at Microsoft.Identity.Web.TokenAcquisition.GetAccessTokenForUserAsync(IEnumerable`1 scopes, String tenant, String userFlow, ClaimsPrincipal user) in C:\src\Microsoft.Identity.Web\TokenAcquisition.cs:line 258
When I delete the cookies and do a reload, Everything works fine. Is this a problem related to the actual chanages?
The
CurrentHttpContextat line 258 is null.gwgrubbs commentedon Jul 22, 2020
jennyf19 I concur with @schmid37 that it is working so far. I haven't experienced the issue you see, but I think I know what the issue is. if you have a stale cookie and call
GetAccessTokenOnBehalfOfUserFromCacheAsync, line 243 will throw aMsalUiRequiredExceptionexception (expecting you to then initiate some redirect to signin to re-authenticate or something). In the catch block, line 258 will cause the result you see, as the rule isCurrentHttpContextwill always be null.jennyf19 commentedon Jul 22, 2020
Gary Grubbs (@gwgrubbs) & @schmid37 glad to hear it's working, thanks for confirming. we are aware of the redirect issue, it's because blazor doesn't have the challenge method, so we're trying to come up with a work around.
dansmitt commentedon Jul 23, 2020
jennyf19 how can we track this? Is there an existing open issue?
jennyf19 commentedon Jul 23, 2020
@schmid37 this is the only issue for tracking at the moment. we're trying to get this into our next release (today or tomorrow), but if we run out of time (we have an external deadline), then I will close this and open a new issue, ping you both here so you know. sound good?
dansmitt commentedon Jul 23, 2020
jennyf19 sounds good to me! Thx for the support πͺπ»
jennyf19 commentedon Jul 23, 2020
@schmid37 Gary Grubbs (@gwgrubbs) here's the new issue for the second part of the call. will still try to get this in the current milestone if possible.
pmaytak commentedon Jul 25, 2020
Gary Grubbs (@gwgrubbs) jaimunday Isaac Levin (@isaacrlevin) @schmid37
This is included in Microsoft Identity Web 0.2.1-preview release.