usefulteam / jwt-auth

WordPress JSON Web Token Authentication
https://wordpress.org/plugins/jwt-auth/
122 stars 48 forks source link

Login from a mobile app with a token as a param #27

Open jobberma opened 3 years ago

jobberma commented 3 years ago

Hello,

Thanks for the plugin. I am using the rest api in a mobile app and I want to generate a link to the website with the token as param and redirect the user to it. I wonder how can I auto login in the website with the token, is there a hook to call and pass the token to it to connect the user automatically ?

Thanks

pesseba commented 3 years ago

You can use something like this:

add_action('init',function() { 

    if(isset($_GET['token'])){

        $r = new WP_REST_Request( 'POST', '/jwt-auth/v1/token/validate');
        $_SERVER['REDIRECT_HTTP_AUTHORIZATION'] = 'Bearer '.$_GET['token'];             
        add_filter('jwt_auth_valid_token_response',function($response, $user, $token, $payload){
            if($response['success'] === true){
                wp_set_auth_cookie(  $payload->data->user->id, true, is_ssl() );                        
                wp_redirect(remove_query_arg('token',false));
                die();
            }
            return $response;
        },10,4);
        rest_do_request( $r ); //if token is valid, the user will be loggedin after that                
    }
});

So, any url with the arg: ?token=your_token, will autologin in page.

jobberma commented 3 years ago

Thank you. I will give it a try