I have some strange problems with my laravel app. I have created an authentication system with Passport, I have installed everything as needed but I can't authenticate the user. When I log in it's creating a token correctly and everything seems to work fine, but when I want to add authentication in postman, it's always "Not Authenticated". This is happening with Laravel 8, I have copied everything from my Laravel 7 app and there is working pretty fine. I will provide you with some code.
This is middleware that I created to check authentication:
public function handle(Request $request, Closure $next)
{
if(!Auth::id()){
return response()->json(['response' => false, 'status' => 403, 'message' => 'Not Authenticated'], 403);
} else {
return $next($request);
}
}
Here is Kernel
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 = [
// \App\Http\Middleware\TrustHosts::class,
\App\Http\Middleware\TrustProxies::class,
\Fruitcake\Cors\HandleCors::class,
\App\Http\Middleware\PreventRequestsDuringMaintenance::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
\App\Http\Middleware\UserSecurity::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\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'api' => [
'throttle:api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
\Laravel\Passport\Http\Middleware\CreateFreshApiToken::class,
],
];
/**
* 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,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'check.auth' => \App\Http\Middleware\UserAuth::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,
];
}
And here is application.blade.php
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<meta name="csrf-token" content="{{ csrf_token() }}">
<!-- <link rel="icon" href="<%= BASE_URL %>favicon.ico"> -->
<title>Vuexy - Vuejs, HTML & Laravel Admin Dashboard Template</title>
<!-- Styles -->
<link rel="stylesheet" href="{{ asset(mix('css/main.css')) }}">
<link rel="stylesheet" href="{{ asset(mix('css/iconfont.css')) }}">
<link rel="stylesheet" href="{{ asset(mix('css/material-icons/material-icons.css')) }}">
<link rel="stylesheet" href="{{ asset(mix('css/vuesax.css')) }}">
<link rel="stylesheet" href="{{ asset(mix('css/prism-tomorrow.css')) }}">
<link rel="stylesheet" href="{{ asset(mix('css/app.css')) }}">
<link
rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css"
/>
<!-- Favicon -->
<link rel="shortcut icon" href="{{ asset('images/logo/favicon.png') }}">
</head>
<body>
<noscript>
<strong>We're sorry but Vuexy - Vuejs, HTML & Laravel Admin Dashboard Template doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
</noscript>
<div id="app">
</div>
<!-- <script src="js/app.js"></script> -->
<script src="{{ asset(mix('js/app.js')) }}"></script>
</body>
</html>
And here is the Router:
Route::group(['middleware' => 'auth:api', 'middleware' => 'auth:api'], function() {
Route::get('profile', [UserController::class, 'getUserDetails'])->name('profile');
Route::post('logout', [UserController::class, 'destroySession'])->name('logout');
});
Now what I have noticed is, when I use auth:API and not my middleware, I'm getting error like:
RuntimeException: Session store not set on request. in file C:\xampp\htdocs\sss\vendor\laravel\framework\src\Illuminate\Http\Request.php on line 483
Any ideas?
After I did my research I found solution but it's not suitable for me:
I changed middleware in my routes to beauth:api
and before that wascheck.auth
, and I removed\Laravel\Passport\Http\Middleware\CreateFreshApiToken::class
, and now it works.
The real question is, why is my middleware not working?
You middlware doesn't work because you are not checking the right guard.
Since you are not providing any guard in your check, Laravel will fallback to the default guard thus theweb
guard (defined in yourconfig/auth.php
).
To make your middleware work, edit the line with the following:
if(!Auth::guard('api')->check())
Cordially
Your condition was wrong; you should write instead:
public function handle(Request $request, Closure $next) {
if(auth()->check()){
return $next($request);
}
return response()->json(['response' => false,'status' => 403,'message' => 'Not Authenticated'], 403);
}
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Find the answer in similar questions on our website.
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.
PHP (from the English Hypertext Preprocessor - hypertext preprocessor) is a scripting programming language for developing web applications. Supported by most hosting providers, it is one of the most popular tools for creating dynamic websites.
The PHP scripting language has gained wide popularity due to its processing speed, simplicity, cross-platform, functionality and distribution of source codes under its own license.
https://www.php.net/
Laravel is a free open source PHP framework that came out in 2011. Since then, it has been able to become the framework of choice for web developers. One of the main reasons for this is that Laravel makes it easier, faster, and safer to develop complex web applications than any other framework.
https://laravel.com/
JavaScript is a multi-paradigm language that supports event-driven, functional, and mandatory (including object-oriented and prototype-based) programming types. Originally JavaScript was only used on the client side. JavaScript is now still used as a server-side programming language. To summarize, we can say that JavaScript is the language of the Internet.
https://www.javascript.com/
CSS (Cascading Style Sheets) is a formal language for describing the appearance of a document written using a markup language.
It is mainly used as a means of describing, decorating the appearance of web pages written using HTML and XHTML markup languages, but can also be applied to any XML documents, such as SVG or XUL.
https://www.w3.org/TR/CSS/#css
Foundation, similar to Bootstrap, has become very popular as a more complex framework with some advanced but easy-to-implement CSS components. It is built with Sass, so just like Bootstrap, it is customizable. In addition to this, it also boasts some features that help make the design mobile responsive.
https://get.foundation/
There are several libraries that do almost the same thing: add one or more animations to a specified element. The first such library to gain popularity in recent years was Dan Eden's Animate.css. This fun library contains dozens of built-in animations that shake, fade, slide, scale, and more.
https://animate.style/
HTML (English "hyper text markup language" - hypertext markup language) is a special markup language that is used to create sites on the Internet.
Browsers understand html perfectly and can interpret it in an understandable way. In general, any page on the site is html-code, which the browser translates into a user-friendly form. By the way, the code of any page is available to everyone.
https://www.w3.org/html/
Welcome to the Q&A site for web developers. Here you can ask a question about the problem you are facing and get answers from other experts. We have created a user-friendly interface so that you can quickly and free of charge ask a question about a web programming problem. We also invite other experts to join our community and help other members who ask questions. In addition, you can use our search for questions with a solution.
Ask about the real problem you are facing. Describe in detail what you are doing and what you want to achieve.
Our goal is to create a strong community in which everyone will support each other. If you find a question and know the answer to it, help others with your knowledge.