Search code examples
azureazure-api-appsazure-authentication

a method to retrieve id_token from Azure AD body request


I'm following this WebApp-WebAPI example. Is there a method to retrieve an id_token after a B2C user is authorized and the id_token is received within the body? I'm on Function app V3.

I receive the authorization response to replyURL in an azure Function app but the id_token coming in a body mixed with code and state data, and I can't seem to break it out or deserialize to json:

public class Function1
{
    internal class AuthToken
        {
            [JsonProperty("id_token")]
            public string id_Token { get; set; }

            [JsonProperty("state")]
            public string StateToken { get; set; }

            [JsonProperty("code")]
            public string CodeToken { get; set; }
        }

    private readonly HttpClient httpClient = new HttpClient();
    [FunctionName("ReceiverAuth")]
    public static async Task<HttpStatusCode> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req, ILogger log)
    {
        //this works and shows id_token, state, code as text (also without the Encoding.UTF8 parameter)
        var requestBody = await new StreamReader(req.Body, Encoding.UTF8).ReadToEndAsync();

       //trying to separate the id_token data into json throws http500
        AuthToken authTok = JsonConvert.DeserializeObject<AuthToken>(requestBody);
        var idToken = authTok.id_Token;
}

Also tried but didn't change the result:

var decodedRequestBody = System.Net.WebUtility.HtmlDecode(requestBody);

To my noob eyes Fiddler's body feels like the data is broken out but I can't separate the id_token on the req. received. Showing request header and webform and response. enter image description here enter image description here


Solution

  • The data is sent to you as form data, not JSON.

    You need to use something like this:

    var idToken = req.Form["id_token"];
    

    Or you could try FromForm instead of HttpRequest req:

    [FromForm] AuthToken authTok
    

    If these don't work, check these: How to parse form data using Azure Functions