Skip to content

token creation by adding payload consisting of associative array with multiple key value pairs #793

Closed

Description

@ionics

Hi folks, hi Luís,

Two possibilities i could think of:

1)

extend documentation

add section token creation: "adding payload consisting of associative array with multiple key value pairs"

please add a best practice example to the documentation on how to add payload data in the form of an associative array (consisting of multiple key => value pairs) on token creation.

Right now i have came up with a solution such as:

Example:

# example data
$data   = array(
            "success_url"     => $scheme.$salesChannelUrl.'/addProduct2Cart',
            "cancel_url"      => $scheme.$salesChannelUrl.$cancelUrlPath,
            "template_id"     => $id,
            "customer"        => $token,
            "locale"          => "de_DE",
            "timezone"        => "Europe/Vienna",
            "theme"           => "default",
            "additional_data" => base64_encode(json_encode([
                "sw-access-key"  => $key,
                "sw-context-token" => $token,
                "product-id" => $product,
                "sales-channel-url" => $salesChannelUrl,
                "quantity" => $quantity,
                "jwtSecretKey" => $jwtSecret,
                "isLogin"      => 1,
                "checkCustomerUrl" => $salesChannelUrl.$checkCustomerUrl
            ]))
        );

# actual token creation
        $builder = null;
        $counter = 0;

        foreach ($data as $key => $value) {
            if($counter < 1){
                $builder = $config->builder()
                    ->withClaim($key, $value);
            }
            else{
                $builder->withClaim($key, $value);
            }
            $counter++;
        }

# get the token
        $createdJwtTokenObject = $builder->getToken($signer, $signingKey);
        $createdJwtTokenStringRepresentation = $builder->getToken($signer, $signingKey)->toString();

# now one could request data from a JWT talking API server with this created token
        $response = $client->request(
            'POST',
            'https://server-jwt-api.example.com/external/public/api/jwttoken/store', [
            'query' => ['jwt' => $createdJwtTokenStringRepresentation]
        ]);

        $stream =  $response->getBody();

        $array = json_decode($stream->getContents(), true);

# and by example return as response to javascript script or whatever...
        $response = new Response(
            $array['data'],
            Response::HTTP_OK,
            ['content-type' => 'text/html']
        );

        return $response;

  • but the foreach loop to please the withClaim function seems not elegant and is bad to read.

OR Alternative for future jwt releases

2)

maybe it makes sense to provide a new function in future lcobucci/jwt releases to $config->builder()->withClaims($array) to deal with associative array payload data? Maybe not the user but lcobucci/jwt should take care about to proper handle the adding of multiple payload data on token creation?

i hope this helps others with similar issues as i had.

Kind regards,
Raphael

Activity

  1. SvenRtbg commented on Oct 5, 2021

    @SvenRtbg
    Collaborator

    Yeah, your "actual token creation" should look like this:

        $builder = $config->builder();
    
        foreach ($data as $key => $value) {
                $builder->withClaim($key, $value);
        }
    

    Why building the builder inside the loop? If you don't build it because the array is empty, all following code accessing the $builder to get the token will fail because the builder hasn't been created.

  2. SvenRtbg commented on Oct 5, 2021

    @SvenRtbg
    Collaborator

    And in fact your example data array is quite complex, carrying the notion that "additional_data" seems to be requiring special treatment anyways. I don't know why the data has to be json_encoded base64'd, but this isn't something this library would do for you. So we are effectively talking about who is doing the loop: Your code, or the libraries code, because the implementation of withClaims(array $claims) would effectively be the same code:

    public function withClaims(array $claims) {
        foreach ($claims as $key => $value) {
            $this->withClaim($key, $value);
        }
    }
    
  3. ionics commented on Oct 5, 2021

    @ionics
    Author

    Thank you very much @SvenRtbg for pointing this out.

    getting the builder object before foreach() is the way to go. I have tried this before and did not succeed, sure there was another issue in my code i have not been aware of... closing.

    sidenote:
    the base64_encode was from a real world example where the API server is expecting a data structure in that form.

    Thank you!

  4. lcobucci commented on Oct 5, 2021

    @lcobucci
    Owner

    Thanks @SvenRtbg for helping out :)
    I'll convert this into a discussion since it might help other people.

  5. Repository owner locked and limited conversation to collaborators on Oct 5, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions