Simple question. I know how to get it in Angular, but I don't want to send the user id over the post to create a new resource because then any user can create a resource for any other user!
I see there's a getUserFromToken middleware, and I can protect a route with it, but can I get it to give me the user id of the current user?
@eablokker think of the getUserFromToken middleware acting as your Auth:attempt(), but instead of True or False will return an exception and block the request.
Sean has written this package to read work with Laravel's Authenticated user object, so once you have passed through getUserFromToken middleware you should be able to do the familiar Auth::user() and get the authenticated user.
Check this out for some more info on the Laravel side: http://laravel.com/docs/5.0/authentication#retrieving-the-authenticated-user
Also this might come in handy seeing as you are dealing with auth #103
As @mmichaelbiz has mentioned, you can use laravel's Auth::user()->id any time after JWTAuth's authenticate() method has been called in the same request lifecycle. This includes after getting through the GetUserFromToken middleware.
Hope that helps
Thank you, that works!
I dont understand. How can I get the userId of the currently authenticated user? I am new to Laravel 5.1 and I am doing this:
First Route goes through jwt-auth Middleware:
Route::group(['prefix' => 'api'], function()
{
Route::post('authenticate', 'AuthenticateController@authenticate');
// Adding JWT Auth Middleware to prevent invalid access
Route::group(['middleware' => 'jwt.auth'], function()
{
Route::resource('authenticate', 'AuthenticateController', ['only' => ['index']]);
Route::resource('movies/', 'AppsController');
});
});
Now, inside the movies controller, I only want to show the list movies that are created by that user. So I have something like this:
class AppsController extends Controller
{
public function index()
{
// the token is valid and we have find the user via the sub claim
$user = JWTAuth::parseToken()->authenticate();
$userId = $user->id;
....
// The rest of the code with query to list of movies from that userId
}
}
So basically, I am just using parseToken to get the userId. Is that a secure way to do this? What is the ideal and secure way to get the userId from token? When I read the posts above, it got me very confused.
Lastly, do I also need to add this to the _construct() method of each controller that uses parseToken() or would this not be necessary since the router is already using jwt.auth middleware?
public function __construct()
{
// Parsing the Token and throw exemptions if error
try {
if (! $user = JWTAuth::parseToken()->authenticate()) {
return response()->json(['User Not Found'], 404);
}
} catch (Tymon\JWTAuth\Exceptions\TokenExpiredException $e) {
return response()->json(['Token Expired'], $e->getStatusCode());
} catch (Tymon\JWTAuth\Exceptions\TokenInvalidException $e) {
return response()->json(['Token Invalid'], $e->getStatusCode());
} catch (Tymon\JWTAuth\Exceptions\JWTException $e) {
return response()->json(['Token Absent'], $e->getStatusCode());
}
}
Can you help me understand this please?
@Mr-Anonymous, if you are successfully passing through the middleware to the index method then seems you are almost there!
You do not need to parseToken again in your index method, the jwt.auth middleware has already checked the token, and thanks to the way Sean has written this package, the Laravel user object gets set up for you which you can access through Laravel's Auth::User().
So you do not need this:
$user = JWTAuth::parseToken()->authenticate();
Instead, try using something like:
$user = Auth::User();
Check this part of the Laravel official docs out for a little more info:
http://laravel.com/docs/5.0/authentication#retrieving-the-authenticated-user
Note: As you rightly picked up, the fact that you were having to duplicate code over and over was a definite code smell. One major benefit of middleware is to have it in one place and re-usable :)
@mmichaelbiz Thank you so much!! Yesterday, I couldnt get it to work using Auth::User(); for some reason but today after you have explained it again so clearly, I tried it again and it worked! Thank you so much for that. Now all I need to do is:
Step 1: Pass route through jwt middleware
Route::group(['prefix' => 'api'], function() {
Route::post('authenticate', 'AuthenticateController@authenticate');
// Adding JWT Auth Middleware to prevent invalid access
Route::group(['middleware' => 'jwt.auth'], function() {
Route::resource('movies/', 'MoviesController');
});
});
Step 2: And have this inside MoviesController:
use Auth;
class MoviesControllerextends Controller
{
public function index() {
$user = Auth::User();
$userId = $user->id; ....
// The rest of the code with query to list of movies from that userId
}
}
Its so easy.. I didnt need to add the extra codes inside __construct() method, no need to parsetoken using jwt again, etc.. The code is so much more cleaner.
Thank you again @mmichaelbiz for taking the time to explain it for me. Much obliged! :)
@Mr-Anonymous, Glad I could help! :) Good luck with the rest of your app!
Just FYI.. In the next version (0.6)
You will be able to use JWTAuth::user() to decouple from laravel's auth system. E.g. if you want to use Sentinel or something.
wow... thats even better. How long for 0.6? Also would Auth::User(); in the above method still continue to work or will I need to change them to JWTAuth::user() after the update?
Using Auth::user() would still work in 0.6 yes.
However if you decided to swap your authentication provider at some point then you would have to change all the references to the new one.
I'm hoping to release it soon, just a few more things to add. It's updating the wiki that will take the most of my time, as quite a few things have changed slightly.
Thanks!
Very cool :+1:
great news! Thanks @tymondesigns
how do i add data's like userID or email to the token payload?
use Auth;
class ExampleControllerextends Controller
{
public function index()
{
$userid = Auth::id();
$email = Auth::user()->email;
}
}
Can't get it to work on Lumen, returns: Method [user] does not exist. on JWTAuth::user();
Most helpful comment
@Mr-Anonymous, if you are successfully passing through the middleware to the index method then seems you are almost there!
You do not need to parseToken again in your index method, the jwt.auth middleware has already checked the token, and thanks to the way Sean has written this package, the Laravel user object gets set up for you which you can access through Laravel's Auth::User().
So you do not need this:
Instead, try using something like:
Check this part of the Laravel official docs out for a little more info:
http://laravel.com/docs/5.0/authentication#retrieving-the-authenticated-user
Note: As you rightly picked up, the fact that you were having to duplicate code over and over was a definite code smell. One major benefit of middleware is to have it in one place and re-usable :)