简体   繁体   中英

create a get api using Authorization token in laravel

i have a registraion api that register user details to database it also genrates token using laravel passport and saves the token into database

now i am trying to create a get api that will fetch all data from database using token generated

what i have tryed

in api.php

Route::get('/get_user', [userDEtails::class, 'get_user']);

userDEtails.php controler

public function get_user(Reqest $req)
{

// what code must i add here
    
}

in post man i want to add token in header as Authorization and api to work

i am using Laravel Framework 9.41.0

在此处输入图像描述

在此处输入图像描述

Since you've said you're using Laravel Passport for this, try doing this to get the user (and check scopes)

public function get_user(Request $request)
{
    $user = $request->user();
}

This should ideally work. You will also need to make sure that your route is using the 'auth:api' middleware for your route like this -

Route::get('/get_user', [userDEtails::class, 'get_user'])->middleware('auth:api');

If for some reason you can't use the 'auth:api' middleware for this route, and need to stick with 'web' or something else, you can use -

$user = auth()->guard('api')->user()

OR

$user = $request->user('api')

instead to get the user object.

To implement an API endpoint that requires an authorization token in Laravel, you will need to use the 'Auth' middleware and pass it to the route as an argument. Here is an example of how you can do this for your 'get_user' route:

Route::get('/get_user', [userDetails::class, 'get_user'])->middleware('auth:api');

This will require the client to include a valid authorization token in the request header in order to access the endpoint.

In the 'get_user' method of the 'userDetails' controller, you can then use the 'Auth' facade to retrieve the authenticated user:

public function get_user(Request $request)
{
    $user = Auth::user();

    // Now you can use the $user variable to retrieve and return the desired data from the database
}

Note that you will need to include the Illuminate\Support\Facades\Auth namespace at the top of the controller file.

I hope this helps. Let me know if you have any questions.

To fetch the data from the database using the token generated, you can follow the steps below: In your get_user function, first retrieve the token from the request header by using the header method on the request object.

$token = $req->header('Authorization');

Then you can use the TokenRepository provided by Laravel Passport to retrieve the authenticated user associated with the token. You can get an instance of the TokenRepository by using the app helper function:

$tokenRepository = app(TokenRepository::class);
$user = $tokenRepository->find($token);

If the token is valid and an associated user is found, you can then use the User model to fetch the data from the database:

$users = User::all();

Lastly,return the fetched data to the client by returning a JSON response

return response()->json($users);

But to take care of any unexpected error,add some error handling in case the token is invalid or an associated user is not found.

In Auth::check() , it will check token is valid or not. Based on that, it will return true or false .

public function get_user(Request $request)
{
    if (Auth::check()) {
        $users = User::all();
        return response()->json($users, 200);
    } else {
        return response()->json(['error' => 'Unauthorized'], 401);
    }
}

In addition, before you send a request to get_user() , write the login() method and get the access token. You can use passport or JWT


If you use a Laravel passport can use bearerToken() to get the token and Auth::checkToken() to validate the token.

If I understood correctly, what you're trying to do is return the information of a user. Therefore, you can do the following:

disclaimer: I assume your controller is named userDEtails (make sure you're not making any typos. Maybe you meant userDetails ?)

in api.php :

Route::get('/{user}', [userDEtails::class, 'get_user']); Here I changed the route, and just referenced the user parameter

public function get_user(User $user)
{
 $user = User::where('id', $user)->first();
 return response()->json([
            'user' => $user,
 ]);    
}

in this function, I'm referencing the User model (and you can see its related with the route in the api as {user} ).

This is one of the ways to do this.

If you need for the user to be logged in, then in your routes you might as well define the auth middleware:

Route::group([
    'middleware' => 'auth:api'
], function() {
   Route::get('/{user}', [userDEtails::class, 'get_user']);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM