Search code examples
owinopenid-connectadal

OpenIdConnectResponseTypes has codeidtoken ,idtoken and it doesnt contain code as response type


OpenIdConnectResponseTypes has codeidtoken ,idtoken and it doesnt contain code as response type. Does UseOpenIdConnectAuthentication in OWIN support Authorization Code grant? By default it sets the responsetype as Code IDToken. Can someone share the sample for Authorization code grant using OWIN ?


Solution

  • From source code of Katana (below code could be found in OpenIDConnectAuthenticationHandler.AuthenticateCoreAsync method):

    // code is only accepted with id_token, in this version, hence check for code is inside this if
    // OpenIdConnect protocol allows a Code to be received without the id_token
    if (string.IsNullOrWhiteSpace(openIdConnectMessage.IdToken))
    {
       _logger.WriteWarning("The id_token is missing.");
       return null;
    }
    

    Above code shows Microsoft.Owin.Security.OpenIdConnect library doesn't support Authorization Code grant . Though not directly supported, you can also use the hybrid flow , but it's up to you to implement the token request part , please refer to below code which use code to exchange the access token for resource protected by azure ad :

        app.UseOpenIdConnectAuthentication(
            new OpenIdConnectAuthenticationOptions
            {
    
                ClientId = clientId,
                Authority = Authority,
                PostLogoutRedirectUri = postLogoutRedirectUri,
                Notifications = new OpenIdConnectAuthenticationNotifications()
                {
                    //
                    // If there is a code in the OpenID Connect response, redeem it for an access token and refresh token, and store those away.
                    //
    
                    AuthorizationCodeReceived = async (context) =>
                    {
                        var code = context.Code;
    
                            // Create a Client Credential Using an Application Key
                            ClientCredential credential = new ClientCredential(clientId, appKey);
                            string userObjectID = context.AuthenticationTicket.Identity.FindFirst(
                                "http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
                            AuthenticationContext authContext = new AuthenticationContext(Authority, new NaiveSessionCache(userObjectID));
                            AuthenticationResult result = await authContext.AcquireTokenByAuthorizationCodeAsync(
                                code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, graphResourceId);
                    }
    
                }
    
            }