Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

mirzashahmir02's avatar

User Authentication and Authorization on client side with no database

first app features: connected with my database login api returning auth user from database with roles and permissions and jwt token used spattie roles and permission package for user roles and permissionsin database

second app features: no database laravel based frontend and only api call using guzzleclient login frontend hitting api from first app take response with either invalid email, passwordor a response like

{ "data": { "status": "success", "user": { "id": 1, "name": "Shahmir Mirza", "email": "[email protected]", "email_verified_at": null, "created_at": "2022-11-21T11:22:28.000000Z", "updated_at": "2022-11-21T11:22:28.000000Z", "roles": [ { "id": 1, "name": "Super Admin", "guard_name": "api", "created_at": null, "updated_at": null, "pivot": { "model_id": 1, "role_id": 1, "model_type": "App\Models\User" }, "permissions": [] }, { "id": 2, "name": "Admin", "guard_name": "api", "created_at": null, "updated_at": null, "pivot": { "model_id": 1, "role_id": 2, "model_type": "App\Models\User" }, "permissions": [] }, { "id": 3, "name": "Agent", "guard_name": "api", "created_at": null, "updated_at": null, "pivot": { "model_id": 1, "role_id": 3, "model_type": "App\Models\User" }, "permissions": [] } ] }, "authorization": { "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOi8vMTI3LjAuMC4xOjgwMDAvYXBpL2xvZ2luIiwiaWF0IjoxNjY5MDQ4ODc4LCJleHAiOjE2NjkwNTI0NzgsIm5iZiI6MTY2OTA0ODg3OCwianRpIjoibzBsc0VGWW9KMUdTT0NXayIsInN1YiI6IjEiLCJwcnYiOiIyM2JkNWM4OTQ5ZjYwMGFkYjM5ZTcwMWM0MDA4NzJkYjdhNTk3NmY3In0.d-9UtiWmdhbuDX7flMWE7wAZGM_7OmZuBGVcTi7rEPU", "type": "bearer", "expiry_time": 3600 } } }

and redirects me to my admin panel i saved this object in a session variable named auth_user now i want to use @can or @role in my second app in my blade files to grant access to side nav menu according to the user roles or permissions stored in my session or any other smarter way. i dun want to make my code bulky using if else and want to use blade directives so i want a laravel project with complete api implementation of login page with roles and permissions

i am a new to laravel i tried to make custom gates first but did`nt reach out how to create it with session variables then i tried to create custom blade directives but i still find no way how to do that i hope i explained what i want.

0 likes
11 replies
vincent15000's avatar

To write a custom blade statement, it's very simple.

https://laravel.com/docs/9.x/blade#custom-if-statements

Blade::if('admin', function ($value) {
    return auth()->user->isAdmin();
});

Then you can use this statement in blade.

@admin
	...
@endadmin

If you prefer using @can, you have to write policies.

public function update(User $user, Room $room)
{
    return $user->isAdmin && $user->is($room->user); // assuming you have an ```isAdmin()``` method in the User model
}

Then you can use @can in blade.

@can('update', $room)
	...
@endcan
mirzashahmir02's avatar

but bro my problem is i cant use policies nor i can use auth()->user() in my client side app because i dont have any model or database in it the client side app will only use stateless apis for each and everything

vincent15000's avatar

@mirzashahmir02 You have writtent this.

... now i want to use @can or @role in my second app in my blade files ...

So why do you say that you can't use @can for example ?

Furthermore if you are using Spatie roles and permissions, you necessarily use models, at least the User model.

If you need to send authorization to the front end, you can for example use Laravel API Resources and add meta data with the permissions. But this will never replace any strong protection of your API routes with middlewares.

mirzashahmir02's avatar

@vincent15000 I used spattie roles and permissions in my server side app all models are in my this app and authentication and authorization is working fine and second app is my frontend containing a side nav with list items how can I display the list items according with user roles or permissions in front end app. In my frontend app user data is stored in a session in an array form the array displayed above.

1 like
mirzashahmir02's avatar

@vincent15000 i am already sending the authorization to the front end bro but cant authorize the user IN THE FRONTEND listen carefully i am writing the code of both apps.

API APP LOGIN CONTROLLER:

public function login(Request $request)
    {
        $request->validate([
            'email' => 'required|email',
            'password' => 'required',
        ]);
        $credentials = $request->only('email', 'password');

        $token = Auth::attempt($credentials);
        if (!$token) {
            return response()->json(["data" => [
                'status' => 'error',
                'message' => 'Invalid Email Or Password',
            ]], 401);
        }

        $user = Auth::user();
        // $user->getPermissionNames();
        // $user->getDirectPermissions();
        $user->getPermissionsViaRoles();
        $user->getRoleNames();
        $exp = auth()->factory()->getTTL() * 60;
        return response()->json([
            "data" => [
                'status' => 'success',
                'user' => $user,
                'authorization' => [
                    'token' => $token,
                    'type' => 'bearer',
                    'expiry_time' => $exp,
                ]
            ]
        ]);
    }

IN POSTMAN i get response like this

{
    "data": {
        "status": "success",
        "user": {
            "id": 1,
            "name": "Shahmir Mirza",
            "email": "[email protected]",
            "email_verified_at": null,
            "created_at": "2022-11-21T11:22:28.000000Z",
            "updated_at": "2022-11-21T11:22:28.000000Z",
            "roles": [
                {
                    "id": 1,
                    "name": "Super Admin",
                    "guard_name": "api",
                    "created_at": null,
                    "updated_at": null,
                    "pivot": {
                        "model_id": 1,
                        "role_id": 1,
                        "model_type": "App\Models\User"
                    },
                    "permissions": []
                },
                {
                    "id": 2,
                    "name": "Admin",
                    "guard_name": "api",
                    "created_at": null,
                    "updated_at": null,
                    "pivot": {
                        "model_id": 1,
                        "role_id": 2,
                        "model_type": "App\Models\User"
                    },
                    "permissions": []
                },
                {
                    "id": 3,
                    "name": "Agent",
                    "guard_name": "api",
                    "created_at": null,
                    "updated_at": null,
                    "pivot": {
                        "model_id": 1,
                        "role_id": 3,
                        "model_type": "App\Models\User"
                    },
                    "permissions": []
                }
            ]
        },
        "authorization": {
            "token": 																																																					 
"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOi8vMTI3LjAuMC4xOjgwMDAvYXBpL2xvZ2luIiwiaWF0IjoxNjY5MjgyMTEwLCJleHAiOjE2NjkyODU3MTAsIm5iZiI6MTY2OTI4MjExMCwianRpIjoiTTZKTDJxRGh4RkFwSmg2NyIsInN1YiI6IjEiLCJwcnYiOiIyM2JkNWM4OTQ5ZjYwMGFkYjM5ZTcwMWM0MDA4NzJkYjdhNTk3NmY3In0.4602RIy527TW7PeEXFl9p1YlAZdpTrxEz0hMQiYpD2E",
            "type": "bearer",
            "expiry_time": 3600
        }
    }
}

then in my client side app i do the following

CLIENT SIDE APP LOGIN CONTROLLER:

public function login(Request $request)
    {
        $client = new Client();

        $request->validate([
            'email' => 'required|email',
            'password' => 'required',
        ]);

        $headers = [
            'Accept' => 'application/json',
            'Content-Type' => 'application/json',
        ];

        $credentials = [
            'email' => $request['email'],
            'password' => $request['password']
        ];

        $body = json_encode($credentials);
       // hitting an api from here
            $authRequest = new GuzzleRequest('POST', 'http://127.0.0.1:8000/api/login', $headers, $body);
           // hitting an api
            $promise = $client->sendAsync($authRequest)->then(function ($response) {
                $myResponse = json_decode($response->getBody(), true);
                return $myResponse;
            }, function ($response) {
                $myResponse = $response->getResponse()->getBody();
                $err = json_decode($myResponse, true);
                return $err;
            })->wait();

            if (isset($promise['data']['status']) == 'success') {
			// here i am putting my response in a session and redirecting it to dashboard
                Session::put('auth_user', $promise);
            } elseif (($promise['data']['status']) == 'error') {
                return $promise;
            }
        
    }

my blade file of this client app :

@extends('layouts.app')

@push('title')
    Dashboard
@endpush

@section('main_sec')

// i want to use this following code instead of if else how can i use this
@role("Super Admin")
 {{ "YOU ARE SUPER ADMIN" }}
@elserole ("Admin")
{{ "You are admin" }}                    
@endrole

// i want to use this above code instead of if else how can i use this
@endsection

jlrdw's avatar

Look at the chapter on using passport.

1 like
mirzashahmir02's avatar

@jlrdw what do you mean by chapter owner using passport btw i am new to laravel and using jwt token

1 like

Please or to participate in this conversation.