Redirect auth controller? - laravel

Im using the Auth controller in Laravel along with the auth middleware.
If the user is not logged in it redirects to:
auth/login
But I wish to redirect to a different url.
I have this in my auth controller:
protected $loginPath = '/cms/login';
protected $redirectTo = '/cms';
But it still redirects to:
auth/login
How can I redirect the auth controller?

The path for the redirect when you're not logged in is handled in the authenticates middleware, which is found at app/Http/Middleware/Authenticate.php.

Redirection will be handled by middleware. Hence change the redirect under handle() method in auth middleware as follows:
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if ($this->auth->guest())
{
if ($request->ajax())
{
//return response('Unauthorized.', 401);
}
else
{
//return redirect()->guest('auth/login');
return redirect()->guest('cms/login');
}
}
return $next($request);
}

Related

Authenticate extends Middleware redirect me if i have permission

Hello please can explain me why it happedned . i hve make middleware and was work ok but suddenly stop and redirect me any way problem in method where Authenticate .php
class Authenticate extends Middleware
{
/**
* Get the path the user should be redirected to when they are not authenticated.
*
* #param \Illuminate\Http\Request $request
* #return string|null
*/
protected function redirectTo($request)
{
if (! $request->expectsJson()) {
return route('login');
}
}
}
this return me to login if i logged not allow for user he have permisson to go this
middleware
class AdminMiddleware
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse) $next
* #return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
*/
public function handle(Request $request, Closure $next)
{
if (Auth::check()){
if (Auth::user()->user_type == 1){ //Any Manger Can Access only Not Users
return $next($request);
}else{
return redirect()->back();
// abort(403);
}
}else{
return redirect()->back();
}
}
}
and user_type == 1 was try in middle ware dd(Auth::user()); but if put it in side method redirectTo
dd(Auth::user());
return info bout user but not return nothing direct go to login in Authenticate ,
Route::group(['middleware' => 'auth:admin'], function () {
Route::get('admin/dashboard', function () {
return view('admin.index');
})->name('admin.dashboard');
and befor it was work ok . what problem !

Automatically refresh access token with laravel passport

When issuing access and refresh tokens I send them to the frontend with httpOnly = true. I made a middleware class which checks if the access token has expired and if the refresh token hasn't expired. If both are the case I call the oauth/token route with refresh_token as grant_type.
All of this works, however I'm not sure how to use the authenticated user inside the controllers. Right now I've set the middleware up that when there's a response it sends the new access and refresh token.
class RefreshAccessToken
{
/* #var AuthController $authController */
private $authController;
/**
* RefreshAccessToken constructor.
*
* #param AuthController $authController
*/
public function __construct(AuthController $authController)
{
$this->authController = $authController;
}
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
// User already has an access token
if ($request->hasCookie('access_token')) {
return $next($request);
}
// User doesn't have an access token and doesn't have a refresh token.
if (!$request->hasCookie('refresh_token')) {
return $next($request);
}
$response = $next($request);
$cookies = $this->authController->refreshToken($request);
return $response
->cookie($cookies['access_token'])
->cookie($cookies['refresh_token']);
}
}
Now inside a controller if I want to access the logged in user I always get null as a response:
public function logout()
{
dd(auth()->user());
}
}
Inside the controller's construct method:
$this->middleware('auth:api')->only('logout');
Does anyone know how to handle this use case?

Single API use for authenticated and guest user

My laravel application route configured on routes/api.php is.
<?php
use Illuminate\Http\Request;
Route::post('see_all_product', 'API\ProductController#see_all_product');
?>
Issue is i want to sent list of product but if user authenticated then send product favorite flag 1, and if not authenticated then send return favorite 0
But both case send product list with favorite flag.
If i logged in with my user id and password and send request for see_all_product that time i m getting blank user.
$user = $request->user();
But if i set route like below i m getting user details.
<?php
use Illuminate\Http\Request;
Route::group(['middleware' => 'auth:api'], function(){
Route::post('see_all_product', 'API\ProductController#see_all_product');
});
?>
Now issue is how can i get details if authorization set in the header with same api.
<?php
use Illuminate\Http\Request;
Route::post('see_all_product', 'API\ProductController#see_all_product');
?>
My see_all_product Function
public function see_all_product(Request $request){
try {
$user = $request->user();
} catch (Exception $ex) {
Log::error($ex);
}
}
API is same for both authenticated and guest user.
I pass authorization token in both case but middleware route i get user details but non middleware route i dont get user information.
Please guide me where i can miss something?
I think you can do it by the way instead of $request->user():
if (auth('api')->check()) {
$user = auth('api')->user();
}
Turn off ['middleware'=> 'auth:api']
use: $request->user('api'); in your controller.
Guests can use the api but user is null;
Auth users can use api as a real user.
alt:
Auth::guard('api')->user();
auth('api')->user();
I didn't test this method on old versions of Laravel, but it should work just fine on the latest ones.
You can create another Middleware that allows ether authenticated or guest users to proceed.
If the user is authenticated then the middleware will prepare the Auth object and auth() function for you.
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Contracts\Auth\Factory as Auth;
use Illuminate\Http\Request;
class AuthOptional
{
/**
* The authentication factory instance.
*
* #var \Illuminate\Contracts\Auth\Factory
*/
protected $auth;
/**
* Create a new middleware instance.
*
* #param \Illuminate\Contracts\Auth\Factory $auth
* #return void
*/
public function __construct(Auth $auth)
{
$this->auth = $auth;
}
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle(Request $request, Closure $next, ...$guards)
{
$this->authenticate($request, $next, $guards);
return $next($request);
}
/**
* Determine if the user is logged in to any of the given guards.
*
* #param \Illuminate\Http\Request $request
* #param array $guards
* #return void
*
*/
protected function authenticate($request, $next, array $guards)
{
if (empty($guards)) {
$guards = [null];
}
foreach ($guards as $guard) {
if ($this->auth->guard($guard)->check()) {
return $this->auth->shouldUse($guard);
}
}
//If unauthenticated allow the user anyway
$this->unauthenticated($request, $next, $guards);
}
/**
* Handle an unauthenticated user.
*
* #param \Illuminate\Http\Request $request
* #param array $guards
* #return void
*
*/
protected function unauthenticated($request, $next, array $guards)
{
return $next($request);
}
}
Import the newly created Middleware under app/Http/kernel.php
protected $routeMiddleware = [
....
'auth.optional' => \App\Http\Middleware\AuthOptional::class
];
And finally use it like this:
<?php
Route::group(['middleware' => ['auth.optional:api']],
});
?>
Now auth()->user() will return the user if user is authenticated and
null if it's not

Auth After Middleware

I wish to authenticate the user after the request with my own middleware:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Auth\Middleware\Authenticate;
class AuthenticateAfter extends Authenticate
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #param string[] ...$guards
* #return mixed
*
* #throws \Illuminate\Auth\AuthenticationException
*/
public function handle($request, Closure $next, ...$guards)
{
$response = $next($request);
$this->authenticate($request, $guards);
return $response;
}
}
I extend Illuminate\Auth\Middleware\Authenticate and modify the handle method to run as after middleware.
It's then declared in my kernel and on the correct route.
But I always get kicked back to the page I was previously on after logging in.
I want to control the page I go to, so before the middleware kicks in I do:
$request->session()->put('url.intended', 'my-test-url');
But it fails to redirect to this route.
How can I get it to redirect to a custom route?
Try this,
public function handle($request, Closure $next, ...$guards)
{
$response = $next($request);
$this->authenticate($request, $guards);
return redirect('/your_page_path');
}
Just for reference, here what I use to authenticate a user:
public function handle($request, Closure $next)
{
if (auth()->user() && auth()->user()->type != 'admin')
{
return redirect('/unauthorized');
}
return $next($request);
}
Try with: return redirect('view') or return redirect()->to('/route')

how to add bearer access token in request header from controller in laravel

I'm working on Laravel API Authentication. I have done login, register part. when I want to get-details of any user using postman every time i need add Bearer access_token in request header.
But I want to send it from my Backend Controller or Middleware .
How can i do this.
Here is my Code Sample. I try this way But not working.
public function details(Request $request)
{
$user = Auth::user();
$token='Bearer '.$request->bearerToken();
$request->header('Authorization',$token);
return response()->json(['success' => $user], $this-> successStatus);
}
I do this in middleware, for example:
<?php
namespace App\Http\Middleware;
use Closure;
class AccessTokenMiddleware
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
$request->headers->add(['Authorization' => "Bearer {$request->access_token}"]);
return $next($request);
}
}

Resources