Laravel passport Authorization token expire on generating new token - laravel

I am using laravel 5.5 with passport authentication for API Routes. I am using bearer token.
The problem is that the old generated token is accepted in place of unauthenticated.
Steps :
create one bearer token. Use it. It is working fine.
create another token without logout and it is working fine.
now if I use the first created token it is also working. It should not be working but it is accepted.
Is there any way by what I can achieve this?
Thanks in advance.

One possible solution is:
Check before creating a new token, if an old one is existing and delete this one. To do this:
Create a Model named OauthAccessToken
Update your User Model the following
/**
* 1:n zu access token, we need to logout users
*
* #return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function accessTokens()
{
return $this->hasMany(OauthAccessToken::class);
}
Now you can check with this and delete all tokens from a user
if ($user->accessTokens->count() > 0) {
$user->accessTokens()->delete();
}

Related

Magic Link login with Laravel Sanctum

For my project I have a set of users that should only be able to login by requesting a Magic Link. So they have an email address but no password. To avoid security issues, my goal was to get this working without having to save an authentication token in LocalStorage.
I've tried setting this up the following way with Laravel Sanctum:
When requested, I create a token for the user and email them the plaintext version.
The user would open the link containing the token in the querystring.
I would attach the (Bearer) token with the Authorization Header.
The next step (I assumed) would be to call a custom /api/login endpoint that uses the 'auth:sanctum' middleware. The Bearer token would authenticate the user and then I would manually login the user with Auth::login(). After this the active Session would be used to authenticate the user, thus avoiding having to save the token in localStorage.
But I can't call the Auth::login() method manually without getting an error (BadMethodCallException: Method Illuminate\Auth\RequestGuard::login does not exist.).
I can't figure out why this isn't working, or maybe I am going at this all wrong?
if you sending Sanctum token to user via email so in 1st request you will get token from url and you can use that token to login to application like this
use Laravel\Sanctum\PersonalAccessToken;
public function login(Request $request)
{
$personalAccessToken = PersonalAccessToken::findToken($request->token);
$user = $personalAccessToken->tokenable;
auth()->login($user);
return redirect('/');
}

Laravel sanctum SPA authentication logout is not working

I am using laravel sanctum SPA authentication in my Vue project.Everything is working well but even after logout
Auth::logout()
I am still able to get datas from api route inside middleware
Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
return $request->user();
});
I should not be able to get datas after logout.It should show 401 unauthenticated but its not the case.
How to solve this problem.I have been stuck here for 3 days.I followed laravel documentation and other tutorial as well but every one logged out same like I did.
Kindly use Auth::guard('web')->logout(); instead of Auth::logout(). look into SPA Log out issue
To Logout, a user simply do this in you logout function to delete all the user tokens
public function logout(Request $request) {
auth()->user()->tokens()->delete();
}
Or user this to remove only the active token
$request->user()->currentAccessToken()->delete();
What worked for me now is :
auth('sanctum')->user()->tokens()->delete();
In order to logout the specific user, You need to specify the user.
// Revoke a specific user token
Auth::user()->tokens()->where('id', $id)->delete();
// Get user who requested the logout
$user = request()->user(); //or Auth::user()
// Revoke current user token
$user->tokens()->where('id', $user->currentAccessToken()->id)->delete()

Unable to get authenticated user using Laravel 5.8 and Auth0

I have a Laravel 5.8 API that I want to secure using Auth0. So far I've followed every step of this tutorial:
On the front side, Login/logout links are currently implemented in Blade, and this works fine, though the rendered content on the page is done using Vue Router, making AJAX requests to the API for the data.
The default User model in Laravel has been modified to store name, sub, and email per the tutorial, and this populates as well.
The API endpoint is secured using the jwt middleware created during the tutorial, and I can successfully submit a GET along with a hard-coded Bearer auth token in Postman and get a good response.
However, at some point I'd like to be able to pass an access token off to Vue so it can do its thing, but I'm unable to get the current authenticated user. After hitting Auth0, it redirects back to my callback route with auth gobbledlygook in the URL. The route in turn loads a controller method, and everything even looks good there:
// Get the user related to the profile
$auth0User = $this->userRepository->getUserByUserInfo($profile); // returns good user
if ($auth0User) {
// If we have a user, we are going to log them in, but if
// there is an onLogin defined we need to allow the Laravel developer
// to implement the user as they want an also let them store it.
if ($service->hasOnLogin()) { // returns false
$user = $service->callOnLogin($auth0User);
} else {
// If not, the user will be fine
$user = $auth0User;
}
\Auth::login($user, $service->rememberUser()); // "normal" Laravel login flow?
}
I'm not an expert on the framework, but the last line above seems to start the "normal" Laravel user login flow. Given that, shouldn't I see something other than null when I do auth()->user(), or even app('auth0')->getUser()?
Try using a simple tutorial if you're a beginner, I would recommend this
It uses a simple JWT package to create a jwt token which you can get when the user authenticates.
JWTAuth::attempt(['email'=>$email,'password'=>$password]);

Dingo/Api and JWT auth

I'm looking for the way to implement auth with JWT and Dingo/Api. I've added JWT package to my project. Added 'jwt' => 'Dingo\Api\Auth\Provider\JWT', into my api.php auth part.
And also added into my BaseController
public function __construct()
{
$this->middleware('api.auth');
}
How do I check if the user has permission (by role) using FormRequest? It has an authorize method, however I'm not sure how to get my user.
Since I'm using JWT the token is sent in the headers.
One way to do it is to adding the role validation to the middleware.
You can try adding this custom validation to the part where it verifies the JWT the user gave as that is the part where you can determine who is the user that owns the token.
You can use the Auth Facade to retrieve the currently authenticated user:
$user = \Auth::user()
For authorization you can use policies, see https://laravel.com/docs/5.6/authorization
Once enabled you can check for a users ability in your authorize method(s), e.g.
public function authorize() {
$user = \Auth::user();
return $user->can("do-something");
}
But there are multiple possibilities how to perform authorization checks, read the docs mentioned above for more details.

How to update the access token expire_at (laravel passport) in laravel 5.4 without refresh the access token

I'm making a api with laravel passport, I made a token for one user with no duplicate user, I made a token to expire in 10 days, but I want to add functionality if the user is already logged in and logged on again with a different device still wearing the same token sehinnga in existing login function 2 conditions if the user logged on has not had a token or tokens expire then create a new token, if the user login is found token has not expired then the old tokens expire updates to 10 days from now without refresh token
You can delete old tokens while creating new token or on login. First of all you need to create OauthAccessToken Model.
For example,
Create following function in your user model
public function accessTokens() {
return $this->hasMany(OauthAccessToken::class);
}
And then check and delete the tokens
$user = User::whereId($id)->with('accessTokens')->first();
if ($user->accessTokens->count() > 0) {
$user->accessTokens()->delete();
}

Resources