Laravel sanctum 401 Unauthorized - laravel

I'm trying to set-up Laravel authentication using sanctum. I'm able to create a successful login function, which returns a token (bearer), but once that bearer is added to a next request using postman, a 401 unauthorized is received, and I cannot figure out why. I'm running the setup using XAMPP (127.0.0.1:8000).
Config/auth contains the following guards
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'token',
'provider' => 'users'
]
],
The config/sanctum guard is set to api.
I've added (and tested with) the following variables in the .env file;
SESSION_DOMAIN='localhost'
SANCTUM_STATEFUL_DOMAINS='localhost:8000'
Lastly, routes are set as follows;
Route::middleware('auth:sanctum')->group(function () {
Route::apiResource('friends', FriendsController::class);
});
I'm now unsure what the issue could possibly be.

Related

Laravel api route post calls work as expected, get call return blank html response

My laravel app has multiple route handlers including web, api, admin, and a new one that's misbehaving: "advisor".
The web, api, and admin routes all work as expected.
For the advisor routes POST requests work as expected, but GET calls return the client-app.blade.php html file. Not authorized or 404, just that html file.
I have the advisor routes added in the map function just like the web and api routes are:
protected function mapAdvisorRoutes()
{
Route::prefix('advisor')
->middleware('advisor')
->namespace($this->namespace)
->group(base_path('routes/advisor.php'));
}
The auth guards are setup as follows (AWS Cognito authentication is working properly on POST):
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'passport',
'provider' => 'users',
],
'admin' => [
'driver' => 'session',
'provider' => 'admins',
],
'advisor' => [
'driver' => 'cognito',
'provider' => 'users',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\User::class,
],
'admins' => [
'driver' => 'eloquent',
'model' => App\Models\Admin::class,
]
],...
The issue is that the advisor GET calls are not executing the controllers or even middleware. advisor POST calls are authenticating and working as expected. Here are some example advisor routes:
Route::group(['prefix' => 'v1'], function () {
Route::group(['middleware' => 'auth:advisor'], function () {
Route::get('get-test', function () {
// ISSUE: is not returned
return 'advisors get test';
});
Route::post('post-test', function () {
return 'advisors post test - works as expected';
});
});});
My client-side app is sending the auth and accept headers - Authorization: Bearer {token} and Accept: "application/json"
Any idea what would cause the response to an api call to be the client-app.blade.php file?
Or why would laravel treat the POST vs GET calls differently?
Thanks!
As is often the case, writing out the problem helped me realize what was causing the problem.
The order of route mapping in RouteServiceProvider.php matters.
Changing this:
$this->mapApiRoutes();
$this->mapWebRoutes();
$this->mapAdvisorRoutes();
to this solved the problem:
$this->mapApiRoutes();
$this->mapAdvisorRoutes();
$this->mapWebRoutes();
The following line in web.php was causing the index or client-app.blade.php file to be returned.
Route::get('/{any}', 'ClientAppController#index')->where('any', '.*');
So my /advisor GET request was never getting to the advisor route logic.
Phew!

Laravel basic auth not working in using jwt

I am using laravel 5.6. I tried to use JWT. That's why I made some modification followed by https://jwt-auth.readthedocs.io/en/develop/quick-start/ . Now jwt is working properly.I checked it by postman. But when I try to use laravel basic login with email and password it does not work. Thanks in advance
I also made change on
'defaults' => [
'guard' => 'api',
'passwords' => 'users',
],
...
'guards' => [
'api' => [
'driver' => 'jwt',
'provider' => 'users',
],
],
is because you are telling laravel to use jwt as driver and the laravel basic login use session as driver, if you want to have both you may need to put this
'web' => [
'driver' => 'session',
'provider' => 'users',
],
and especify the guard that you will use for the login
if (Auth::guard('web')->attempt($credentials)) {
//
}

custom auth guards in laravel 5.5

I have multiple entities in my application that need to be authenticated. So I defined multiple guards to do so:
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'customers',
],
'customer' => [
'driver' => 'passport',
'provider' => 'customers',
],
'partner' => [
'driver' => 'passport',
'provider' => 'partners',
],
'admin' => [
'driver' => 'passport',
'provider' => 'admins',
],
],
Then in my Login controllers I have the following condition:
if (Auth::guard('admin')->attempt(['email' => $email, 'password' => $password])) {
...
...
}
when I try to do so (even though it's written in the docs) I get an error telling me that "method attempt does not exist".
So I try defining the guard method on the controller (also like the docs) like this:
protected function guard()
{
return Auth::guard('admin');
}
authentication still doesn't work with the right credentials (I tried to check what guard the Auth facade was using before the attempt using dd(Auth::guard()) and it was the default web guard.
I tried removing the web guard from the default guards array in auth config. didn't work.
I also tried config:clear and rerunning the server but nothing worked!
I am out of ideas. I know that I can write my own simple login, but why reinvent the wheel, and I was following the docs to the letter. help.

Cannot use both Session and JWT Auth in Laravel 5.5

I am using Laravel 5.5 with JWT dev-develop. I have also set my auth drivers for web.
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'jwt',
'provider' => 'users',
],
],
But, the above configuration doesn't give me JWT Bearer Token. When I replace web with api, Auth::attempt($credentials) gives me JWT token instead of session.
Any ideas how to use both at the same time?
Auth::attempt($credentials) override actual method when you using JWT and giving you JWT Token.
You can also check this function in tymon\src\JWTAuth.php
You can both as use default guard as as web and use
JWTAuth::attempt($credentials) to get JWT Token

Laravel oauth2 unauthorized redirect

I am trying to implement oath2 using laravel and passport. however i have managed to make everything up & running. But the problem i am facing is when token expires or without token the url redirects to the laravels login page. I was expecting an unauthorized error message with a status code 401.
oauth2 is implemented using passport. I think laravels default auth is creating the problem.
this is my code in routes
Route::group(['middleware' => 'auth:api'], function () {
Route::get('users', "\App\Http\Controllers\UserController#getUsers");
Route::post('permission/add', "\App\Http\Controllers\UserController#createPermission");
Route::get('permissions', "\App\Http\Controllers\UserController#getPermissions");
Route::get('permission/{param}', "\App\Http\Controllers\UserController#getPermission");
Route::post('role/add', "\App\Http\Controllers\UserController#createRole");
Route::get('roles', "\App\Http\Controllers\UserController#getRoles");
Route::get('user/profile', function () {
// Uses Auth Middleware
});
});
My output when unauthorized
my config/auth.php
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'passport',
'provider' => 'users',
],
],

Resources