I'm new to Laravel and JWT-auth. I've implemented the process of generating JWT tokens and getting the associated user in my back-end, but I'm still can not understand how the server verifies the authentication of a user from just a token stored on the client side.
If I log in on machine A and change my password on machine B, can I still log in from machine A with the previous token?
You have a 'users' table and generally another table like 'sessions'. When a user makes a request to login through your API, a new line into the 'sessions' table is inserted (the token is saved) and the API return the token to the user. For all requests that need authentification, the user will have to give this token (through HTTP header for example).
When you want to authentificate a user on a request you have to verify if the token exists and remains valid and then retrieve the user. Example in Lumen :
$this->app['auth']->viaRequest('api', function ($request) {
$session = Session::where(['token' => $request->header('token')])->get(); //user gives his token in the header request
if($session){
return $session->user(); //you have setup the hasOne/hasMany relationship between sessions and users
//the user is authenticated
}
return null;
// the user is not authenticated
});
"If I log in on machine A and change my password on machine B, can I still log in from machine A with the previous token?"
If the token is still valid and you allow multiple active sessions then yes. The token isn't set depending of the password.
Related
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('/');
}
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();
So i read about how authentication is done using JWT, where we basically verify if the token is valid using a private key (assuming RSA is the algortihm). And if the token is valid, then the user is considered authenticated. And I also read about session authentication where we check if the user supplied session id (through cookie), exist in the session store (assuming mysql / redis is used to store session). If it exist, then the user is considered authenticated.
But how do we use JWT and session for authorization ? Lets consider an action such as GET invoice , whereby a user can only view the invoice that he owns.
If we consider the user is already authenticated,
how do we check if the user is authorized if we are using JWT?
And how do we do it for session ?
You are probably confusing the things. One of the benefits using JWT is to avoid maintaining sessions which is big bottle neck in scaling.
JWT (Json Web Token) carry all the information that would require it to get authenticated, you don't need to maintain the session. Every single HTTP request to server will carry JWT that would contain necessary user claims including the signature. On server you will validate the signature to verify if the token is valid or not. You can verify the token without maintaining any session and there are number of ways to do it.
Since JWT is essentially a Json object (Header, Body , Signature) , you can put in claims (emails, roles, profile etc) in JWT body. Once you verify the token , you can extract the claims including any roles and check if user is authorized to access the resource.
You must look into Open ID Connect and Tokens here
I am developing a laravel API(MyAPI) with the 5.1 version.I am connecting to this API from a widget which hosted in another website.it has a separate API(hostAPI). I need to authenticate user when widget loaded.
following are my requirement.
" When the widget loads it will attempt to authenticate. It will send a request to the MyAPI with
{
username: username,
token: token
}
MyAPI will POST this information on to the hostAPI. This will return either success or a 401.
On sucess, we log the user in. We may need to create an account if an user with that name does not exist"
how can i auth a user with only username and a token key
Is not a good practice to login user by user interface.
But it is an option and maybe in your case you can use that.
So you know only the username, and token.
I think you can query the database based on you username and token . find the user and login the selected one :)
Example:
$user=User::where('username',$username)->where('token',$token)->first();
Auth::login($user);
return Auth::user();
In case you want to create the user if it does not exist:
$user=User::where('username',$username)->where('token',$token)->firstOrCreate(['username' => $username,'token'=>$token]);
I'm new to server developing,and there is a question:
when user logins,what will be returned by server to identify the user so that when user next logins they needn't to input username and password again,and what will be saved in server to record state of users,saved in memory or database.And will the solution will be different among mobile app and website?
I'm confused about this,anyone can teach me,thanks!
There exist many authentication mechanisms with different properties to authenticate a client to a server.
The easiest one is with Sessions and I suggest you to start with it. The basic idea is that when a user succesfully login, the server generates a big unique random number (usually with an expiration time) and send it back to the user. Both client and server store this value somewhere. Next time the user performs a request, it sends back the session id and in this way the server knows it is the user that previously logged in. This mechanism is supported in almost every language and you can handle it very easily.
Another interesting authentication mechanism is called JWT (Json Web Token). In this case the server generates a self-contained token that user uses for future requests. In this case the server doesn't have to store the token because the needed information is embedded in the token itself. You can find all the necessary information and resources here: https://jwt.io/ .
There are also other standards to perform authentication that are slightly more complicated. One of the most popular is OAuth (https://en.wikipedia.org/wiki/OAuth).
When user sends his username/password, generate a session token. Then, store that token at the client side (as a cookie if using a browser for example). On the server side, you can save it in presistent store (database) if you need to keep it for long time, or in memory (user session).
Afterwards, the user needs to send that token to identify himself instead of re-sending his username/password each time. The session token can be sent in several ways; through cookies, Authorization header, post body, etc.
Also, consider sending the session token through a secure connection (https) for security concern, and check for session expiry as well.
You have to use session storage.
An example, in common page :
<?php
session_start();
if(!isset($_SESSION)) {
//Redirection to login page
header('Location: loginPage.php');
} else {
//User is log
var_dump($_SESSION);
}
And in login page :
<?php
session_start();
//Your query for verifing is username and password matched
$isMatched = true;
if($isMatched) {
$_SESSION['userId'] = 45687; //Id of the user
//You can save what you want in this session
}
And on every page you can retrieve the data save with $_SESSION['theValueYouSet']