How to create verification code session between controllers - laravel

I have 2 controller which are Verify Controller and Register Controller. To access the register page, I have added a custom middleware where super admin need to enter a code to access it which means only super admin have access to the registration form.
I have build the verification code form and inside the Verify controller, I have hard coded a code to test if user entered the same code. I also create a session variable on Verify Controller to store if success.
How my session works
If I go to superadmin/register then store session as empty.
If it matches, store session value as success.
Checking session
Finally check the session on middleware using if else condition.
If empty, redirect to verify page.
If not empty, redirect to register page and proceed to register new super admin.
The problem is, I still can directly access superadmin/register. It does not redirecting to verify page.
Verify Controller
<?php
namespace App\Http\Controllers\Auth;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Session;
class SuperAdminVerifyController extends Controller
{
public function showVerifyForm()
{
return view('auth.superadmin-verify');
}
public function verify(Request $request)
{
// Validate the form data
$this->validate($request, [
'verifycode' => 'required'
]);
$code = "123";
$verifycode = $request->verifycode;
if ($code != $verifycode)
{
return redirect()->back()->with('status', 'Invalid Code');
}
else
{
Session::put('session_val', 'success');
return redirect()->route('superadmin.register');
}
}
}
Register Controller
<?php
namespace App\Http\Controllers\Auth;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;
use Session;
use App\Superadmin;
class SuperAdminRegisterController extends Controller
{
public function __construct()
{
$this->middleware('checksessionvar');
}
public function showRegisterForm()
{
return view('auth.superadmin-register');
}
protected function register(Request $request)
{
$this->validate($request, [
'name' => 'required',
'email' => 'required|email',
'password' => 'required'
]);
if (Superadmin::where('email', '=', $request->email)->exists())
{
return redirect()->route('superadmin.register')->with('status', "Email already exists");
}
else
{
$admin = new Superadmin;
$admin->name = $request->name;
$admin->email = $request->email;
$admin->password = Hash::make($request->password);
$admin->save();
Session::flush();
return redirect()->route('superadmin.register')->with('status', "Successfull added to database. Please go to Super Admin login page.");
}
}
}
Custom Middleware
<?php
namespace App\Http\Middleware;
use Closure;
use Session;
class CheckSessionVariable
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
$getSession = Session::get('session_val');
if($getSession == null)
{
return redirect()->route('superadmin.verify');
}
else if($getSession == "success")
{
return $next($request);
}
}
}
Routes
Route::prefix('superadmin')->group(function() {
Route::get('/verify', 'Auth\SuperAdminVerifyController#showVerifyForm')->name('superadmin.verify');
Route::post('/verify', 'Auth\SuperAdminVerifyController#verify')->name('superadmin.verify.submit');
Route::get('/register', 'Auth\SuperAdminRegisterController#showRegisterForm')->name('superadmin.register');
Route::post('/register', 'Auth\SuperAdminRegisterController#register')->name('superadmin.register.submit');
Route::get('/login', 'Auth\SuperAdminLoginController#showLoginForm')->name('superadmin.login');
Route::post('/login', 'Auth\SuperAdminLoginController#login')->name('superadmin.login.submit');
Route::post('/', 'CompanyController#store_company')->name('superadmin.company.submit');
Route::get('/', 'SuperAdminController#index')->name('superadmin.dashboard');
Route::get('/logout', 'Auth\SuperAdminLoginController#logout')->name('superadmin.logout');
});
Kernel.php
<?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
/**
* The application's global HTTP middleware stack.
*
* These middleware are run during every request to your application.
*
* #var array
*/
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
];
/**
* The application's route middleware groups.
*
* #var array
*/
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
// \Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'api' => [
'throttle:60,1',
'bindings',
],
];
/**
* The application's route middleware.
*
* These middleware may be assigned to groups or used individually.
*
* #var array
*/
protected $routeMiddleware = [
'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'checksessionvar' => \App\Http\Middleware\CheckSessionVariable::class,
];
}

You could probably cut down on a lot of the steps you're currently doing and use a Gate in the controller. The scenario you describe is similar to the example provided in the documentation:
Gate::before(function ($user, $ability) {
if ($user->isSuperAdmin()) {
return true;
}
});

Related

Laravel localization middleware takes a long time to determine current language and times out

So, I have a bit of a weird issue. I have a localization middleware
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use URL;
class setLocale
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle(Request $request, Closure $next)
{
URL::defaults(['locale' => $request->segment(1)]);
return $next($request);
}
}
This is included in the kernel like so.
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
-------> \App\Http\Middleware\setLocale::class,
\Illuminate\Session\Middleware\StartSession::class,
\Laravel\Jetstream\Http\Middleware\AuthenticateSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
};
Then in my web.php file I have some routes that are localized
Route::get('/', function () {
return redirect(app()->getLocale());
});
Route::group(['prefix' => '{locale}', 'where' => ['locale' => '[a-zA-Z]{2}']], static function () {
Route::get('/', static function () {
return view('auth.login');
})->name("home");
Route::get('/register', static function () {
return view('auth.register');
})->name("signup");
});
When a fresh user comes the the website they wil hit the / route, this takes a loooong time to determine the users locale, it times out due to too many redirects and 1 second after it redirects to the correct locale.
Any reason why it times out, and then redirects to the correct locale anyway ?

Laravel redirected you too many times error

I am trying to implement a simple role-based authentication system in Laravel 7, where I have an additional field on user table named 'role' of integer type, which can have two values - 0 for general users and 5 for the admins.
Any logged in user should be able to access the '/railway' page. Only admins should be able to access the '/admin' page. Admins should also be able to access the '/railway' page.
I am following this article and getting 'too many redirect' error: https://dev.to/kaperskyguru/multiple-role-based-authentication-in-laravel-30pc
Edit:
Sorry forgot to mention!
Everything is working perfectly for the non-admin users. They are being redirected to the '/railway' page after logging in alright, and also being redirected to this page if they try to access the '/admin page'.
The error is happening for the admins only. It is redirecting them to the '/admin' page after logging in alright, but showing the 'too many redirection' error. But admins can access the '/railway' page which is perfect.
Edit-3
I've added this on a git repository, if anyone is interested to reproduce the issue: https://github.com/rawhasan/laravel-auth-bug.git
Here is what I've done so far:
web.php
Route::get('/', function () {
return view('welcome');
});
Auth::routes();
Route::get('/railway', 'RailwayController#index')->name('railway');
Route::get('/admin', 'AdminController#index')->name('admin')->middleware('admin');
Middleware Admin.php
namespace App\Http\Middleware;
use Auth;
use Closure;
class Admin
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if (!Auth::check()) {
return redirect()->route('login');
}
if (Auth::user()->role == 0) {
return redirect()->route('railway');
}
if (Auth::user()->role == 5) {
return redirect()->route('admin');
}
}
}
Kernel.php
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
'admin' => \App\Http\Middleware\Admin::class,
];
HomeController.php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class HomeController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function index()
{
return view('railway');
}
}
AdminController.php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class AdminController extends Controller
{
public function index()
{
return view('admin.admin');
}
}
Edit - 2
I also have this on the LoginController.php
use Auth;
class LoginController extends Controller
{
use AuthenticatesUsers;
protected $redirectTo;
public function redirectTo() {
if (Auth::user()->role = 5) {
$this->redirectTo = '/admin';
return $this->redirectTo;
} else {
$this->redirectTo = '/railway';
return $this->redirectTo;
}
}
public function __construct()
{
$this->middleware('guest')->except('logout');
}
}
Any help sorting out the issue would be appreciated!
So in both user roles it requires authentication which means you could wrap your routes under default laravel auth middleware for that:
Route::middleware(['auth'])->group(function () {
Route::get('/railway', 'RailwayController#index')->name('railway');
Route::get('/admin', 'AdminController#index')->name('admin')->middleware('admin');
});
And your middleware should look something like:
use Auth;
use Closure;
class Admin
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if (Auth::user()->role == 0) {
return redirect()->route('railway');
}
if (Auth::user()->role == 5) {
return redirect()->route('admin');
}
return $next($request);
}
}
Fixed this with the help from another source. Removed the following code from the Admin Middleware and it worked perfectly:
if (Auth::user()->role == 5) {
return redirect()->route('admin');
}
Since I am redirecting the admins from the loginController, this redirect from the middleware was making the conflict.
I've also kept this code in web.php as suggested by Leo:
Route::middleware(['auth'])->group(function () {
Route::get('/railway', 'RailwayController#index')->name('railway');
Route::get('/admin', 'AdminController#index')->name('admin')->middleware('admin');
});
Thanks for the answers everyone!
Include the following value in config/admin.php file in the end of auth key. after 'remember' key.
// Redirect to the specified URI when user is not authorized.
'redirect_to' => 'auth/login',
// The URIs that should be excluded from authorization.
'excepts' => [
'auth/login',
'auth/logout',
'_handle_action_',
'auth/forgot-password',
'auth/reset-password'
],

User authentication in laravel using middleware

I have a question about the built in user authentication functionality in laravel. I got the authentication part to work but it doesn't seem like a user is stored in the session.
Admin Controler Code:
<?php
namespace App\Http\Controllers\Admin;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Validator, Input, Redirect;
use DB;
use Session;
class AdminController extends Controller
{
public function index(Request $request)
{
if(isset($_POST['submit'])){
$v = Validator::make($request->all(), [
'email' => 'required',
'password' => 'required',
],
[
'required' => 'This field is required.'
]);
if ($v->fails())
{
$messages = $v->messages();
return redirect()->back()->withErrors($v)->withInput();
}
else
{
$email = $request->input('email');
$pass = $request->input('password');
$whereData = [
['email',$email],
['password',md5($pass)]
];
$res = DB::table('tbl_admin_users')->where($whereData)->get();
if(!empty($res)){
$userid=$res[0]->id;
$fname=$res[0]->fname;
Session::put('userid', $userid);
Session::put('fname', $fname);
return Redirect('admin/dashboard-listing');
}
else
{
Session::flash('message', 'Email/Password is invalid!');
Session::flash('alert-class', 'alert-danger');
return Redirect('admin/login');
}
}
}
else{
return view('admin.admin-login');
}
}
public function logout()
{
Session::flush();
return Redirect('admin/login');
}
}
Middleware Authentication.php code:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class Authenticate
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #param string|null $guard
* #return mixed
*/
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->guest()) {
if ($request->ajax() || $request->wantsJson()) {
return response('Unauthorized.', 401);
} else {
return redirect()->guest('login');
}
}
return $next($request);
}
}
AuthController I have:
<?php
namespace App\Http\Controllers\Auth;
use App\User;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
class AuthController extends Controller
{
/*
|--------------------------------------------------------------------------
| Registration & Login Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users, as well as the
| authentication of existing users. By default, this controller uses
| a simple trait to add these behaviors. Why don't you explore it?
|
*/
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
/**
* Where to redirect users after login / registration.
*
* #var string
*/
protected $redirectTo = '/';
/**
* Create a new authentication controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware($this->guestMiddleware(), ['except' => 'logout']);
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|min:6|confirmed',
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return User
*/
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
}
Route after correct details and login page route:
Route::get('/admin/dashboard-listing',array('uses'=>'Admin\AdminDashboardController#index'));
After logout redirect route:
Route::get('/admin/login',array('uses'=>'Admin\AdminController#index'));
My question is that how can i use middleware in this code. because
after logout i can easily access the url .back button is also worrking
i want laravel user authentication through middleware ..
You need to manually login user with auth()->login():
$res = DB::table('tbl_admin_users')->where($whereData)->first();
if(!empty($res)) {
$userid = $res[0]->id;
$fname = $res[0]->fname;
Session::put('userid', $userid);
Session::put('fname', $fname);
auth()->login($res);
return Redirect('admin/dashboard-listing');
}
Alternatively, you can use the auth()->loginById($res->id) method.

Method [validate] does not exist. - Laravel 5.5

I'm trying "laravel-modules" and "Laravel-permission package". But when run post, it has issue 'Method [validate] does not exist.'. i have added 'use Validator;' but no thing change. In some topics, i remove "use Illuminate\Routing\Controller;" in PermissionController, but it have error
Controller
namespace App\Http\Controllers;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
class Controller extends BaseController
{
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
}
My PermissionController
namespace Modules\User\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Routing\Controller;
use Auth;
//Importing laravel-permission models
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;
use Session;
class PermissionController extends Controller
{
// use Validator;
public function __construct() {
$this->middleware(['auth', 'isAdmin']); //isAdmin middleware lets only users with a //specific permission permission to access these resources
}
/**
* Display a listing of the resource.
* #return Response
*/
public function index()
{
$permissions = Permission::all(); //Get all permissions
return view('user::permissions/index')->with('permissions', $permissions);
// return view('user::index');
}
/**
* Show the form for creating a new resource.
* #return Response
*/
public function create()
{
$roles = Role::get(); //Get all roles
return view('user::permissions/create')->with('roles', $roles);
}
/**
* Store a newly created resource in storage.
* #param Request $request
* #return Response
*/
public function store(Request $request)
{
$this->validate($request, [
'name'=>'required|max:40',
]);
$name = $request['name'];
$permission = new Permission();
$permission->name = $name;
$roles = $request['roles'];
$permission->save();
if (!empty($request['roles'])) { //If one or more role is selected
foreach ($roles as $role) {
$r = Role::where('id', '=', $role)->firstOrFail(); //Match input role to db record
$permission = Permission::where('name', '=', $name)->first(); //Match input //permission to db record
$r->givePermissionTo($permission);
}
}
return redirect()->route('permissions.index')
->with('flash_message',
'Permission'. $permission->name.' added!');
}
}
Route
Route::group(['middleware' => 'web', 'prefix' => 'permissions', 'namespace' => 'Modules\User\Http\Controllers'], function()
{
Route::get('/', 'PermissionController#index');
Route::get('/create', 'PermissionController#create');
Route::post('/', 'PermissionController#store');
Route::delete('/', ["as" => "permissions.destroy", "uses" => "PermissionController#destroy"]);
});
Add back in use Validator in your PermissionController. Add this right after use Auth;. You have currently added this in the wrong place.
Then change your $this->validate(...) code to:
// validate the input
$validation = Validator::make( $request->all(), [
'name'=>'required|max:40',
]);
// redirect on validation error
if ( $validation->fails() ) {
// change below as required
return \Redirect::back()->withInput()->withErrors( $validation->messages() );
}
I was trying
$this->validate($request, [
'password' => 'required|confirmed|min:6',
]);
But in Laravel 5.7 following code did the trick for me
$request->validate([
'password' => 'required|confirmed|min:6',
]);

Customising token response Laravel Passport

I am working on an API at the moment and have hit a brick wall. I am using Passport with the 'Password' grant type.
I want to return the user information with the access tokens, however, I am not sure how to.
Which class could I implement, edit or extend to get this?.
I would like this to be returned:
{
"token_type": "Bearer",
"expires_in": 31536000,
"access_token": "lalalalalal",
"refresh_token": "lalalallala",
"user": {
"username": "a username",
"user_type": "admin"
}
}
Thanks in advance.
The instructions on how to do this are hinted in the BearerTokenResponse class (part of the league/oauth2-server package).
Tested on Laravel 5.7.
1. Extend the BearerTokenResponse class, add the extra params you need in the response.
namespace App\Auth;
use League\OAuth2\Server\Entities\AccessTokenEntityInterface;
class BearerTokenResponse extends \League\OAuth2\Server\ResponseTypes\BearerTokenResponse
{
/**
* Add custom fields to your Bearer Token response here, then override
* AuthorizationServer::getResponseType() to pull in your version of
* this class rather than the default.
*
* #param AccessTokenEntityInterface $accessToken
*
* #return array
*/
protected function getExtraParams(AccessTokenEntityInterface $accessToken): array
{
return [
'user_id' => $this->accessToken->getUserIdentifier(),
];
}
}
2. Create your own PassportServiceProvider class and override the makeAuthorizationServer() method in order to pass in your own BearerTokenResponse class.
namespace App\Providers;
use App\Auth\BearerTokenResponse;
use Laravel\Passport\Bridge;
use League\OAuth2\Server\AuthorizationServer;
class PassportServiceProvider extends \Laravel\Passport\PassportServiceProvider
{
/**
* Make the authorization service instance.
*
* #return \League\OAuth2\Server\AuthorizationServer
*/
public function makeAuthorizationServer()
{
return new AuthorizationServer(
$this->app->make(Bridge\ClientRepository::class),
$this->app->make(Bridge\AccessTokenRepository::class),
$this->app->make(Bridge\ScopeRepository::class),
$this->makeCryptKey('private'),
app('encrypter')->getKey(),
new BearerTokenResponse() // <-- The class you created above
);
}
}
3. Add your provider to the providers array in config/app.php
/*
* Application Service Providers...
*/
App\Providers\PassportServiceProvider::class,
4. Exclude the passport package from laravel auto-discovery in composer.json
This stops the default PassportServiceProvider class from being loaded.
"extra": {
"laravel": {
"dont-discover": [
"laravel/passport"
]
}
},
Then run composer install.
Two steps.
1. Add a new route in your routes file.
// routes/api.php
Route::post('oauth/token', 'AuthController#auth');
Keep in mind this will change the route for getting the token from /oauth/token to /api/oauth/token.
2. Add the controller method.
<?php
// app/Http/Controllers/AuthController.php
namespace App\Http\Controllers;
use App\User;
use Psr\Http\Message\ServerRequestInterface;
use \Laravel\Passport\Http\Controllers\AccessTokenController;
class AuthController extends AccessTokenController
{
public function auth(ServerRequestInterface $request)
{
$tokenResponse = parent::issueToken($request);
$token = $tokenResponse->getContent();
// $tokenInfo will contain the usual Laravel Passort token response.
$tokenInfo = json_decode($token, true);
// Then we just add the user to the response before returning it.
$username = $request->getParsedBody()['username'];
$user = User::whereEmail($username)->first();
$tokenInfo = collect($tokenInfo);
$tokenInfo->put('user', $user);
return $tokenInfo;
}
}
Im using Multi-Auth with passport, so the previous answers didn't help me.
After hours of "googling" I found this answer (after-) middleware.
My middleware basically gets the result of Passport auth, checks if there is an Bearer inside and append more data to the content.
<?php
namespace App\Http\Middleware;
use Closure;
class AppendTokenResponse
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
$response = $next($request);
$content = json_decode($response->content(), true);
if (!empty($content['access_token'])) {
$content['moredata'] = 'some data';
$response->setContent($content);
}
return $response;
}
}
Now put the new Middleware in $routemiddleware at App/Http/Kernel.php
/**
* The application's route middleware.
*
* These middleware may be assigned to groups or used individually.
*
* #var array
*/
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'cors' => \App\Http\Middleware\Cors::class,
'multiauth' => \SMartins\PassportMultiauth\Http\Middleware\MultiAuthenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
'oauth.providers' => \SMartins\PassportMultiauth\Http\Middleware\AddCustomProvider::class,
'append_auth' =>\App\Http\Middleware\AppendTokenResponse::class,
];
Then just register this middleware to Passport Routes in Providers/AuthServiceProvider.php
With Multiauth:
Route::group(['middleware' => ['oauth.providers','append_auth']], function () {
Passport::routes(function ($router) {
return $router->forAccessTokens();
});
});
I believe regular passport should be (not tested):
Route::group(['middleware' => ['append_auth']], function () {
Passport::routes();
});
Another better answer from the web
Custom Laravel Passport BearerTokenResponse
https://gist.github.com/messi89/489473c053e3ea8d9e034b0032effb1d
To add custom claims to your Passport token, here is a gist using Passport 8 with Laravel 6
https://gist.github.com/onamfc/0422da15743918e653888441ba6226ca

Resources