Guard is not working
Closed this issue · 1 comments
tim-kilian commented
Hello,
when I try to get a route without Authorization information it is responding normally to my request. I've protected it with the App\Http\Middleware\Authenticate::class
middleware, but it is not working.
app.php
$app->configure('auth');
$app->withFacades();
$app->withEloquent();
$app->routeMiddleware([
'auth' => App\Http\Middleware\Authenticate::class,
'client' => Laravel\Passport\Http\Middleware\CheckClientCredentials::class,
]);
$app->register(Laravel\Passport\PassportServiceProvider::class);
$app->register(Dusterio\LumenPassport\PassportServiceProvider::class);
$app->router->group([
'namespace' => 'App\Http\Controllers',
'middleware' => 'auth',
], function (Laravel\Lumen\Routing\Router $router) {
$router->get('/user', 'AuthController@currentUser');
});
AuthController.php
public function currentUser()
{
return [
'success' => true,
];
}
Authenticate.php
public function handle($request, callable $next, $guard = null)
{
if ($this->auth->guard($guard)->guest()) {
return response('Unauthorized.', 401);
}
return $next($request);
}
AuthTest.php
public function test_user_access_denied() {
$this->get('/user', [
'Accept' => 'application/json',
])->seeStatusCode(401);
}
subangkit commented
Hi @tim-kilian,
- Make sure you has set right configuration for config/auth.php
<?php
return [
'defaults' => [
'guard' => 'api',
'passwords' => 'users',
],
'guards' => [
'api' => [
'driver' => 'passport',
'provider' => 'users',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => \App\Models\User::class
]
]
];
- Set this functions in your app/Models/User.php
class User extends Model implements AuthenticatableContract, AuthorizableContract
{
use Authenticatable, Authorizable, HasFactory, HasApiTokens;
...
/**
* Find the user instance for the given username.
*
* @param string $username
* @return \App\Models\User
*/
public function findForPassport($username)
{
return $this->where('name', $username)->first();
}
// link every access_token with user_id
public function getAuthIdentifier() {
return $this->attributes['id'];
}
// custom password check, make sure this hash as same as you creating password for new user
public function validateForPassportPasswordGrant($password) {
return Hash::check($password, $this->attributes['password']);
}
// bypass retrieveById
public function retrieveById($identifier) {
return true;
}
...```