Repository navigation
Closed
Labels
Milestone
Description
Which version of Microsoft Identity Web are you using?
1.16.1
Where is the issue?
- Web app
- Sign-in users
- 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
- In-memory caches
- Session caches
- Distributed caches
- Other (please describe)
Is this a new or an existing app?
The app is in production and I have upgraded to a new version of Microsoft Identity Web. This error started happening after upgrading from 1.15.2 to 1.16.1. I've verified this by downgrading the package to 1.15.2 again.
I think maybe this issue is related to #1372 but it has already been closed so I opened a new issue for this.
Repro
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication()
.AddMicrosoftIdentityWebApp(azureAdSection, cookieScheme: null)
.EnableTokenAcquisitionToCallDownstreamApi().AddInMemoryTokenCaches();
}
public void Configure(IApplicationBuilder app)
{
app.UseAuthentication();
app.UseAuthorization();
}
}
public class BaseController : Controller
{
private readonly SignInManager<User> _signInManager;
private readonly ITokenAcquisition _tokenAcquisition;
private readonly IGraphApiClient _graphApiClient;
public BaseController(
SignInManager<User> signInManager,
ITokenAcquisition tokenAcquisition,
IGraphApiClient graphApiClient
)
{
_signInManager = signInManager;
_tokenAcquisition = tokenAcquisition;
_graphApiClient = graphApiClient;
}
[Route("ExternalLoginCallback")]
public async Task<IActionResult> ExternalLoginCallback(
string returnUrl,
string? remoteError = null
)
{
var info = await _signInManager.GetExternalLoginInfoAsync();
var accessToken = await _tokenAcquisition.GetAccessTokenForUserAsync(
new[] { "User.Read" },
user: info.Principal
);
}
}Expected behavior
I expected ITokenAcquisition.GetAccessTokenForUserAsync() to return an access token like it did in 1.15.2 instead of throwing a NullReferenceException.
Actual behavior
The call to ITokenAcquisition.GetAccessTokenForUserAsync() throws the following exception:
System.NullReferenceException: Object reference not set to an instance of an object.
at Microsoft.Identity.Web.MergedOptions.PrepareAuthorityInstanceForMsal()
at Microsoft.Identity.Web.TokenAcquisition.BuildConfidentialClientApplication(MergedOptions mergedOptions)
at Microsoft.Identity.Web.TokenAcquisition.GetOrBuildConfidentialClientApplication(MergedOptions mergedOptions)
at Microsoft.Identity.Web.TokenAcquisition.GetAuthenticationResultForUserAsync(IEnumerable`1 scopes, String authenticationScheme, String tenantId, String userFlow, ClaimsPrincipal user, TokenAcquisitionOptions tokenAcquisitionOptions)
at Microsoft.Identity.Web.TokenAcquisition.GetAccessTokenForUserAsync(IEnumerable`1 scopes, String authenticationScheme, String tenantId, String userFlow, ClaimsPrincipal user, TokenAcquisitionOptions tokenAcquisitionOptions)
at TEST.Web.Controllers.BaseController.ExternalLoginCallback(String returnUrl, String remoteError) in D:\Code\DotNet\Test\TEST.Web\Controllers\BaseController.cs:line 159
at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.TaskOfIActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeActionMethodAsync>g__Awaited|12_0(ControllerActionInvoker invoker, ValueTask`1 actionResultValueTask)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeNextActionFilterAsync>g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeInnerFilterAsync>g__Awaited|13_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|24_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Session.SessionMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Session.SessionMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.ResponseCaching.ResponseCachingMiddleware.Invoke(HttpContext httpContext)
at Microsoft.AspNetCore.Diagnostics.StatusCodePagesMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
Activity
[-][Bug] Calling TokenAcquisition.GetAccessTokenForUserAsync still throws a NullReferenceException[/-][+][Bug] Calling TokenAcquisition.GetAccessTokenForUserAsync throws a NullReferenceException[/+]jennyf19 commentedon Sep 13, 2021
David Karlsson (@davidkarlsson) can you provide a link to your code or a basic repro i can run locally? thank you.
davidkarlsson commentedon Sep 13, 2021
jennyf19 I've written a repro you can run locally here now: https://github.com/davidkarlsson/identity-web-token-issue.
lsiepel commentedon Sep 13, 2021
Same issue here. Downgraded Microsoft.Identity.Web 16.1 to 16.0 and all is fine.
Startup.cs:
Unfortunately i'm unable to provide a runnable demo at this moment, but if the provided details are not enough, i could try to spend some time later this week.
When same code is used with package 16.0 all is fine.
jennyf19 commentedon Sep 13, 2021
lsiepel can you include a default authentication scheme? Which authentication scheme do you have in your controller, when you call token acquisition?
lsiepel commentedon Sep 15, 2021
Ah sorry, the authentication schemepart was left out. Both schemes are used in the controllers, both lead to the same problem
GeorgeTTD commentedon Oct 11, 2021
Hi David Karlsson (@davidkarlsson),
Not sure if this is any help but I have found that using AuthorizeForScopesAttribute has solved a similar sounding issue for me. Use
[AuthorizeForScopes]on the pages you wish to use token acquisition or add it as a filter if you want to apply to all routes.davidkarlsson commentedon Oct 11, 2021
Hey George Downer (@GeorgeTTD)! Thanks for the suggestion but as far as I can tell I don't really want the functionality the
[AuthorizeForScopes]attribute provides. The scopes I'm using either don't require incremental consent or has already been authorized by an admin for the application in Azure AD.Also calling
ITokenAcquisition.GetAccessTokenForUserAsync()is working fine from the controller action without this attribute in 1.15.2 but throws a NullReferenceException in 1.16.1 so I think it is meant to work without it.lsiepel commentedon Nov 19, 2021
Will be testing if this issue still persists for the latest version. Is there anything i can do to help fix this issue?
davidkarlsson commentedon Nov 22, 2021
jennyf19 Were you able to reproduce this error with 1.16.1 or later with the test repo I created?
Choonster commentedon Dec 22, 2021
Similar to #1385, this seems to be caused by the options merge not being triggered. I worked around this by getting the
IOptionsMonitor<OpenIdConnectOptions>instance (fromHttpContext.RequestServicesin my case) and callingGet(OpenIdConnectDefaults.AuthenticationScheme)to trigger the merge.jennyf19 commentedon Dec 23, 2021
sorry for the delay in responses. will take a look.
jmprieur commentedon Mar 28, 2022
See PR: #1672
jennyf19 commentedon Apr 20, 2022
Released in 1.24.0.
davidkarlsson commentedon May 17, 2022
After having updated from 1.15.2 to 1.24.1 I now have to pass
OpenIdConnectDefaults.AuthenticationSchemeas theauthenticationSchemeparameter toGetAccessTokenForUserAsyncfor this to work otherwise it throws this new exception the PR added:Is this a required parameter now or is this a bug? The documentation for the parameter says "Authentication scheme. If null, will use OpenIdConnectDefault.AuthenticationScheme if called from a web app..." so I thought it should work without passing a scheme to it? There's also a spelling mistake there as it should say
OpenIdConnectDefaults.AuthenticationSchemeand notOpenIdConnectDefault.AuthenticationScheme.I'm not sure if this matters but I'm not passing OpenIdConnect as the default authentication scheme when I configure authentication because I'm using both cookie and OpenID Connect authentication:
FelipeCostaGualberto commentedon Jun 10, 2022
Hi, I lost a lot of time with this problem because the latest version (1.25.0) doesn't work with
JwtBearerDefaultsscheme. Downgrading to 1.16.0 made it work. Please fix this. This is how I register my service:jmprieur commentedon Jun 13, 2022
What does not work @FelipeCostaGualberto
Can you please provide a full repro?
@davidkarlsson.
Thanks for the update.
FelipeCostaGualberto commentedon Jun 14, 2022
Hi Jean-Marc Prieur (@jmprieur) , as soon as I can create a minimal project I'll provide a repo, thanks for investigating the issue.
What not work is: if I use
Microsoft.Identity.Web 1.25.0, the methodITokenAcquisition.GetAccessTokenForUserAsyncthrowsNullReferenceException. If you use version1.16.0, it works normally.xperiandri commentedon Jun 19, 2022
Here is the issue
microsoft-identity-web/src/Microsoft.Identity.Web/ITokenAcquisition.cs
Line 41 in 34cfae8
rkd-xom commentedon Jul 9, 2022
Is this fixed? I'm facing the same issue and I am using
JwtBearerDefaultsscheme as well. I tried usingOpenIdConnectDefaults.AuthenticationSchemeas well and got the same errorSystem.InvalidOperationException: IDW10503: Cannot determine the cloud Instance. The provided authentication scheme was ''.I'm using version 1.25.1dawid-kraczkowski commentedon Jan 5, 2023
I solved this problem by implementing custom AuthenticationSchemeProvider according to this thread: https://stackoverflow.com/questions/46464469/how-to-configureservices-authentication-based-on-routes-in-asp-net-core-2-0