How to call Auth0 API to get Auth0 Roles


First we have to copy the token from Auth0 Management API

API URL to get the Auth0 Roles

 https://dev-ki9-psll.us.auth0.com/api/v2/users/{id}/roles


Source Code (functions.php) : 


if ( ! function_exists( 'customroles' ) ) :

    /**
     * Preloads the main web font to improve performance.
     *
     * Only the main web font (font-style: normal) is preloaded here since that font is always relevant (it is used
     * on every heading, for example). The other font is only needed if there is any applicable content in italic style,
     * and therefore preloading it would in most cases regress performance when that font would otherwise not be loaded
     * at all.
     *
     * @since   Custom Function 1.0
     *
     * @return void
     */
    function customroles() {
   

    if(is_user_logged_in() )    
    {
        $user_ID = get_current_user_id();
   
            global $wpdb;
            $result = $wpdb->get_results("select meta_value from wp_usermeta where user_id=".$user_ID." AND meta_key='wp_auth0_id'");
            $auth0id=$result[0]->meta_value;
           
            $remote_url = 'https://dev-ki9-psll.us.auth0.com/api/v2/users/'.$auth0id.'/roles';
            $id_token = get_user_meta( $user_id, 'auth0_id_token', true);
            $args = array(
                'headers'     => array(
                    'Authorization' => 'Bearer ' . {token} ,
                ),
            );
            $result = wp_remote_get( $remote_url, $args );
            $json = json_decode( $result['body'] );
       
            $authRole=($json[0]->name);
            echo $authRole;
       
            $u = new WP_User($user_ID );
       
       
            // Remove role
            $u->remove_role( 'subscriber' );
       
            // Add role
            $u->add_role( $authRole );
            echo "success";
    }
    else
    {
        echo "Please Login First";
    }

    }

endif;

add_action( 'wp_head', 'customroles' );

Did you find this article useful?