find id of user with JWT token in laravel - laravel

In my API after the user registers, a token is created with this code :
$token = JWTAuth::fromUser($user);
when i use dd($token) , returns this :
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC8xMjcuMC4wLjE6ODAwMFwvYXBpXC9sb2dpbiIsImlhdCI6MTYyNjgxNDM2NCwiZXhwIjoxNjI2ODE3OTY0LCJuYmYiOjE2MjY4MTQzNjQsImp0aSI6Imd3eDZnVzNGTGN4MzlMekIiLCJzdWIiOjQsInBydiI6IjIzYmQ1Yzg5NDlmNjAwYWRiMzllNzAxYzQwMDg3MmRiN2E1OTc2ZjcifQ._m-7tojFaupUbAibDUbLJm6BeuFVL_etdFlwj0h5664
so how can i find the id of user without entering this token in authorization of postman ?

Simple, use https://jwt.io
In "sub" (subject) you will see the user id.
Read more about jwt tokens

whatever token string you get from request headers, use that to create an object of Token class like this
$token = new Token(token_string);
After, use that $token inside of JWTAuth class like this
JWTAuth::setToken($token);
Finally call getPayload method of JWTAuth class to get actual data.
JWTAuth::getPayload($token)->get('sub')
Full code
use JWTAuth;
use Tymon\JWTAuth\Token;
...
...
// generate token
$user = \App\User::find(1);
$tokenString = JWTAuth::fromUser($user);
// decode token to get actual data
$token = new Token($tokenString); // here you use header insted of $tokenString
JWTAuth::setToken($token);
$subject = JWTAuth::getPayload($token)->get('sub');

Related

How to genarate JWT token using both environment variable's and user model

jwt token works perfectly with user model.
jwt tokens works perfectly with environment variable's.
Using both scenario 1 and 2 in one system.
I want to generate jwt token using environment variable's email and password which are not stored in user table and also I don't want to change the existing flow of jwt token.
I want to generate JWT token for master user who is not part of system and his email and password are not stored in database.
Is there any way to generate jwt token using both user model and environment variable's??
I have got the solution.
We can create token using JWT::encode.
Here the sample code is :
$customClaims = ['foo' => 'bar', 'baz' => 'bob'];
$factory = JWTFactory::customClaims($customClaims);
$payload = $factory->make();
$token = JWTAuth::encode($payload);

Laravel Personal Access Tokens

Is there a way to re-view the accessToken itself after it's been created?
Looking at the code below you can see that $token holds the accessToken for the "Test Token" client and that's fine it works as expected, however, say the user forgot that $token is there a way to display it for the user again?
// user can manually create personal access token
// by using the following
$user = Auth::user();
$token = $user->createToken('Test Token')->accessToken;
// this works fine, however, I want to allow the user to edit / re-view these personal access
// tokens when he/she wants
// I'm able to delete or revoke these tokens but how can I vew the access token again?
// I tried the following:
foreach (Auth::user()->tokens as $token)
{
// but none of these give back that access token??
// halp!
// print "accessToken: " . $token->accessToken;
// print "token: " . $token->token;
}
If I understood correctly: you can store the tokens in DB. If there is more tokens per user you can store it in json format.

Laravel crsftoken routing

I have some troubles with the crsf_token() in laravel. I create a URL to send to the user with the token and if they click this unique link the post will set the token to NULL.
Here my sample code:
//get token from database
$getDataUserToken = $subject->lists('token');
// send the token to email user (unique token)
#foreach ($token as $toke){{ URL::to('/extend/verify', array($toke)) }}#endforeach
This code will generate: www.example.com/extend/verify/1234123TOKENHERE2313213123
Now I want if user clicks on this link that the token sets to null.
I tried this:
Route::get('/extend/verify/{$toke}', 'SubjectController#confirm');
But when I do this I get an error that says: throw new NotFoundHttpException;
So the url is not found and I don't know how to get that url token and send it to my controller to do some stuff with that.
the laravel route parameters not use "$".
this is a correct use:
Route::get('/extend/verify/{toke}', 'SubjectController#confirm');

Error refreshing the OAuth2 token, message: '{ "error" : "invalid_grant" }'

I am working with this package Analytics-Laravel 4 for google analytics and I have follower all of the steps correctly. When I try to get the site id for example, I face this error:
Error refreshing the OAuth2 token, message: '{ "error" : "invalid_grant" }'
I have double checked all of the configurations, client id, service_account and private key but the error still occurs.
Anything else I should try to check that maybe would solve this issue?!
I didn't use this package before, I'm using google-api-php-client, but anyways, this error occurs if you don't set the refresh token.
You should know that you need to have the access token ONLY once. You also need to set the access type to be offline, which will provide you with a refresh token that you will use to automatically get a new access token without getting a new code every time your access token expires.
In google's console, I created a Client ID for web application. Make sure you set the redirect URI to your web page where you will receive the code and will extract the access token using that code.
Here is a code example using google-api-php-client, I hope it will help:
You need to run the following code only once, and retrieve and store the access token.
<?php
require_once('google-api-php-client-master/src/Google/Client.php');
session_start();
$client = new Google_Client();
$client->setApplicationName('APP_NAME');
$client->setClientId(YOUR_CLIENT_ID);
$client->setClientSecret('YOUR_CLIENT_SECRET');
$client->setRedirectUri('YOUR_REDIRECT_URI');
$client->setDeveloperKey('YOUR_DEV_KEY');
$client->setScopes(array('https://www.googleapis.com/auth/analytics.readonly'));
$client->setAccessType("offline");
// Step 1: Create an auth url
if (isset($_GET['ref']) && $_GET['ref'] == "1") {
$authUrl = $client->createAuthUrl();
return Redirect::to($authUrl);
}
// Step 2: The user accepted your access now you need to exchange it.
if (isset($_GET['code'])) {
$client->authenticate($_SESSION['code']); //Authenticate the client
$token = $client->getAccessToken(); //Get the access token
var_dump($token); //Store the token in your DB or config file
die();
}
?>
After getting your access token from the code above (which should contain a refresh token), store it in your DB or a config file.
Now the following code should authenticate the client and refresh the access token when it expires via the getAccessToken function
<?php
require_once('google-api-php-client-master/src/Google/Client.php');
require_once('google-api-php-client-master/src/Google/Service/Analytics.php');
$client = new Google_Client();
$client->setApplicationName('APP_NAME');
$client->setClientId(YOUR_CLIENT_ID);
$client->setClientSecret('YOUR_CLIENT_SECRET');
$client->setRedirectUri('YOUR_REDIRECT_URI');
$client->setDeveloperKey('YOUR_DEV_KEY');
$client->setScopes(array('https://www.googleapis.com/auth/analytics.readonly'));
$client->setAccessType("offline"); //Make sure the access type is offline to get a refresh token
$config = CoreConfig::find(1); //Getting the first record from the config table
$client->setAccessToken($config->google_access_token); //Retrieve the access token that you stored and set it to the client object
//Check this the token is expired
if($client->isAccessTokenExpired()) {
$token = json_decode($config->google_access_token, true); //Get the token stored, and convert JSON to array
$client->refreshToken($token['refresh_token']); //Set the refresh token
$newtoken = $client->getAccessToken(); //Call the getAccessToken() function to get a new access token for you
$config->update(array('google_access_token' => $newtoken)); //Store the new token in your DB
}
if ($client->getAccessToken()) {
$analytics = new Google_Service_Analytics($client);
//Do something with the $analytics object
}
?>
It could be the server time. If the local time on your server is out of sync with google's oAuth server even by a few seconds you'll get that error message.
You can check the time by running "date" in the console.
Running "sudo ntpdate ntp.ubuntu.com" solved it for us.

In codeigniter, How to get the token returned from google login as parameter to controller?

I am working with AuthSub to view portfolios of google finance api on codeigniter framework.
after successful login of google it redirects to the url we provide.
I have provided url like: www.finance.mysite.com/google/token/
google will append its token like:
www.finance.mysite.com/google/token/?token=1/gyXbtvKT4XaIuUIhEBAsuxyDgATMDk3ztAG3MocNkKI
How can I get it inside a function token() inside google controller.
I don't know that you have control over "how" it gives it to you. For a controller parameter, you'll need to redirect after the Auth callback "gives" you the token. This is probably unnecessary though, as you can simply grab it out of the query string.
<?php
$token = $this->input->get('token');
if ($token)
{
// Option 1: redirect to a controller action that
// takes the token as the parameter
redirect('/google/token/'.$token);
// Option 2: do something directly with the token
// right now (why bother redirecting?)
var_dump($token);
exit;
}
die('Access token? We didn\'t get no access token!');
?>
Storing the token in the session or database is an alternative to the redirect, but the redirect would how to "get the token as parameter to controller" like you ask.
Just extract the token, and route it to controller of your choice.
You can extract the params like this
$params = "http://www.finance.mysite.com/google/token/?token=1/gyXbtvKT4XaIuUIhEBAsuxyDgATMDk3ztAG3MocNkKI";
$parsed = parse_url($params);
$pieces = explode("=", $parsed['query']);
$searchIndex = array_search("token", $pieces);
if($searchIndex) {
$token = $pieces[$searchIndex+1];
//now use it as you need
redirect("controller/google/$token");
}
Note: The code above will only work, if there is only single parameter on the url, or else not.

Resources