Azure B2C: Generating the code_challenge

Viewed 2124

My Azure app is a single-page application and when trying to implement email signup via invite, I get the error:

AADB2C99059: The supplied request must present a code_challenge

Does our application server generate this code_challenge or should Azure B2C do this for us? Also, how exactly should we generate the code_challenge?

2 Answers

You need to generate the code_challenge via code and pass it to the request URL, also use code_verifier when getting the access token.

Reference - https://medium.com/the-new-control-plane/using-proof-key-for-code-exchange-pkce-in-azure-ad-b2c-9203fbc148fd

C# Sample:

using IdentityModel;
using System;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
 
namespace PKCEConsoleApp2
{
    class Program
    {
        static void Main(string[] args)
        {
            var random = new Random();
            int cvlength = random.Next(43, 128);
            const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~";
            var codeVerifier = new string (Enumerable.Repeat(chars, cvlength).Select(s => s[random.Next(s.Length)]).ToArray());
 
            string codeChallenge;
            using (var sha256 = SHA256.Create())
            {
                var a = Encoding.UTF8.GetBytes(codeVerifier);
                var challengeBytes = sha256.ComputeHash(Encoding.UTF8.GetBytes(codeVerifier));
                codeChallenge = Base64Url.Encode(challengeBytes);
 
/* Alternatively instead of using Base64Url.Encode method, the code below can accomplish the same result:
 
                var result = Convert.ToBase64String(challengeBytes)
                    .Replace('+', '-') // replace URL unsafe characters with safe ones
                    .Replace('/', '_') // replace URL unsafe characters with safe ones
                    .Replace("=", ""); // no padding
*/
            }
 
            Console.WriteLine("codeVerifier " + codeVerifier + "\n");
            Console.WriteLine("codeChallenge " + codeChallenge + "\n");
 
            Console.ReadLine();
        }
    }
}

You need to send the auth request to your app, and have your app make the proper auth request. You cannot just launch the invite link as-is, it’s just an example to test it.

To integrate such a link into an app, see this:

https://docs.microsoft.com/en-us/azure/active-directory-b2c/enable-authentication-spa-app-options#pass-id-token-hint

For SPA app, if you use MSAL.js library, initialise the extraQueryParameters config key in your MSAL object. And pass in the key value pair: id_token_hint : id_token_hint_value. Then pass the correct B2C policy Id as the authority and then initiate msalObj.loginRedirect().

Your users should receive a link like myApp.com/redeem?id_token=id_token_hint_value.

Related