Laravel 5.3 and API authentication using api_token - php

I have followed the steps of this tutorial in order to setup API authentication in Laravel 5.3 using the auth:api middleware.
Everything is working as expected apart from I am finding that in order to successfully access my API, I only need to provide an API token for any user in my users table rather than the token linked to the user currently logged in.
Is this expected behaviour because this middleware is stateless? I am using AdLdap2 to authenticate users but I can't see what I could be doing wrong especially as I have followed the steps in the tutorial above.
I have also had a look at TokenGuard which deals with API token validation but can't see any logic that ensures the token matches that of the user logged in.
Any help is much appreciated.

I think the authentication works like expected. The only thing auth:api does is making sure you are authenticated to access the protected routes. If you want to protect a specific route to only one user you could use Gates
So if you have a route to access a user like below and you want the user that's logged in to only access herself you can add a gate.
routes/web.php
Route::get('/user/{id}', function ($id) {
$userYourTryingToView = User::find($id);
if (Gate::allows('get-user', $userYourTryingToView)) {
// The user is allowed to access herself, return the user.
return response()->json($userYourTryingToView);
}
// User is not authenticated to view some other user.
return response('Unauthenticated', 403);
});
And in your app/Providers/AuthServiceProvider.php
/**
* Register any authentication / authorization services.
*
* #return void
*/
public function boot()
{
$this->registerPolicies();
Gate::define('get-user', function ($authenticatedUser, $userYourTryingToView) {
return $authenticatedUser->id == $userYourTryingToView->user_id;
});
}

Related

laravel passport auth code - asking to grant permissions, is it nessecarry?

I am looking for some clarification as for how exactly to proceed with Oauth auth code PKCE grant when it comes to authorizing my own SPA.
So I get this when I am redirected from my SPA to backend (after I log in of course):
Now I get this, makes sense if I want to login into my app with google or twitter for example.
But If I want to log in to the backend app to get the token with my SPA - is there a way to avoid that every time a user logs in? Does it make sense?
I would like to have it from user perspective like this:
click login
redirect to backend pretending to be SPA (visually)
login
go straight back to SPA without having to confirm that stuff
I just mainly want to understand the process for SPA. I assume and suspect that what I want is simply not possible?
Yes you can :)
Create your own Passport client.
<?php
declare(strict_types=1);
namespace App\Models;
class PassportClient extends \Laravel\Passport\Client
{
/**
* Determine if the client should skip the authorization prompt.
*
* #return bool
*/
public function skipsAuthorization()
{
// todo: add some checks, e.g. $this->name === 'spa-client'
return true;
}
}
And update your App\Providers\AuthServiceProvider.
public function boot()
{
// ...
Passport::useClientModel(PassportClient::class);
}

Get user which is authenticated by Fortify in API routes Laravel 8

I have a Laravel 8 application that uses Fortify with custom views to login and register users. I have some API routes that I want to get the logged-in user details on them as well. The problem is that I don't want to use Passport and other packages to make the job hard to generate tokens and so on because most of the routes are in the web.php and just some routes are on api.php, so what I have tried is like below :
dd(auth()->guard('api')->user());
However, it returns null and...
dd(Auth::user());
Again returns null. Is there any way to get the authenticated user in the API routes?
In your controller method, you can retrieve the user with these two methods:
public function render(Request $request) {
$user = $request->user(); // 1
$user = auth()->user(); // 2
}

How to Restrict controllers or routes for different type of users in API

I'm working on a project with laravel. in my project there's two type of users one of them are admins and other one is normal users.
btw project is only provides API and there's no blade views.
I give a token to any user or admin logins with the api. and application will identify user or admin by sending that token with an authorization header and I check if token is validate and the user type is admin then give access to the admin features for that client.
here's my code for this part:
$admin = Auth::guard('admin-api')->user();
if ($admin) {
// allow to use admin features
}
else {
return response()->json(['error' => 'token is invalid'], 401);
}
I read something about applying Restrictions on a controller class in laravel and it was written there to add a constructor like this into controller class:
public function __construct() {
$this->middleware('admin-api');
}
and also there's something like that just for Restricting routes. like this
but I just want to know is it necessary to add same constructor to my controller class while the project just provides API? or the way that I'm doing is correct?
You are doing it right.
I would prefer restricting the request via routes, so there is no need to add constructor on each new Controllers.
Route::middleware(['admin-api'])
->group(function () {
Route::get('cart', 'Carts\CartController#retreive');
Route::post('cart/coupon', 'Carts\CartCouponController#addCoupon');
Route::delete('cart/coupon', 'Carts\CartCouponController#deleteCoupon');
Route::delete('cart/flyer', 'Carts\CartController#deleteFlyer');
});
This will apply the admin-api middleware on all the routes in the group and there is no need to add a constructor on Carts\CartController and Carts\CartCouponController, just to have middleware restriction.

Laravel oauth user redirection after registration

all. I'm just trying to implement Single sign-on server using Laravel and passport app.
What I'm trying to achieve: A single sign-on server who listen to the request from the client and provide the authentication based on the requested parameter.
What I've achieved so far: The SSO server who listen to the client request and provide the authentication and redirect back to the client site only if the user already registered on the SSO server.
The problem is coming to the picture when the user is not registered on SSO server and try to register the account In this case Laravel register user and redirect back to the homepage instead client callback URL.
Please let me know if this is achievable in Laravel or someone does something special for it.
It is pretty much achievable, depends on how much effort you want to put towards it.
When the user is registering, you can save the callback URL in the session.
session(['callback' => $callback]);
Upon registration, redirect the user to their callback URL
return redirect()->away(session('callback'));
If you are still using the default Auth/RegisterController provided by laravel, you can change the redirect behavior by defining a custom redirect function
protected function redirectTo()
{
return redirect()->away(session('callback'));
}
Laravel will automatically pick it up.
Don't forget to delete the property
protected $redirectTo = '/home';
Yes you can do this with some customization in default registration functionality, you have to replace some code in RegistrationController as provided below:
app\Http\Controllers\Auth\RegistrationController
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use AuthenticatesUsers, RegistersUsers {
AuthenticatesUsers::redirectPath insteadof RegistersUsers;
AuthenticatesUsers::guard insteadof RegistersUsers;
}
public function register(Request $request)
{
$this->validator($request->all())->validate();
event(new Registered($user = $this->create($request->all())));
if ($this->attemptLogin($request)) {
if ($request->hasSession()) {
$request->session()->put('auth.password_confirmed_at', time());
}
return $this->sendLoginResponse($request);
}
}

Entrust Route Protection in Laravel 5 - Check for Auth first

For some reason I have had a mind block and can't figure out what is probably a very simple fix.
I have a Laravel 5 App and am using Zizaco's Entrust package for Access Control.
I want to protect a route so am using route Protection in routes.php as follows:
Entrust::routeNeedsRole('passtypes', array('admin'), null, false);
Which works as expected, apart from when a user's session has expired or they are not logged in and try to access the route.
In this case I would want Laravel's Authentication to be checked first, and redirect to the login page; however Entrust redirects to the 403 error first; which is confusing for a user that has ability to view that page, but is told they do not have access, rather than that they are not logged in/session has expired.
I initiate the Authentication in the Controller rather than in the route:
public function __construct()
{
$this->middleware('auth');
}
So just need to know how to get the same functionality, but by having auth get checked before the route permission requirement.
Thanks
I think that Entrust::routeNeedsRole fires before controller. Can you move Entrust to middleware? You could then check in middleware if user is logged in and then check if he has required role.
It's been a while, but I had a similar problem. The only difference, my entire app had to be protected. I ended up modifying Authenticate Middleware handle method:
public function handle($request, Closure $next)
{
if ($this->auth->guest()) {
if ($request->ajax()) {
return response('Unauthorized.', 401);
} else {
/**
* This is to protect the entire app, except login form,
* to avoid loop
*/
if($request->path() != 'auth/login')
return redirect()->guest('auth/login');
}
}
return $next($request);
}
And inside Kernel.php moved Authenticate from $routeMiddleware to $middleware
Then you can protect your routes with Entrust.

Categories