Token Based Logout - Laravel - laravel

For Logout function what Request should be Pass ? ( Access Token or any User Details?)
API Route
Route::group([
'middleware' => 'auth:api'
], function() {
Route::post('logout', 'api\LoginController#logout');
});
Controller function
public function logout(Request $request)
{
$request->user()->token()->revoke();
return $this->loggedOut($request);
}

Send just your Access Token to request. As midleware knows that given token belong to which user.
Postman request example:

Related

Laravel API: display error message for invalid token?

I set up a simple api authentication with a hashed token as explained in the laravel doc
// app/Http/Controllers/Api/Blog/PostController.php
class PostController extends Controller
{
...
public function show($post)
{
if (!$post = Post::select('title', 'slug', 'content')->find($post)) {
return response()->json([
'message' => 'Ressource not found.'
], 404);
}
return response()->json($post);
}
...
}
// routes/api.php
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
Route::group(['middleware' => 'auth:api'], function () {
Route::apiResource('posts', PostController::class);
});
Now, in Postman if I send a request along with a valid token:
https://example.com/myapp/public/api/posts/5?api_token=tLcCDe6jCiYhuhUtVWwmnCbddSY7w9m4GIp6UXahyojW5O2YXPTpc4A7XRYV
I get the expected data in JSON format.
Now if I modify the token on purpose in order to simulate an invalid token, the request is redirected to the login page and I get the HTML code of the page in Postman with a 200 OK status.
But what I want is to display a 401 error message in JSON instead.
How can I do that ?

Laravel OAuth2 Passport API, generates Token but then unable to make requests : "unauthenticated"

I have installed OAuth2 Passport to my Laravel project.
I am using postman to test, I can create new user, I can login (token is generated) and logout.
Once I have logged in I try to make request to an API endpoint but here I get stuck as no matter what I get 401 Unauthorized response in postman "message": "Unauthenticated."
When I make GET request to endpoint I include following headers:
Content-Type: application/json
X-Requested-With: XMLHttpRequest
Authorization: Bearer TOKENHERE
This is my routes file api.php
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
Route::get('trip/{id}', 'TripController#getUserTrips');
Route::get('trainroute/{id}', 'TripController#getTrainRouteInfo');
Route::get('routestops/{id}', 'TripController#getRouteStops');
Route::post('trip', 'TripController#addTrip');
Route::get('trip', 'TripController#errorTrip') -> name('test');
Route::group([
'prefix' => 'auth'
], function () {
Route::post('login', 'AuthController#login');
Route::post('signup', 'AuthController#signup');
Route::group([
'middleware' => 'auth:api'
], function() {
Route::get('logout', 'AuthController#logout');
Route::get('user', 'AuthController#user');
});
});
In my TripController, where are the endpoints I wish to access, I've included
public function __construct()
{
$this->middleware('auth');
}
I have searched for answers and tried several things, such as editing .htaccess file and made sure to include Authorization header to GET request.
After a long long, hours long dive into this problem the answer was rather simple, in my TripController I had this
public function __construct()
{
$this->middleware('auth');
}
but I'm using api routes, and then I saw login etc middleware was named 'auth:api' so I tried same and ... IT WORKED!
so this is correct
public function __construct()
{
$this->middleware('auth:api');
}

I can only access my auth()->user() in the method where I auth()->login() and not the other methods in the same Controller

I'm trying to implement my own login/logout with passport in a new Controller.
class AuthController extends AccessTokenController
{
use AuthenticatesUsers;
.
.
My login methods works fine:
public function login(ServerRequestInterface $request)
{
if (!auth()->attempt([
'email' => $request->getParsedBody()['email'],
'password' => $request->getParsedBody()['password']
])) {
return response()->json('failed attempt...');
}
auth()->login(User::where('id', Auth::user()->id)->first());
.
.
// I can access auth()->user() here just fine ..
}
But I can't access the authenticated user in the logout method so I can get his tokens and delete them.
public function logout()
{
//I can't access the authenticated user here
return auth()->user();
//return response()->json('Logged out successfully', 200);
}
What am I doing wrong?
Note: I left out anything in the login method that is related to issuing a token because it's not related to the question ..
Update: my routes/api.php
Route::post('register', 'Auth\RegisterController#register');
Route::post('login', 'Auth\AuthController#login');
Route::post('logout', 'Auth\AuthController#logout');
if you are using api then you should send authorization header else it should work for session based authentication
Then you can access the authenticated user using the request
public function logout(Request $request)
{
return $request->user(); //the user that made the request (the authenticated user)
}
Or:
public function logout(Request $request)
{
return Auth::user(); //the user that made the request (the authenticated user)
}

Accessing The Request Via Route Closures

In this route below, what is the user() function?
Route::group(['middleware' => 'auth:api'], function () {
Route::get('user', function (Request $request) {
return $request->user();
});
});
It's an instance of the authenticated user. It's the same as auth()->user()
https://laravel.com/docs/5.4/authentication#retrieving-the-authenticated-user
A global helper returning the user making the request. Identified through auth:api

Request goes to each middleware laravel 5.2

I'm using laravel 5.2 with entrust/zizaco. When the user authenticates, they have the role admin, but when I put dd(1) in my app_user role middleware the request enters it !!
The request also enters admin, and business_owner role middlewares.
And even when the user logs out, after that each of their requests goes through auth middleware !!
Route::group(['middleware' => 'auth'], function () {
Route::group(['middleware' => ['role:admin']], function (){
// Routes go here
});
Route::group(['middleware' => ['role:app_user']], function (){
// Routes go here
});
Route::group(['middleware' => ['role:business_owner']], function (){
// Routes go here
});
});
Yes, request should enter in authenticate middleware and you can write your codes in middleware.
This is laravel built in middleware for authenticate users:
public function handle($request, Closure $next)
{
if ($this->auth->guest()) { // if user isn't authenticated
if ($request->ajax()) { // if request is ajax
return response('Unauthorized.', 401); // return 401 res
} else {
return redirect()->guest('login'); // else redirect login page
}
}
return $next($request); // return next res(e.g dashboard) if user is authenticated
}

Resources