Can you see my routes and config with sanctum - php

Using https://laravel.com/docs/9.x/sanctum , I'm try create API application.
Generating token is ok.
But when I try to restrict my endpoint to authorized users with middleware, any check permission didn't work, endpoint is accessible for all.
In controller I tested with debug auth('sanctum')->check() - and I became true for valid token and false else.
My routes/api.php
Route::post('login', [AuthController::class, 'login']);
Route::group(['middleware' => ['auth:sanctum']], function () {
Route::post('logout', [AuthController::class, 'logout']);
Route::group([
'prefix' => 'services/{service}',
'where' => [
'service' => implode('|', array_column(ServiceEnum::cases(), 'name'))
]],
function () {
Route::get('accounts/{account}/balance', [AccountController::class, 'getBalance']);
});
});

It was my fail.
I recreate a project with new fresh laravel (something was broken with installing laravel passport) and then solve a problem with empty auth user in constructor of controller:
public function __construct(Request $request)
{
$this->middleware(function ($request, $next) {
$this->user = auth()->user();
return $next($request);
});
}

Related

laravel Auth::login($user) always return 401 Unauthorized

I'm a newbie in laravel. I work with a simple blog with angular and laravel. I use Sanctum for authorization and registration.
This is my code AuthController:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;
use Auth;
use Validator;
use App\Models\User;
class AuthController extends Controller
{
public function register(Request $request)
{
$validator = Validator::make($request->all(),[
'name' => 'required|string|max:255|unique:users',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:8'
]);
if($validator->fails()){
return response()->json($validator->errors());
}
$user = User::create([
'name' => $request->name,
'email' => $request->email,
'password' => Hash::make($request->password)
]);
$token = $user->createToken('auth_token')->plainTextToken;
Auth::login($user);
return response()
->json(['result' => 'success']);
}
public function login(Request $request)
{
if (!Auth::attempt($request->only('name', 'password')))
{
return response()
->json(['message' => 'Unauthorized']);
}
$user = User::where('name', $request['name'])->firstOrFail();
$token = $user->createToken('auth_token')->plainTextToken;
return response()
->json(['message' => 'Authorized']);
}
// method for user logout and delete token
public function logout()
{
auth()->user()->tokens()->delete();
return response()->json([
'message' => 'You have successfully logged out and the token was successfully deleted'
]);
}
}
web.php
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\MainController;
use App\Http\Controllers\StoryController;
use App\Http\Controllers\AuthController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', [MainController::class, 'home']);
Route::get('/about', [MainController::class,'about']);
Route::get('/review', [MainController::class,'review'])->name('review');
Route::post('/review/check', [MainController::class,'review_check']);
/*Route::get('/about/{id}/{name}', function ($id,$name) {
return "ID:".$id." Name:".$name;
});*/
Auth::routes();
Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home');
//Route::post('/api/saveStory', [StoryController::class,'store']);
Route::apiResource('api/saveStory', 'StoryController');
//Route::resource('/api/story', 'StoryController');
Route::post('api/register', [AuthController::class, 'register']);
//API route for login user
Route::post('api/login', [AuthController::class, 'login']);
//Protecting Routes
Route::group(['middleware' => ['auth:sanctum']], function () {
Route::post('api/user-information', function(Request $request) {
return auth()->user();
});
// API route for logout user
Route::post('api/logout', [AuthController::class, 'logout']);
});
This work fine. But when i'm success login and send post request angular to 'api/user-information' i always get error '401 Unauthorized'.
angular 2 request:
loginMethod()
{
this.http.post(this.baseUrl+"api/login", this.loginForm).subscribe(
(data:ResponseLogin)=>{
this.responseLogin=data;
if(this.responseLogin.message ==='Authorized')
{
this.router.navigate(['/user-profile']);
}
console.log("this.responseLogin.message:"+this.responseLogin.message);
},
error => console.log(error)
);
}
Route::group(['middleware' => ['auth:sanctum']], function () {
Route::post('api/user-information', function(Request $request) {
return auth()->user();
});
But when I send request 'api/user-information' using Postman, I'm success get data authorized user.
Please help me resolve this problem.
First, you have to send your authorization token too with your request. You are sending request to protected endpoint. Laravel has middleware to check if the user authenticated or not. If you try to send a request to /about it shouldn't be a problem but you are sending request to route that has protected with middleware.

Problems while setting up an existing Laravel Project in a local machine on Ubuntu 18.04

I am new to laravel but having some PHP experience.
I am facing issues while setup the an existing laravel project in my local machine.
I have followed the steps from this reference link.
I am attaching the screenshot of the error.
I have tried to check the routes/web.php file and run the controller action manually but the same error is coming.
I have done composer update but no success.
This is my routes/web.php
Route::group(['prefix' => 'admin'], function () {
Route::get('/', 'Admin\AuthController#index');
Route::get('/login', 'Admin\AuthController#index');
Route::get('[![enter image description here][1]][1]/papers', 'Admin\PapersController#index');
Route::get('/providers', 'Admin\ProvidersController#index');
Route::get('/products', 'Admin\ProductsController#index');
});
This is my routes/api.php file
$api = app('Dingo\Api\Routing\Router');
$api->version('v1', function ($api) {
$api->group(['middleware' => ['throttle:60,1', 'bindings'], 'namespace' => 'App\Http\Controllers'], function ($api) {
$api->get('ping', 'Api\PingController#index');
//$api->group(['middleware' => ['auth:api'], ], function ($api) {
$api->group(['prefix' => 'papers'], function ($api) {
$api->get('/', 'Api\PapersController#index');
$api->post('/', 'Api\PapersController#store');
$api->get('/{uuid}', 'Api\PapersController#show');
$api->put('/{uuid}', 'Api\PapersController#update');
$api->delete('/{uuid}', 'Api\PapersController#destroy');
});
$api->group(['prefix' => 'providers'], function ($api) {
$api->get('/', 'Api\ProvidersController#index');
$api->post('/', 'Api\ProvidersController#store');
$api->get('/{uuid}', 'Api\ProvidersController#show');
$api->put('/{uuid}', 'Api\ProvidersController#update');
$api->delete('/{uuid}', 'Api\ProvidersController#destroy');
});
This is my channels.php
Broadcast::channel('App.User.{id}', function ($user, $id) {
return (int) $user->id === (int) $id;
});
This is my routes/console.php
Artisan::command('dev:generate-personal-token {userId}', function ($userId) {
$user = \App\Entities\User::find($userId);
$this->info('Token for user ' . $user->name);
$token = $user->createToken('Personal Access Token')->accessToken;
$this->info($token);
})->describe('Generates a personal access token for a user');
I want to setup this project any how please someone help me out.

Laravel multiple midleware for some route

I am developing web application with laravel 5.2.
What i need is i have some off account that distinguished by role. and i have to role that can access 1 route but other role cannot access. i have browsing and i have done everything that i found like
Route::group(['prefix' => '/', 'middleware' => ['role:user_a','role:user_b']], function(){someroute}
Route::group(['prefix' => '/', 'middleware' => ['role:user_a|role:user_b']], function(){someroute}
Route::group(['prefix' => '/', 'middleware' => ['role:user_a,role:user_b']], function(){someroute}
no one work. i dont know how to make my single route can be accessed by 2 role but disable for other role
You can create a middleware named role, read more about middleware in docs here
The handle method of middleware will be as:
public function handle($request, Closure $next)
{
if (auth()->user()->role('b')) {
return redirect('home');
}
// else users of other roles can visit the page
return $next($request);
}
Then you can use it in your route file as:
Route::group(['middleware' => 'role'], function () {
// someroute
});
i think you cant do this, but you can use this way.
Route::group(['prefix'=>'/', 'middleware' =>['role:user_a','role:user_b']],function(){
Route::group(['prefix'=>'userAorB', 'middleware' =>['role:user_a|role:user_b']],function(){ Routes });
Route::group(['prefix'=>'userAANDB', 'middleware' =>['role:user_a,role:user_b']],function(){ Routes });
})

Lumen Login always return Unauthorized

Log in using the correct user name and password,but redirect to '/',always return 'Unauthorized' .what should i do?
routes.php
$app->get('auth/login', 'Auth\AuthenticationController#getLogin');
$app->post('auth/login', 'Auth\AuthenticationController#login');
$app->post('auth/register', 'Auth\AuthenticationController#register');
$app->group(['middleware' => 'auth'], function () use ($app) {
$app->get('/', 'ExampleController#index');
});

method post, put, delete route not work on laravel 5

I try test api rest on laravel 5 but I have problems with method post, put, delete.
In my route.php file I have code:
Route::group(['prefix' => 'api'], function()
{
Route::group(['prefix' => 'user'], function()
{
Route::get('', ['uses' => 'UserController#allUsers']);
Route::get('{id}', ['uses' => 'UserController#getUser']);
Route::post('', ['uses' => 'UserController#saveUser']);
Route::put('{id}', ['uses' => 'UsercCntroller#updateUser']);
Route::delete('{id}', ['uses' => 'UserController#deleteUsers']);
});
});
Route::get('/', function()
{
return 'Enjoy the test...';
});
and in UserController.php have code:
public function allUsers()
{
return 'test';
}
public function getUser($id)
{
return 'test get user';
}
public function saveUser()
{
return 'test save user';
}
public function updateUser($id)
{
return 'test update user';
}
public function deleteUsers($id)
{
return 'test delete user';
}
When I run with method get it works good but with method post, put and delete it does not work.
Why is this?
If you want to make REST APIs then use laravel's generators.
Use php artisan make:controller UserController
Laravel automatically creates RESTful controller class for you with all required methods.
Then just put one line in your routes.php
Route::group(['prefix' => 'api'], function()
{
Route:resource('user', 'UserController');
});
And that's it, now you can access get, post, put, and delete requests very easily.
If you want to see what route I should use for what method then simply fire php artisan route:list from commandline.
And because of laravel comes with built in csrf token verification middleware, you must have to pass _token with your post data request. Or either you can access those routes without csrf token verification by doing this:
Go to kernel.php in Http folder under the app directory, and comment the csrfToken line.
protected $middleware = [
'Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode',
'Illuminate\Cookie\Middleware\EncryptCookies',
'Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse',
'Illuminate\Session\Middleware\StartSession',
'Illuminate\View\Middleware\ShareErrorsFromSession',
// 'App\Http\Middleware\VerifyCsrfToken',
];

Categories