Auth user showing Null in outside of auth api passport - php

I am developing an app where I am fetching user details with Laravel passport API get method with query string.
But when I put that route in auth API it shows "route login not found" and when I put outside auth API it shows Null when I call Auth::user().
Here is my route and my API with method:
Route::post('login', 'AuthController#login');
Route::post('register', 'AuthController#register');
Route::get('GetUserClaims', 'AuthController#GetUserClaims');
Route::group(['middleware' => 'auth:api'], function(){
//Route::get('details', 'AuthController#details');
//Route::get('GetUserClaims', 'AuthController#GetUserClaims');
});
http://xxx.xxx.xxx.xxx/public/api/GetUserClaims?userKey=eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp0aSI6Ijg3M2E4NTdhZmViMGVhMzAzNWQ5ZGU5NGZmNTUzMmI4NGUyMDZjZjE0MjRhYzQxZjI0YjUwYjdmZjc4OWZmYjM5YzhmNjBlZjRmYzM0OTQzIn0.eyJhdWQiOiIxIiwianRpIjoiODczYTg1N2FmZWIwZWEzMDM1ZDlkZTk0ZmY1NTMyYjg0ZTIwNmNmMTQyNGFjNDFmMjRiNTBiN2ZmNzg5ZmZiMzljOGY2MGVmNGZjMzQ5NDMiLCJpYXQiOjE1ODUwODU5NDksIm5iZiI6MTU4NTA4NTk0OSwiZXhwIjoxNjE2NjIxOTQ5LCJzdWIiOiI2Iiwic2NvcGVzIjpbXX0.VXKRTTpZxMGq4gR8kdu9qREBvhxSfPz4WureEYCpr-nh-qMFqkuR9Q10oa4AotmNmIABRFb_ijyrpt1AVJOpPU4b0R4lEnUWq746wh3etBg37fuSvDx8XDwF84NcOyU1GNnXDZ0KLbwr4YjrOqtuPNBAtkDEPHOKUYdxHvYOUSqt8YIx-L1p2ijHEvYDKroG8-B9mZs97HCtgSpwqTv7b5I0hEV4b1Ifkm24qDhoRMvaSYDFGcu52VWfwPjMEq6NPDYwwBx9Jpv_wv8-UA8BZPqECzE-D7xw46X4IhUNg9PyGxhtWbMvipz1E1OFzb_lBmgYTU5JVx0s0wmmcjqAq4jlfHNarUdBQGziJR4m3rLBGYNtLmqQ4kR1knrhaR-qQYaKiQNknxtb7c_HG724G_XSYkzFJZUalLFtQkDYpXSSP-QgzKFrQHblE6Led2AwPqt4S4svDOht5hqg29TejNbggIztj_fs9u2cwso1VvPjAM1LLG8chzVT5PM6YTihDGaVf4VEUaQmClgG64pEq2TmJISTLsplqlG1wn2BTdmCcO69VZYBvLJvjDlm942RGAYaNHD7Wt3RbJxMOH3RF8OGRP_H2IvIwtWz4x29dDUg8fMEKlA-nM1A8wsrK-YFkbwrY-IOzHl-4MdPopmXiFViB5RPMkQdCMd0ItWTjgA
public function GetUserClaims(Request $request)
{
if ( $request->has('userKey') ){
$user = Auth::user();
$token = $request->userKey;
var_dump($user);
//$token='Bearer '.$request->bearerToken();
//$request->header('Authorization',$token);
//return response()->json(['user' => auth()->user()], 200);
//return response()->json(['success' => $user], Response::HTTP_OK);
}
}

I think you can refer to the solution below to solved you issue.
Laravel 7 filters
The guide lead you about how to setup Laravel Authentication which include at Laravel package.
You don't have to build out from scratch by yourself

Related

Can you see my routes and config with sanctum

Using https://laravel.com/docs/9.x/sanctum , I'm try create API application.
Generating token is ok.
But when I try to restrict my endpoint to authorized users with middleware, any check permission didn't work, endpoint is accessible for all.
In controller I tested with debug auth('sanctum')->check() - and I became true for valid token and false else.
My routes/api.php
Route::post('login', [AuthController::class, 'login']);
Route::group(['middleware' => ['auth:sanctum']], function () {
Route::post('logout', [AuthController::class, 'logout']);
Route::group([
'prefix' => 'services/{service}',
'where' => [
'service' => implode('|', array_column(ServiceEnum::cases(), 'name'))
]],
function () {
Route::get('accounts/{account}/balance', [AccountController::class, 'getBalance']);
});
});
It was my fail.
I recreate a project with new fresh laravel (something was broken with installing laravel passport) and then solve a problem with empty auth user in constructor of controller:
public function __construct(Request $request)
{
$this->middleware(function ($request, $next) {
$this->user = auth()->user();
return $next($request);
});
}

How get access token after autorization laravel sanctum?

Hello i'm newbie in laravel. I use for authorization sanctum. But i want that some request can available for authorization user (i use laravel for only api, on front i use angular 2).
web.php:
Route::group(['middleware' => ['auth:sanctum']], function () {
Route::post('api/user-information', function(Request $request) {
return response()->json([ auth()->user()]);
});
// API route for logout user
Route::post('api/logout', [AuthController::class, 'logout']);
});
How can I get access token after success autorization user that i can send request for middleware routes. Because if i have request withous access token i always send null in 'api/user-information'. Please help me resolve this problem.
You could better make a new function in a controller, probably the AuthController. In this function you can validate fields
$validatedData = $request->validate([
'email' => ['required', 'email'],
'password' => ['required'],
]);
With the validated data you can use Auth::login($validatedData);
Source: https://laravel.com/docs/9.x/authentication#login-throttling
Welcome to Laravel! I am assuming you have login method that authenticates user. You can create a token in that method and pass it to your frontend.
public function login(Request $request)
{
$request->validate([
'email' => 'required|email',
'password' => 'required',
]);
$user = User::where('email', $request->email)->first();
if (! $user || ! Hash::check($request->password, $user->password)) {
return ['status'=>0,'message'=>'Invalid Credentials','data'=>[]];
}
$data = [
'user'=>$user,
'token'=>$user->createToken('MyToken')->plainTextToken
];
return ['status'=>1, 'message'=>'Login Successful!', 'data'=>$data];
}
If you just need to pass the token, you can simply return token in the response and then pass it in request header (Authorization) of your Angular applcation to access the API routes protected by Sanctum middleware auth:sanctum
return $user->createToken('MyToken')->plainTextToken;
Also since you are going to use Laravel for API, I would suggest you put all your routes in routes/api.php file.
The routes in routes/api.php are stateless and are assigned the api middleware group. The prefix '/api' is applied to all the routes defined in api.php
You can read more about it in Laravel Documentation
Issuing API Tokens
The Default Route Files

How to access model method based on api auth in laravel 5.6?

I have user cars having many to many relation between users and cars. I am using passport and everthing is working properly (Sign-in, Sign-up etc) In my I have a method like below in Users Model
public function cars()
{
return $this->belongsToMany(Car::class, 'users_cars', 'user_id', 'car_id');
}
I also have API auth routes which is working fine
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');
Route::get('car-list','CarController#carList');
});
});
And in CarController I am trying to get user cars based on auth login user_id as like below
public function carList(){
$User = new User();
return new CarResource($User->cars());
}
I am also using API resource for API's
use App\Http\Resources\Car as CarResource;
But it does not working so can someone kindly guide me how to fix the issue. I would appreciate, thank you so much.
In the CarController you are instantiating a new User object. They are never going to have any cars. If you want to get all the cars that the user who is logged in, you will need to do something like the following:
public function carList(){
$User = User::with('cars')->findOrFail(Auth::id());
return new CarResource($User->cars);
}

Laravel Refreshing JWT tokens

I have a small Lumen / Laravel app that is just used as an API. I am able to sign in and set JWT tokens but after a period of time they timeout, I was expecting them to refresh each time an Endpoint was hit.
I've been looking at the docs for Tymon's JWT-AUTH but I cannot seem to get it to work.
Below is an example of one of my end points which return an array of all the users in the db. But when the token timesout the endpoint returns the error You don't have previleges to view all users
I'd be very grateful if someone was able to advise me or show me how to make my code refresh a token when someone is hitting an endpoint.
Inside Controller
public function index(Request $request)
{
$user = JWTAuth::parseToken()->authenticate();
if (!$user->isAdmin()) {
return $this->error_respond(['error' => "You don't have previleges to view all users"]);
}
$users = $this->repository->findAllWithPlan();
return $this->respond(['users' => $users]);
}
Inside Routes.php
$app->group(['middleware' => 'jwt.auth'], function ($app) {
/**
* Show All users
*/
$app->get(
'users',
[
'as' => 'user.all',
'middleware' => 'cors',
'uses' => 'App\Http\Controllers\UserController#index'
]
);
});

JWT-Auth for Laravel Dingo API package not able to login

I have been trying to implement the JWT-Aut in Laravel's Dingo API package, but I am stuck at users Login part, I have checked the official docs for auth but cant figure out, here is what I have done till now.
Protected the routes
Route::api(['version' => 'v1', 'protected' => true], function () {
Route::resource('users', 'UserController');
});
Added JWT auth provider in dingo/config
'jwt' => function ($app) {
return new Dingo\Api\Auth\JWTProvider($app['tymon.jwt.auth']);
}
Installed the JWT-Auth from Github docs
Tried Login using below sample code from JWT-Auth docs using Postman but getting {token : false}
Route::post('auth/login', function () {
$credentials = Input::only('email', 'password');
if ( ! $token = JWTAuth::attempt($credentials) )
{
// return 401 error response
}
return Response::json(compact('token'));
});
If someone can guide how I can login logout, & signup user and make a request with Authorization: Bearer <token> will be very helpful.
If someone could share your auth controller for same will be lifesaver :)
It looks like you are not returning a response when the credentials are incorrect - so the token will be equal to false in that case.
Here is an example:
Route::post('auth/login', function () {
$credentials = Input::only('email', 'password');
if ( ! $token = JWTAuth::attempt($credentials) )
{
// return the 401 response
return Response::json(['error' => 'invalid_credentials'], 401);
}
return Response::json(compact('token'));
});

Categories