[Question] How to handle the MsalUiRequiredException for incremental consent with AJAX calls
See original GitHub issueWhich version of Microsoft Identity Web are you using? v0.4.0-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
- In-memory caches
- Session caches
- Distributed caches
- Other (please describe)
Is this a new or an existing app? c. This is a new app or an experiment.
Repro
in startup.cs configureservices:
string[] initialScopes = Configuration.GetValue<string>("DownstreamApi:Scopes")?.Split(' ');
services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApp(Configuration.GetSection("AzureAd"))
.EnableTokenAcquisitionToCallDownstreamApi(initialScopes)
.AddMicrosoftGraph(Configuration.GetSection("DownstreamApi"))
.AddDistributedTokenCaches();
services.AddControllersWithViews(options =>
{
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
options.Filters.Add(new AuthorizeFilter(policy));
}).AddMicrosoftIdentityUI();
in appsettings.json:
"DownstreamApi": {
/*
'Scopes' contains space separated scopes of the Web API you want to call. This can be:
- a scope for a V2 application (for instance api:b3682cc7-8b30-4bd2-aaba-080c6bf0fd31/access_as_user)
- a scope corresponding to a V1 application (for instance <App ID URI>/.default, where <App ID URI> is the
App ID URI of a legacy v1 Web application
Applications are registered in the https:portal.azure.com portal.
*/
"BaseUrl": "https://graph.microsoft.com/v1.0",
"Scopes": "user.read"
in controller:
[Authorize]
[HttpGet]
[Route("RecognitionTile")]
[AuthorizeForScopes(Scopes = new[] { "https://ccbcc.sharepoint.com/AllSites.Read" })]
public ViewComponentResult RecognitionTile()
{
return ViewComponent("RecognitionTile");
}
for token acquistion;
/// <summary>
/// Private: Gets and returns an access token for the provided resource.
/// </summary>
/// <param name="resource">Resource to obtain access token for</param>
/// <returns></returns>
private async Task<string> GetAccessTokenforResource(string resource)
{
// Get the access token for the resource.
string accessToken = await _tokenAcquisition.GetAccessTokenForUserAsync(new[] { resource });
//resource is actually same as controller scope -- "https://ccbcc.sharepoint.com/AllSites.Read"
Expected behavior Expect the incremental consent prompt to come up when call the controller. Actual behavior When call the tokenAcquisition.GetAccessTokenForUserAsync(new[] { resource }) they exception is thrown: IDW10502 An MsalUiRequiredException was thrown due to a challenge for the user. Inner Exeption: AADSTS65001: The user or administrator has not consented to use the application with ID ‘xxx’ named ‘xxxx’. Send an interactive authorization request for this user and resource.
Possible solution
Additional context / logs / screenshots This code is trying to access sharepoint api with incremental scope. The initial scope cause the initial consent prompt during authentication: Cleared all the Permissions prior: After initial consent:
Issue Analytics
- State:
- Created 3 years ago
- Comments:31 (15 by maintainers)
Top GitHub Comments
See also https://github.com/Azure-Samples/active-directory-aspnetcore-webapp-openidconnect-v2/issues/264#issuecomment-703351600
@OnAzureCloud9 I tried to do the following in startup.cs and it solved the AJAX issue similar as Cookie Authentication scheme mentioned earlier by @Tratcher. Basically it detect AJAX request and return 401 in Response and in Header Location parameter pass the incremental consent page to get Auth Code. The AJAX has a chance to redirect the browser window by window.location = authcode url and avoid CORS errors.
But I have another problem after I introduced this OnRedirectToIdentityProvider OpenIdConnectEvent, which is now causing an infinite loop on this authcode page similar to #573, #531. It seems that the it is interfering with the following method protected override async Task HandleChallengeAsync(AuthenticationProperties properties) within public class OpenIdConnectHandler : RemoteAuthenticationHandler<OpenIdConnectOptions>, IAuthenticationSignOutHandler. The method is processing posted auth code and then within same method redeming access token. Trying reading all kind of document about auth code flow which is up to date with the code is a challenging task alone,
I just upgraded the Microsoft.Identity.Web to the 1.0.0, will look if there is any luck.
For my project to move ahead, I just admin consent them all and removed the incremental consent, sadly.