Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Get user alway return null #87

Closed
kieuminhcanh opened this issue Sep 16, 2016 · 19 comments
Closed

Get user alway return null #87

kieuminhcanh opened this issue Sep 16, 2016 · 19 comments

Comments

@kieuminhcanh
Copy link

I got access_token and send request to get user but alway return

{
"error": "Unauthenticated."
}

I readed on the internet and some people told me change api.php like that

Route::get('/user', function (Request $request) {
    return $request->user();
})->middleware('auth:api');

to

Route::get('/user', function (Request $request) {
    return $request->user();
});

Then it does not display error again but return null value. I can't get user.

@tonoman3g
Copy link

how do you send the access_token?

if you remove the middleware auth:api, it won't be able to identify the user, of course you will get null

you should send it as a header Authorization: Bearer {{access token}}

@ilvalerione
Copy link

ilvalerione commented Sep 18, 2016

I had the same error. I solved it by setting a deadline.

Passport::tokensExpireIn(Carbon::now()->addDays(15));

and it worked

@kieuminhcanh
Copy link
Author

Solved
I don't know why but when i checked the token_key on JWT debugger then the EXP value return 0. And I need to change the expire. Thanks @ilvalerione
Passport::tokensExpireIn(Carbon::now()->addDays(15));

@lukepolo
Copy link

What's the reasoning of adding a expired date , sounds like code smell

@alexjose
Copy link

Default JWT generate is with expiry set to the same time of creation. So this cannot be used out of the box.

As per the docs the default JWT is a long lived token, but this seems to be not working.

@alexjose
Copy link

This is because of the 32bit PHP and the 100 Year validity for the default tokens.

See this #47

@balakan
Copy link

balakan commented Oct 3, 2016

With the Authorization: Bearer {{access token}} header add another with a value of Accept => application/json. It worked for me!

@codymoorhouse
Copy link

For me: I had to fix this by going into my config/auth.php and set the 'guard' => 'api'. (it was web before)


    'defaults' => [
        'guard' => 'api',
        'passwords' => 'users',
    ],

@lukepolo
Copy link

lukepolo commented Oct 12, 2016

Found out, if you are upgrading from 5.2 to 5.3 you need to use

'auth' => \Illuminate\Auth\Middleware\Authenticate::class,

Instead of the Authenticate class that was in your app middleware before

@dreferreira
Copy link

dreferreira commented Oct 19, 2016

I've done every single adjustment listed here and am still having issues with getting the user.
I've:

  • Set an expiration in Auth Service Provider
  • Removed and reapplied the auth:api middleware call in routes (multiple times resulting in null returned values)
  • Tried changing the defaults driver in config/auth.php to 'api' from 'web'
  • Ensured the Kernel's classes are properly located
  • Added the Accept header with value of application/json
  • Ensured the default laravel_session cookie was being properly sent in
  • Ensured I was sending the access token with header of Authorization Bearer access_token_here
  • Ensured that I was hitting the right route

However I still keep getting unauthorized errors returned. Is there ANYTHING else I've missed here? I'm sort-of at a loss.

@miladnit
Copy link

I have same Issue
laravel 5.3

Passport::tokensExpireIn(Carbon::now()->addDays(7));
Passport::refreshTokensExpireIn(Carbon::now()->addDays(14));

@gocanto
Copy link

gocanto commented Nov 11, 2016

I have the same issue here. Here is my request header,

Accept:application/json, text/plain, */*
Accept-Encoding:gzip, deflate, sdch
Accept-Language:en-US,en;q=0.8,es;q=0.6
Connection:keep-alive
Cookie:remember_web_59ba36addc2b2f9401580f014c7f58ea4e30989d=eyJpdiI6IlM4N0tuZE9vcTRQQXltVWJsMDJnRkE9PSIsInZhbHVlIjoiVkpNb2J0dFZuWkpVRmNYakVxcytKaDR4emJzMEJVNDhKb2FBNkNJN0M4bz0iLCJtYWMiOiIxMmIwNWE3ZThkN2ZmMDczNzA2OGM4NzRhZjIzZWRhYzM3NjgzMjFjNDY0NzlkZWQzZWVkOWJhNmZjNWIwZWVlIn0%3D; laravel_token=eyJpdiI6ImpzeTBYSWpqNWRuOXpWZnFlTFUyVEE9PSIsInZhbHVlIjoicnVSWGtqK1FkRnlPdTJKTElzdUR1bkx1T3VNUFBzMGV3TGRrTzFJTlVxVk56eURCWXprbURzWHJcL3dYXC9jUEh2RTRTcE42S0dJSGR6SVdJbXNzdng5RXltV25xeGcydjZuTTBNMFBYWlV4MVwvZGZrKzVNckx1N003c0N4ZlRsRTVJRE1Yb283XC8zQVo4NjA1dk5cLzFTME5SOEF0YUx5bWQ3SERGTXZ0bWZNU3I2UElpZ0I1QlwvMFk0SzRJU3U0ZFwvcVdxWlZzZVVLWlVXMVIzdnh3ZkJwb3pXOVZ6OTBUSUlzT2o5OGZjdzZSbWtBYVFHUHNDcVVvR3hNYnl3dzlZblFPRTVITXdnMHRMbDE0R050VERDT25RPT0iLCJtYWMiOiIzNWRhODljM2Y3MmEyY2NkNDA0YzI0NmQ2OWI0MDVkOTczYWQ4MzYyMjUzNWEzNGVhOTRmMTJkODE1ZDNlZjNiIn0%3D; XSRF-TOKEN=eyJpdiI6Ijh2SzdEOFFsOGloV0grZzZNSnR1N2c9PSIsInZhbHVlIjoiQXpidnNjZ05qcTJDMnJkOHhjSzc0RGRSa3BYQVpDd0l6N0I5M093V2lWeitJaTVoSjU5VTJCV2p4SDdkZW5laHhRYmlsMytJWHRlUGJYOUgrTkJMXC9RPT0iLCJtYWMiOiJjMjZjOTM0Zjc0MzBlMTQ2NTA0OWI5ZDZiMDJjYzA1YWVhMWU4NTYyZDhkMjZmNjYyYTU3YzBjNWIwYmU3NTE1In0%3D; laravel_session=eyJpdiI6IlJxbVlReXBlTmtoK2N1SUFIVFwvcVwvdz09IiwidmFsdWUiOiJCQW5cL3NUVCttMUtWYlF2a20rSm40RGc2a3kySFVucjIxNFwvbmRVMWk2UlhEVTRFb05NTjl6d1hXWWZBT2hqUWhZQVVzdmZnYnF1T2RBXC94dWFVUVVmQT09IiwibWFjIjoiOWJiNzQ3ZmUwZThkYzlmODUyOGE2Yjc0ZjIzZTMzNTY1OWU1YjM0ZmViZmI5ZWIyODQzZTIwMTliMTA2MWJkMSJ9
Host:noplaceleft.dev
Referer:http://noplaceleft.dev/dashboard/users/profile
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36
X-XSRF-TOKEN:eyJpdiI6Ijh2SzdEOFFsOGloV0grZzZNSnR1N2c9PSIsInZhbHVlIjoiQXpidnNjZ05qcTJDMnJkOHhjSzc0RGRSa3BYQVpDd0l6N0I5M093V2lWeitJaTVoSjU5VTJCV2p4SDdkZW5laHhRYmlsMytJWHRlUGJYOUgrTkJMXC9RPT0iLCJtYWMiOiJjMjZjOTM0Zjc0MzBlMTQ2NTA0OWI5ZDZiMDJjYzA1YWVhMWU4NTYyZDhkMjZmNjYyYTU3YzBjNWIwYmU3NTE1In0=

@gocanto
Copy link

gocanto commented Nov 11, 2016

Well, I just fixed mine doing this.

JS

axios.defaults.headers.common['X-CSRF-TOKEN'] = 'laravel token';

Routes

Route::get('users/profile', 'Users\UsersApiController@index')->middleware('auth:api');

The issue here is, doing all this I am not making use of passport.

I relly need some help! thanks

@bruno-fernandes
Copy link

@lukepolo solution solved the problem.

On Kernel.php file use:

'auth' => \Illuminate\Auth\Middleware\Authenticate::class,

instead of

'auth' => \App\Http\Middleware\Authenticate::class,

Also added the Unauthenticated Method to App\Exceptions\Handler class, otherwise an exception will be thrown if the user is not authenticated. See instructions in the upgrade documentation page: https://laravel.com/docs/5.3/upgrade

/**
 * Convert an authentication exception into an unauthenticated response.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Illuminate\Auth\AuthenticationException  $exception
 * @return \Illuminate\Http\Response
 */
protected function unauthenticated($request, AuthenticationException $exception)
{
    if ($request->expectsJson()) {
        return response()->json(['error' => 'Unauthenticated.'], 401);
    }

    return redirect()->guest('login');
}

@iraklisg
Copy link

iraklisg commented Nov 22, 2016

@bruno-fernandes @lukepolo I am already using 'auth' => \Illuminate\Auth\Middleware\Authenticate::class, but I still get null as a response when hitting /api/user. This is my route:

Route::get('/user', function (Request $request) {
    return $request->user();
})->middleware('auth:api');

Note that using return Auth::guard('api')->user(); instead of return $request->user(); successfully returns the user that issue the Personal Access Token

EDIT: Strange but I found out that my api returned successfully the current logged in user's details.

Route::get('/user', function (Request $request) {
    return $request->user();
})->middleware('auth:api');

The problem is that I was not able to conole.log() later the response through a Vue component

export default {
        name: "Home",
        mounted() {
            this.$http.get('/api/user').then(response => {
                alert(response.data);
            });
        }
    }

Digging a little bit more into my problem, I found out that if I compile my assets running gulp, the response can be successfully logged in my console. However, If I compile my assets using gulp --production I am getting no output .

It seems that gulp --production strip console.log out automatically.....

@arctic-ice-cool
Copy link

Shouldn't this be in the 5.2 > 5.3 upgrade instructions?

#87 (comment)

@shamsuljewel
Copy link

@lukepolo thanks a lot even after 2 years this helped me adding new 'auth.api' => \Illuminate\Auth\Middleware\Authenticate::class, in the kernel.php

as i am already using 'auth' for sentinel so i named it auth.api and in the route used it like auth.api:api
and that worked for me

@Leleking
Copy link

I might be late here but I faced the same problem when I created my own personal access token thus creating my own login method. Even though I was getting an access token the user was still not logged in. I solved it with Auth::attempt( $login_credentials)

    $login = $request->validate([
        'email' => 'required|email',
        'password' => 'required'
    ]);
    if( !Auth::attempt( $login ) ) {
        return response(['message'=> 'Invalid login credentials']);

    }
    $user = Auth::user();
    if($user->status == "Active" && $user->isVerified == "Verified") {
        $accessToken = $user->createToken('authToken')->accessToken;
        return response(['user'=> Auth::user(), 'access_token' => $accessToken]);
    }

    return response()->json(["errors"=>"Account inactive or not verified"],401);

Now $request->user() works

@ramkumawathis
Copy link

i have 2 type of users.

  1. Login user
  2. Guest user
    I am using passport api with laravel8.
    I have news curd api with comment. The route are : List all news api, Show single news detail api and user post comment api.
    My question:-
    -> Login user have all access with access_token.
    -> But guest user access only news list and single detail api.

How can i access guest news list api and single detail. For security need to add token.

Guest access apis with token.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests