Handling Consent in .Net Framework 4.8 Web Forms/OWIN middleware app and Microsoft.Identity.Web

267 Views Asked by At

I am trying to configure a web app that signs-in users and calls a web API, but the app does not show the consent pop up for a scope for which consent has not been given.

My Owin Middleware code contains the following

app.AddMicrosoftIdentityWebApp(factory, updateOptions: options => 
        {
            options.RedirectUri = redirectUri;
            options.PostLogoutRedirectUri = redirectUri;
            //options.Scope = apiScopes;
        });

Notice the commented-out line. If I include that line, the consent pop up shows up and the user is able to consent, but then when trying to get the access_token to call my API, I get an "MsalUiRequiredException: No account or login hint was passed to the acquireTokenSilent call", which I try to handle by issueing a new Authentication challenge, which in turn ends up causing and endless loop.

This is how I try get the access token and call my API:

public HttpResponseMessage Get(string apiUrl) 
    {           
        IAuthorizationHeaderProvider headerProvider = TokenAcquirerFactory.GetDefaultInstance().ServiceProvider?.GetService(typeof(IAuthorizationHeaderProvider)) as IAuthorizationHeaderProvider;
        string authorizationHeader = headerProvider.CreateAuthorizationHeaderForUserAsync(_apiScopes).Result;

        HttpResponseMessage result;            
        var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, apiUrl);
        httpRequestMessage.Headers.Add("Authorization", authorizationHeader);

        result = _httpClient.SendAsync(httpRequestMessage).Result;
        return result;
    }

If I keep the line "options.Scope = apiScopes" commented out, consent pop up will not show up and when trying to retrieve the access_token I get this: "MsalUiRequiredException: AADSTS65001: The user or administrator has not consented to use the application with ID '' named ''. Send an interactive authorization request for this user and resource"

I added api permissions in client app registration and created the corresponding scopes in API's app registration. I also made sure there were scopes for which consent was not given yet in the client app registration.

apiScopes = "openid offline_access api://b624.../test-scope"

Thanks in advance for the help.

0

There are 0 best solutions below