dusterio / lumen-passport

Making Laravel Passport work with Lumen
MIT License
654 stars 141 forks source link

Auth guard driver [api] is not defined Error #17

Closed rockers007 closed 2 years ago

rockers007 commented 7 years ago

when I called /oauth/token/refresh or /oauth/tokens then its throw

InvalidArgumentException in AuthManager.php line 99: Auth guard driver [api] is not defined.

paolopiccinini commented 7 years ago

Have you done the configuration point of README? How is your auth.php?

rockers007 commented 7 years ago

Yes.its solve this issue but its always say Unauthorized. in response for /oauth/token/refresh or /oauth/tokens I passed in Header Authorization:Bearer

rockers007 commented 7 years ago

Check attache unauthorized issue

paolopiccinini commented 7 years ago

are you using apache?

rockers007 commented 7 years ago

Yes ,xampp

paolopiccinini commented 7 years ago

there is another point in the README, for Apache httpd have you done it?

rockers007 commented 7 years ago

this is public/.htaccess file code

Options -MultiViews RewriteEngine On # Redirect Trailing Slashes If Not A Folder... RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)/$ /$1 [L,R=301] # Handle Front Controller... RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^ index.php [L] RewriteEngine On RewriteCond %{HTTP:Authorization} ^(.*) RewriteRule .* - [e=HTTP_AUTHORIZATION:%1]
paolopiccinini commented 7 years ago

put a log in App\Http\Middleware\Authenticate

use Illuminate\Support\Facades\Log;
Log::info('hi', ['Authorization' => $request->header('Authorization')]);

is this null? if it's null your .htaccess is not working

rockers007 commented 7 years ago

Log data [2016-12-23 10:33:09] lumen.INFO: hi {"Authorization":"Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp0aSI6IjQ2OTVkNGUyMjA0NTIwYTE2MDYyNDJjMTU0NzEzMzdkY2QyYjQyYjE4ZDQzMTcyZmVjZDQ5ZTU1MmU2NzUyZWI3ZDRhZmM1OTA3YTQyOTY3In0.eyJhdWQiOiIxIiwianRpIjoiNDY5NWQ0ZTIyMDQ1MjBhMTYwNjI0MmMxNTQ3MTMzN2RjZDJiNDJiMThkNDMxNzJmZWNkNDllNTUyZTY3NTJlYjdkNGFmYzU5MDdhNDI5NjciLCJpYXQiOjE0ODI0ODg1ODgsIm5iZiI6MTQ4MjQ4ODU4OCwiZXhwIjoxNTE0MDI0NTg4LCJzdWIiOiIiLCJzY29wZXMiOltdfQ.fiamXrLzFJ1btqYDUk9jjjpf41F7LA3B3zhYCdFyRkFReDvyVDZRU-3tXWb3zqlgEtEkDrfoc4PSBuFxfjQK6TunIf53OzFXPzTmsCvNEb-23IQhs3ewx8CwjPufOdSkSx1d1VZcUev7ETSqA7jkTMG83aGmNqF4Zsizwzs4zZv30i_uL72dMU6gkGTEnjR4bUZiIy8MtNgmgpYBeJe8SJ-GTmQylK60KWLLH4MsCeRobLkoT4ihMwGWYRomfZbJifs3JyNJe6PgsIaq5NsIYviy9dgOcHbIdsCcgEkoW18imBpP9il-Oo2LpSm_4CAKPx4_14leSwZC5ORbGZkPTiXAy_aXtaJ79pa9d9_L7MV0m9gK_r8wbBZU1iAp2X72riXaCIyN-4_0Awp2B2HFd9j5xkqP3uAYaCWF9JpNJ9y5uuthXUcMrLMNcOSbYXqvbArAHtqvKIs1vtO1G6g8Gz4agktTa9xSGP_R2xqHc3Z2u1iq3y6A2ozYycICVZHw7pM4pgc8_nEzsRq2dJMv8Ymkm03ua-xMaxrK1dDw2-9_cckdfuindpOBMz191pOe2edgvPu_cSiHB_vASMJgoucv1RR9NALZrnRXoQus1TxGXJ9uB3T0k0S6kkPfaPpig1XEACpxrIhYL7cYnHyODDAeh5hgdXAadklMjxQ2R4w"}

rockers007 commented 7 years ago

for cross checking issue I used vagrant and try on virtual machine with nginx server then also getting same result Unauthorized. POST /oauth/token its generate token ,but do not authorized it.Is there more parameter we need to pass with header ?

paolopiccinini commented 7 years ago

In the db table oauth_access_token when this token expires_at?

rockers007 commented 7 years ago

created 2016-12-23 14:54:12 expired 2017-12-23 09:24:12

paolopiccinini commented 7 years ago

In storage/ do you have oauth-private.key and oauth-public.key? when run php artisan passport:install it complains for something?

rockers007 commented 7 years ago

Yes

paolopiccinini commented 7 years ago

Do you have openssl installed? i think passport call this for generate the keys

rockers007 commented 7 years ago

Yes .in php.ini extension=php_openssl.dll

paolopiccinini commented 7 years ago

No i mean the binaries. When you run php artisan passport:install are you getting 'openssl' is not recognized as an internal or external command

rockers007 commented 7 years ago

No.its works perfectly

rockers007 commented 7 years ago

php artisan passport:install when I run this then its generate client and secret ,using these credentials I can generate token

paolopiccinini commented 7 years ago

you have two times RewriteEngine On in your .htaccess delete the second

rockers007 commented 7 years ago

Still same result

RewriteEngine On

# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [L,R=301]

# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]

RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule .* - [e=HTTP_AUTHORIZATION:%1]
paolopiccinini commented 7 years ago

ask there or try their solutions. i've finished my bullets :) https://github.com/laravel/passport/issues/47

dusterio commented 7 years ago

You can test your JWT tokens in browser on https://jwt.io/ I copy/pasted your token from the first message and the 'sub' (stands for subject) field is blank while it should contain user's numerical ID.

Therefore, something is wrong with your Passport to user model binding

rockers007 commented 7 years ago

I tested on it,its say Signature Verified

dusterio commented 7 years ago

@rockers007 that only means that encryption is applied correctly, but you have to check the embedded (decoded) data in the right pane. It shows an empty user ID for your token

rockers007 commented 7 years ago

json web tokens jwt io check this

dusterio commented 7 years ago

See "sub" field in the decoded array - this should contain a number! In your case it's an empty string

rockers007 commented 7 years ago

this is client_credentials which using client_id and client_secret. Which files I need to cross check?

kimdolong commented 7 years ago

Hi @dusterio , I have same issue with @rockers007 . jwt.io says Signature Verified. Also got empty string in "sub" field.

Please help to resolve this issue.

Thanks.

claysang commented 7 years ago

I believe this is something related to Apache configuration.

If you’ve configured Virtual Host via a standalone .conf file, you should change AllowOverride to All, this enables your .htaccess file.

But if it is None and followed by your own configuration for .htaccess optimization like this piece of code in your Virtual Host configuration:

<IfModule mod_rewrite.c>
  <IfModule mod_negotiation.c>
      Options -MultiViews
  </IfModule>

  RewriteEngine On

  # Redirect Trailing Slashes...
  RewriteRule ^(.*)/$ /$1 [L,R=301]

  # Handle Front Controller...
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteRule ^ index.php [L]
</IfModule>

Your .htaccess file still works, but there might be some conflicts.

In this case, the Authenticate middleware will always return Unauthorized..

I found it weird that my Apache server has never accessed my remote database when I tried to test an Authenticate protected route.

So if you’ve configured Virtual Host, just change to AllowOverride All, and get rid of everything else related to .htaccess like the code shown above. If you haven’t, you should probably search AllowOverride in the httpd.conf file located in /private/etc/apache2/ in macOS.

And here is my Virtual Host configuration just in case you need it:

<VirtualHost *:80>
  ServerAdmin example@example.com
  DocumentRoot "/Users/claysang/Sites/PhMK-VRDP-API/public"

  <Directory "/">
    Options FollowSymLinks
    AllowOverride None
    Order Allow,Deny
  </Directory>

  <Directory "/Users/claysang/Sites/PhMK-VRDP-API/public">
    AllowOverride All
    Order Allow,Deny
    Allow from 127.0.0.1
    Require all granted
  </Directory>

  # ErrorLog ${APACHE_LOG_DIR}/error.log
  # CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

@rockers007 @kimdolong

redboxsk commented 7 years ago

@rockers007 Hello, how did you generate token, what was your post parameters when you called POST /oauth/token?

us-22 commented 6 years ago

Same issue here. I'm always get "Unauthorized response". I double check everything. I'm using Nginx not apache.

@rockers007 did you solve it ?

us-22 commented 6 years ago

I have made some investigations. The issue happen on $request. when request arrived at Illuminate\Auth\RequestGuard. I traid to dump headers on RequestGuard constructor. the request is empty. there is not headers nor other data. it's an empty object.

/**
     * Create a new authentication guard.
     *
     * @param  callable  $callback
     * @param  \Illuminate\Http\Request  $request
     * @param  \Illuminate\Contracts\Auth\UserProvider|null $provider
     * @return void
     */
    public function __construct(callable $callback, Request $request, UserProvider $provider = null)
    {
      var_dump($request->header('Authorization')); // give NULL
        $this->request = $request;
        $this->callback = $callback;
        $this->provider = $provider;
    }

Any advice ?

us-22 commented 6 years ago

Actually it's empty before that. It's empty in Laravel\Passport\PassportServiceProvider. I tried to dump data of request before passing it to RequestGuard and it's empty. Why we have empty request in Service provider.

/**
     * Make an instance of the token guard.
     *
     * @param  array  $config
     * @return \Illuminate\Auth\RequestGuard
     */
    protected function makeGuard(array $config)
    {
        var_dump($this->app['request']->header('Authorization')); // Gives Null
        return new RequestGuard(function ($request) use ($config) {
            return (new TokenGuard(
                $this->app->make(ResourceServer::class),
                Auth::createUserProvider($config['provider']),
                $this->app->make(TokenRepository::class),
                $this->app->make(ClientRepository::class),
                $this->app->make('encrypter')
            ))->user($request);
        }, $this->app['request']);
    }
dusterio commented 6 years ago

@us-22 I think it's supposed to be this way - Request is created much later, after SPs load?

us-22 commented 6 years ago

@dusterio Yes you are right. But the issue comes even after services provider loaded. If you try to print the value of request in Laravel\Passport\Guards::user() method you will get NULL value twice. I think the first print when provider loaded and the second print when trying to authorize the user.

/**
     * Get the user for the incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  Request  $request
     * @return mixed
     */
    public function user(Request $request)
    {
      var_dump($request->header('Authorization')); // print NULL twice
        if ($request->bearerToken()) {
            return $this->authenticateViaBearerToken($request);
        } elseif ($request->cookie(Passport::cookie())) {
            return $this->authenticateViaCookie($request);
        }
    }

It's more then five hours now. I cannot find where the problem is for real.

us-22 commented 6 years ago

I solved it by making api guard resolved each time receive a request. But, However, still don't know why it's happen in first place.

All I have done is change the code in Illuminate\Auth\AuthManager@guard method from:


/**
     * Attempt to get the guard from the local cache.
     *
     * @param  string  $name
     * @return \Illuminate\Contracts\Auth\Guard|\Illuminate\Contracts\Auth\StatefulGuard
     */
    public function guard($name = null)
    {
        $name = $name ?: $this->getDefaultDriver();

        return isset($this->guards[$name])
                    ? $this->guards[$name]
                    : $this->guards[$name] = $this->resolve($name);
    }

To

/**
     * Attempt to get the guard from the local cache.
     *
     * @param  string  $name
     * @return \Illuminate\Contracts\Auth\Guard|\Illuminate\Contracts\Auth\StatefulGuard
     */
    public function guard($name = null)
    {
        $name = $name ?: $this->getDefaultDriver();

        return  $this->resolve($name);
    }

But still don't know why it's happens. Any Suggestions ?

Quix0r commented 6 years ago

Maybe a hint: I see Apache 2.2 and 2.4 (very different) authentication lines in @claysang 's config file. Which one are you using? 2.4 I presume? If that is the case, rewrite the 2.2 to "new" 2.4 way.

Hothi-Jimit commented 5 years ago

same issue face any one solve this issue?

ReubenRahul commented 4 years ago

I have a suggestion regarding the issue. first thing if you are sending the token in header you should call the $request->header('field_name') in ##AuthServiceProvider.php file maybe you are sending the token in the header and taking request as an input in AuthServiceProvider which is wrong second thing, lumen is rest API framework and these are stateless so we can't log in the user so we just need to update the api_token in every login request so match the api_token on every request so we don't need the config/auth.php file and there maybe you have defined the guard so it always through the error. Thanks