How to structure, prepare and set JWT authorization bearer token for / with CURL requests
Asked Answered
O

1

1

To sent and receive authorization bearer I did read this Correct way to set Bearer token with cURL and this How to properly use Bearer tokens? and here is my code:

$url = "http://www.example.com/phpinfo.php";
$data = array('long_url' => 'http://www.google.com');



$ch = curl_init($url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

//example token
$token = 'ffaaf96dd9';
$header = array("Authorization: Bearer ". $token);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
$response = curl_exec($ch);
curl_close($ch);
print($response);

How to set authorization $token so then I could access it via global $_SERVER["Authorization"] variable in phpinfo.php.

What am I missing?

Overvalue answered 27/10, 2019 at 17:6 Comment(4)
You changed example.com to the proper url?Minesweeper
of couse yes, I edited just here for privacy. This is actually set to my site phpinfo page.Overvalue
I tried your code on my own setup (using PHP on docker) and in HTTP Headers Information, I get - <tr><td class="e">Authorization </td><td class="v">Bearer ffaaf96dd9 </td></tr>Lenten
How did you access that page? was it your phpinfo? was it as $_SERVER['Authorization']? or how?Overvalue
F
2

Bearer Tokens are not set automatically by the server

Developers require to create custom function(s), that encodes and decodes bearer tokens.

Bearer token is a way to encode arrays of sensitive data for secure transportation between servers.

Usually to be used in conjunction with other software, for example for oAuth cross server API functionality.

oAuth is an open source framework that allows the creation of secure communication between servers without continuous risks of using passwords.

Bearer client allows to encode array of information for user authentication and/or for sensitive data transfer.

Depending on what you need to use it for, you likely to find plenty of examples, plugins and extension online and if it comes with some 3d party software, you usually get a thorough documentation.

Below is an example of usage of bearer token for a Website based on Wordpress CMS.

1. Install a combination of plugins on the Wordpress oAuth, Rest_API & jwt-authentication-for-wp-rest-api and then extend them with your own plugin(s).

You will need to create custom token generating function, receiving URL points etc. Then you will be able send / receive information securely, for example between Chrome / Safari Browser extension and your Wordpress website.

2. Example Receiving Url Point on WordPress website:

               add_action( 'rest_api_init', function () {
                    //apply_filters( 'determine_current_user', true );
                    register_rest_route( 'humanai/v1', 'data', array(
                 
                        'methods'  => 'POST',
                        'callback' => function($request){ 
                                global $wpdb;
                                $data = $request->get_params();
                                $query = array( 'meta_key' => 'hai-token', 'meta_value' => $data[0]['token'] );
                                $user_id = $wpdb->query('SELECT * FROM '.$wpdb->prefix.'usermeta WHERE meta_key = \'hai-token\' AND meta_value=\''. $data[0]['token'].'\'');

/* Please pay attention on the processing_function, you will use it to process request and return any data if required. */

                                return processing_function($user_id, $request);
                        }
                 
                    ) );
                ),12);

3. The processing_function

         function processing_function($user_id, $request){
              $res = update_user_meta($user_id,'new_creadit_card_number',$request['new_creadit_card_number']);
         }
  1. Of course you need a function to control the Bearer tokens... There's a reason bearer token called Bearer...because it is bearing the information, please have a look at my example below:

    function jwt_token($attr=null){
    
        $secret_key = defined('JWT_AUTH_SECRET_KEY') ? JWT_AUTH_SECRET_KEY : false;
    
        /** First thing, check the secret key if not exist return a error*/
        if (!$secret_key) {
            return new WP_Error(
                'jwt_auth_bad_config',
                __('JWT is not configured properly, please contact the admin', 'wp-api-jwt-auth'),
                array(
                    'status' => 403,
                )
            );
        }
        /** Try to authenticate the user with the passed credentials*/
        $user = wp_get_current_user();
    
        /** If the authentication fails return a error*/
        if (is_wp_error($user)) {
            $error_code = $user->get_error_code();
            return new WP_Error(
                '[jwt_auth] '.$error_code,
                $user->get_error_message($error_code),
                array(
                    'status' => 403,
                )
            );
        }
    
        /** Valid credentials, the user exists create the according Token */
        $issuedAt = time();
        $notBefore = apply_filters('jwt_auth_not_before', $issuedAt, $issuedAt);
        $expire = apply_filters('jwt_auth_expire', $issuedAt + (DAY_IN_SECONDS * 30), $issuedAt);
    
        $token = array(
            'iss' => get_bloginfo('url'),
            'iat' => $issuedAt,
            'nbf' => $notBefore,
            'exp' => $expire,
            'data' => array(
                'user' => array(
                    'id' => $user->data->ID,
                ),
            ),
        );
    
        require dirname(dirname(dirname(__FILE__))) . '/jwt-authentication-for-wp-rest-api/includes/vendor/autoload.php';
    
            /** Let the user modify the token data before the sign. */
            $token = JWT::encode(apply_filters('jwt_auth_token_before_sign', $token, $user), $secret_key);
    

/* Attention below The token is signed, now create the object with user data to the client. */

            $data = array(
                'token' => $token,
                'user_email' => $user->data->user_email,
                'user_nicename' => $user->data->user_nicename,
                'user_display_name' => $user->data->display_name,
                'user_new_credit_card' => 'XXXX XXXX XXXX XXXX'  
            );

            /** Let the user modify the data before send it back */
            return apply_filters('jwt_auth_token_before_dispatch', $data, $user);
        
    }

Please note:

This is not a complete functionality, software, nor a complete solution to the original question.

All information is provided strictly for educational purposes.

I strongly suggest to use additional methods of encryption to protect sensitive information.

When building a complete functionality/software and facing new issues, why not link them in a new question in a comment below? - I will try to help as much as I can in a new answer.

Fable answered 31/10, 2019 at 9:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.