Laravel how to get auth user details in apiResources controller - laravel-5

How can I get auth user details in api controller in laravel
I am using laravel version 5.8
This is my apiResources route
Route::apiResources([
'employeeapi' => 'API\EmployeeController',
]);
and my controller is
class EmployeeController extends Controller {
public function store(Request $request)
{
}
}
How can I access Auth::user() inside the store function?

You could use the following middleware on your api routes to use laravel sessions if the user was logged in to a session in one of your web routes.
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\Session\Middleware\AuthenticateSession::class,
However you probably want your api to use some kind of token based authentication. laravel passport has great tools for that. Because using sessions in an api might become messy.

Related

Issue with POST requests with Laravel Sanctum and Postman

I have a problem with Sanctum and Postman that's related to this post: SPA Authentication Issues with Sanctum and Postman
I followed everything from the Laravel docs about Sanctum and configured it correctly. Then I followed this tutorial: https://blog.codecourse.com/laravel-sanctum-airlock-with-postman/
Everything is working except for POST requests. When I do login, it works. But then I have a collection without the pre-request Script and when I do a GET request to for example /user, it will return the logged in user.
But when I change the method to POST in Laravel and in Postman, I'll get a CSRF token mismatch error.
Does anybody knows what I have to do, to make POST requests working?
Route::middleware('auth:sanctum')->post('/user', function (Request $request) {
return $request->user();
});
I've been using sanctum in one of my e-commerce APIs and I've also followed the same tutorial you've linked in the question. It's hard to tell what's the actual problem in your case but it seems like that you're not sending the X-XSRF-TOKEN header in your POST requests.
The last paragraph in the above-mentioned tutorial, the writer shows how to hit the /logout route which is a POST route.
Remove this function in the controller
public function __construct()
{
$this->middleware('auth');
}
Or change it to
public function __construct()
{
$this->middleware('auth:sanctum');
}
Also, check your RouteServiceProvider and change your API route to
Route::prefix('api/v1')
->middleware('auth:sanctum')
->namespace($this->namespace)
->group(base_path('routes/api.php'));
csrf_token is used to validate forms having method POST in laravel and token is created dynamically,
two thing you can do
First thing if you are writing api's you need to use https://<base_url>/api
and routes in routes/api.php, there you donot need csrf_token but make sure to use proper api authentication
Second just disable csrf token for those routes until you are testing on postman, once you successfully tested enable again, its provide security
disable like this
<?php namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier;
class VerifyCsrfToken extends BaseVerifier
{
protected $except = [
'submitMyForm/*',
];
}

Laravel - Protect API routes

I have Laravel application with VUEJS as front-end,
I am getting data by creating API Routes.
So for example the route for getting posts data will be http://localhost/api/posts
What is the best way to protect my routes?
I saw on laravel documentation that there is:
API athentication https://laravel.com/docs/5.8/api-authentication
also Passport https://laravel.com/docs/5.8/passport
For example now any user can reach to the route http://localhost/api/posts
and he will get json with all posts data.
I want protect that and allow only inner api request from my VUEJS commponent to get the data
I’m assuming you’re going to use the Laravel auth routes to do the authentication, and after the authentication, the next view you’re reaching is the one with all the Vue components.
The solution is simple, even that is on the documentation, the necessary steps should be clarified.
We need to:
Add passport composer require laravel/passport
Make the migrations php artisan migrate
Install passport php artisan passport:install
The fourth step is more complex. We need to open our User.php model file. And first we need to import the HasApiTokens and tell the model to use it.
use Laravel\Passport\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens, Notifiable;
.......
}
Then on our config/auth.php we need to modify the api array and change the driver to passport
'api' => [
//for API authentication with Passport
'driver' => 'passport',
'provider' => 'users',
],
Then on our app/Http/Kernel.php we need to add a middleware to the $middlewareGroups array in the key web.
protected $middlewareGroups = [
'web' => [
................
//for API authentication with Passport
\Laravel\Passport\Http\Middleware\CreateFreshApiToken::class,
],
Now we can use the auth:api middleware on our api routes.
Route::middleware('auth:api')->group( function(){
...your routes here
});
This is what the CSRF TOKEN doing, it's not quite the same with the API Authorization doing
CSRF Token:
To protect (inner) API or access points from cross-site accessing, See Cross-site_request_forgery
CSRF Token is expired and generated within a randomly time, which will make the program access difficulty
API Authorization:
The API is design to be used from other programs, and you'd like to protect them from non-authorized access
Since API tokens expiration and generation is handle by admin manually, since you'll need to place this API token in your HTML to get your function working, it's not what you searching for here
More details of CSRF protection in Laravel see: Laravel CSRF production document
Generally, we'll protect all the routes POST and PUT routes by default

Laravel authentication lifecycle

I'm trying to understand how an authentication request is handled by laravel in order to be able to write my own authentication method that allows me to check data from multiple tables before authenticating (basically there are some columns that I need to check to understand if a user is able to login).
I'm actually quietly confused about the relation between guards, middleware, provider and driver.
Can someone please explain me the lifecycle of a login request?
Thank you
EDIT: i'm working with laravel 5.7, standard Auth scaffolding that is available using make:auth
To make a custom authentication follow this steps
1.go to routes/web.php and make a get route to handle login view and post login route to handle login logic
Route::get('login','LoginController#show')
Route::post('login','LoginController#login')
2. Make a controller called LoginController
php artisan make:controller LoginController
4.inside LoginController make a function called login to handle login logic like this
public function login(){
$input = $this->validate(request(),['username'=>'required','password'=>'required']);
$model = CustomUsersModel::where('username',$input['username'])
->where('password',bcrypt($input['password']))->first();
if($model){
//user exist and valid login information
auth()->login($model);//login user via model
//now user loggedin
}
//handle wrong login information
}

Laravel API / Passport - Change auth user

I use Laravel 5.7 with Passport and Vue component.
I have a Vue component with method to change Auth of user, this method call API by POST.
My API is protected by auth:api middleware.
The connexion to site is with PHP session. I don't want use JWT.
How I can change the account connected ?
public function switchAccount(Request $request, Team $team, User $user)
{
Auth::guard('web')->login($user);
}

How to authenticate API requests in Laravel?

I am currently building some sort of posts based web application using Laravel 5(.4). I have decided to load asynchronously the comment section for each post(and refresh it periodically). After some research I have decided to write a small integrated REST API (using the api routes of Laravel) that should answer to the requests made through AJAX.
However, I am facing the problem if authenticating the incoming requests. Take for example a request to post some comment. How exactly would you recommend to do that?
If you are making AJAX requests from browser and you are signed in then you don't need to use Laravel Passport tokens.
You can define certain routes which will be using web,auth middleware on requests like webapi/comments/get like this.
Route::group(['middleware' => ['web','auth]], function () {
Route::get('webapi/comments/get', 'CommentsController#get');
}
And use Auth Facade as you do in web request i.e Auth::check(), Auth::user() etc. and return the data in JSON like this.
class CommentsController extends Controller
{
public function get(Request $request)
{
if($request->acceptsJson()){
$data = array();
// add data
return response()->json([
"data"=> $data,
"status" => true
]);
}else{
return abort(404);
}
}
}
You can also send Accept header in AJAX request as application/json and in controller check if request $request->acceptsJson() and make your decision to show content when url is loaded from browser address bar or requested as AJAX.
Laravel Passport token are useful where there is no session and cookies are managed.
hope this helps :)
"Passport includes an authentication guard that will validate access tokens on incoming requests. Once you have configured the api guard to use the passport driver, you only need to specify the auth:api middleware on any routes that require a valid access token" - from the Laraven Documentation.
Apparently I have to configure passport, and after that configure the auth:api middleware to use the passport driver. Correct me if I'm wrong, please :)

Resources