get valid jwt token from azure b2c custom application

Pfeiffer Andreas - UCI 245 Reputation points
2023-12-12T15:36:18.39+00:00

Hi there,

I am trying to understand how to get a valid token, especially the scope or roles in the token with curl. Here is my code (in php, but simple enough to be understandable) :

    $clientId = CLIENT_ID;
    $clientSecret = SECRET;
    $tenant_id = TENANT_ID;
    $grantType = "client_credentials";
    $tokenEndpoint ="https://login.microsoftonline.com/$tenant_id/oauth2/token";

    	
    $scope = "https://<b2c tenant url>/xxxxxx-5ed7-415d-af04-xxxxxxxxxx/.default";

    // Build the request body
   $requestBody = "client_id=$clientId&client_secret=$clientSecret&grant_type=$grantType&scope=".urlencode($scope)."";

    // Set up the curl options
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $tokenEndpoint);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $requestBody);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    // Execute the request
    $response = curl_exec($ch);
    curl_close($ch);

    // Get the access token from the response
    $responseJson = json_decode($response, true);
    $accessToken = $responseJson["access_token"];
    print $accessToken;

When testing my token on jwt.ms, everything is fine unless the scope which is not set in the token (neither scp nor roles in the claim). As a consequence, I cannot use the token since I get a 401 error (not authorize)

This piece of code works fine in a b2b context with scopes set at the app registration.

Note here I don't want to have an interactive flow with user credentials as mentionned in the doc here : https://learn.microsoft.com/en-us/azure/active-directory-b2c/access-tokens. I just want a valid token for the app without interaction of a user giving his username and password.

Any recommendation, link to a doc or example, etc... would be great.

thank you

Microsoft Security | Microsoft Graph
{count} votes

Accepted answer
  1. CarlZhao-MSFT 46,376 Reputation points
    2023-12-13T08:59:10.12+00:00

    Hi @Pfeiffer Andreas - UCI

    Then you just need to change the token endpoint to the following:

    $tokenEndpoint ="https://<tenant-name>.b2clogin.com/<tenant-name>.onmicrosoft.com/<policy>/oauth2/v2.0/token";
    

    See step 3 of this document.

    Hope this helps.

    If the reply is helpful, please click Accept Answer and kindly upvote it. If you have additional questions about this answer, please click Comment.


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.