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('/');
}
Related
Here is the context. I have two sites using the same domain.
The first using Laravel and view components The second is an "API", I use Laravel Sanctum. This API has a single user. Later, there will be a third site using this same API as well.
The API authentication system works perfectly. When I switch from Postman my user, my token is returned.
I'm wondering about token retrieval and usage on my first site using vue components.
My idea was to store API user login credentials in my .env file and retrieve the token in controllers where I use vue components.
Another solution would be to fetch my token on each call to the API, but that could be cumbersome.
Finally store the token at the user's connection and reuse it but where to store it, in session, in cookies,... Security level is not ideal.
Thanks in advance for your ideas.
The default thing to do to use token as a bearer token from the front end is as following
login attempt to backend and you will get the token to authenticate your request later.
store it using vuex store in you user store
then do your API request using that token
destroy the token after logout
if you are concerning about security, well the token should have expiration time and the token itself should be destroyed from the backend when the user is logged out. Every time the user do the login, new token will be created for them
If your API authentication is working properly, Then you've to store your token on the database every time the user logs in. And delete on some other occasions. To store your token on database every time the user logs in use the following code:
public function login(Request $request)
{
if (!Auth::attempt($request->only('email', 'password'))) {
return response()->json([
'message' => 'Invalid credential'
], 401);
}
$user = User::where('email', $request['email'])->firstOrFail();
//store the hashed token on db and return plain text token for the user
$token = $user->createToken('token_name')->plainTextToken;
return response()->json([
'access_token' => $token,
'token_type' => 'Bearer',
]);
}
I took the code from here
I used Laravel-8 for rest api. The route is shown below:
localhost:8888/myapp/server/api/v1/admin/role
It is a GET Request.
When I send it on POSTMAN, I got this error:
401Unauthorized
{
"message": "Unauthenticated."
}
In my route I have:
'middleware' => ['auth:api']]
The reason is because I don't know how to add the Login details. email: akwetey#gmail.com, password: mypass
How do I achieve this?
Thanks
This person walks you through the process nicely and should get you setup.
https://coding-lesson.com/api-authentication-with-laravel-passport/
Basically you need to:
Get to your login api, probably something like: localhost:8888/myapp/server/api/v1/login
Create a POST request to the login API, select the Body tab and define key values for you Email and Password
Then run the request and copy the AccessToken value from the results
Now with your API above, select the Authorization tab, choose Bearer Token as the Type and paste in your AccessToken value for the Token field
You should also go to your Headers table and define Accept and Content-Type keys, both with values of: application/json
Of course you'll want to then change all this to use variables after you get it right, so you don't have to keep repeating this with all your new API calls.
To fetch data behind protected routes you need to provide a token that will verify that the user who made the call is authenticated.
Then you have to provide the token in Authorization section of postman.
I assume you know the difference between Post and Get. Laravel works a little different then regular PHP, let me tell you how.
In order to access the protected routes you'll have to first access the token from login route. By sending the required data in .
Once that's done it'll return the token which can be used to access the protected routes under admin or auth middleware.
In your case you're accessing localhost:8888/myapp/server/api/v1/admin/role which is a protected route under admin middleware. You'll have to first access token and then send token with the get request to fetch the required data.
I have been created PWA with NuxtJS,
then I'm going to use sanctum package, but I don't want to request to the typical Laravel /login route, because I have a customized api /login route which authenticates users with OTP, not by password!
So I'm wonder how can I use sanctum in this situation??
You can use Sanctum's token based authentication to achieve this. All you have to do is add the HasApiTokens trait to your authenticable model and issue new tokens for it on a successful login. So you would have a route which will accept phone number or email and perform a login action. This would trigger the application to send OTP to the user. You have to store the OTP somewhere on the system. Then create another endpoint where user's can send back the OTP they received. This route will then check if the provided OTP matches the one on the system and issue a token to the user.
$token = $user->createToken(<provide-a-token-name>);
Make sure to send back the plaintext token to the user using the plainTextToken function on the token instance. User's will need to add this token to requests as a bearer token in the Authorization header.
Helo,
I would like to know how get token by user with laravel passeport ?
I don't want a user to access another user's resource.
I would like to verify that the user's token in the request corresponds to the user's token.
i get the request token with:
$token = $request->bearerToken();
i don't know how to get user token.
Thank you
If you've set up correctly then passport will keep track of the tokens of each user in each device. However, if you want to retrieve the token of the authenticated user simply use Auth::user()->token();
I've been trying to get authentication working (described below) in my laravel application, following these two tutorials:
https://auth0.com/docs/quickstart/webapp/laravel/01-login
https://auth0.com/docs/quickstart/backend/laravel/01-authorization
On the frontend (angular app):
User clicks log in button and taken to auth0 login page
The user logs in and is redirected back to the callback with the accessToken
The access token is stored on the frontend and passed to Laravel API each request.
On the backend:
User makes a request to my http://localhost/api/route passing the accessToken in the authorisation header
Laravel validates the user is logged in and valid.
Laravel allows access to that route
It works to an extend, but when I try to use postman to access the protected route by passing the accessToken I get the error:
"message": "We can't trust on a token issued by: https://myprojectname.au.auth0.com/."
Is my workflow correct? What am I missing?
Thanks!
Just in case if somebody facing with the same issue. The authorized_iss must contain a trailing slash.
In the laravel-auth0.php file the field,
'authorized_issuers' => 'https://myprojectname.au.auth0.com/'
should be in this form.