JWT Auth for Laravel - laravel

I am trying to authenticate a user from App, and I have written the API in laravel. I want to know what is the difference between JWTAuth::fromUser($user),JWTAuth::toUser($user) and JWTAuth::attempt($user) and any advantages over using it?

JWTAuth::fromUser($user)
If you have user instance already and want to generate token for that user then you use fromUser
$token = JWTAuth::fromUser($user);
JWTAuth::attempt($user)
This function is used to authenticate user from credentials and if authenticate success then it generate token for authenticated user
if (! $token = JWTAuth::attempt($credentials)) {
return Response::json(['error' => 'invalid_credentials'], 401);
}
JWTAuth::toUser($user)
When you want to get user from token then you use toUser method. like this
$user = JWTAuth::toUser($token);
For details you can check it here https://github.com/tymondesigns/jwt-auth/wiki/Creating-Tokens

Related

Create session on consuming login with api on laravel

I have an api that has a method to start and I am calling it from a frontend project.
In the front end project I use Guzzle to make the call via post to the api and login, from which I get back a json with the user data and a jwt token.
But when I receive the token as I manage the session, I must create a session and save the token, since the laravel to authenticate I need a model user and have a database, which of course I do not have in this backend because I call the api to log in, which brings a token and user data, then as I manage it from the backend, I'm a little lost there.
$api = new Api();
$response = $api->loginapi(['user'=>'wings#test.com','password'=>'123']);
Because here I could not do Auth::login($user) to generate the session.
Because I don't have here the database because the login is done from the api.
There I call the api, of which the answer is the token, but how do I manage it from here, creating a session? saving the token?
thanks for your help.
With api, you don't usually manage a session. usually, you'd call something like
Auth::attempt([
'email' => 'me#example.com',
'password' => 'myPassword'
]);
If the credentials are correct, laravel will include a Set-Cookie header in response, and, that is how you authenticate with api. Via an auth cookie. You don't need to do anything else.
Let's show you how:
//AuthController.php
public function login(Request $request) {
$validatedData = $request->validate([
'email' => 'required|email',
'password' => 'required'
]);
if(Auth::attempt($validatedData)){
return ['success' => 'true'];
}
else{
return ['success' => false, 'message' => 'Email or password Invalid'];
}
}
public function currentUser (){
return Auth::user();
}
Now, the APi file
Route::post('/login', ['App\Http\Controllers\AuthController', 'login']);
Route::get('/current_user', ['App\Http\Controllers\AuthController', 'currentUser']);
Now if you make a call to /api/current_user initially, you'll get null response since you're not currently logged in. But once you make request to /api/login and you get a successful response, you are now logged in. Now if you go to /api/current_user, you should see that you're already logged in.
Important ::
If you are using fetch, you need to include credentials if you're using something other than fetch, check out how to use credentials with that library or api
You want to use the API to authenticate and then use the SessionGuard to create session including the remember_me handling.
This is the default login controller endpoint for logging in. You don't want to change this, as it makes sure that user's do not have endless login attempts (protects for brut-force attacks) and redirects to your current location.
public function login(Request $request)
{
$this->validateLogin($request);
// If the class is using the ThrottlesLogins trait, we can automatically throttle
// the login attempts for this application. We'll key this by the username and
// the IP address of the client making these requests into this application.
if (method_exists($this, 'hasTooManyLoginAttempts') &&
$this->hasTooManyLoginAttempts($request)) {
$this->fireLockoutEvent($request);
return $this->sendLockoutResponse($request);
}
if ($this->attemptLogin($request)) {
if ($request->hasSession()) {
$request->session()->put('auth.password_confirmed_at', time());
}
return $this->sendLoginResponse($request);
}
// If the login attempt was unsuccessful we will increment the number of attempts
// to login and redirect the user back to the login form. Of course, when this
// user surpasses their maximum number of attempts they will get locked out.
$this->incrementLoginAttempts($request);
return $this->sendFailedLoginResponse($request);
}
The core happens when we try to "attemptLogin" at
protected function attemptLogin(Request $request)
{
return $this->guard()->attempt(
$this->credentials($request), $request->boolean('remember')
);
}
When using the SessioGurad (which is default) the method attemptLogin fires a couple of events, checks if the user has valid credentials (by hashing the password and matching it with db) and then logs the user in, including the remember me functionality.
Now, if you don't care about events, you can just check from your API if the credentials match and then use the login method from the guard. This will also handle the remember me functionality. Something like this:
protected function attemptLogin(Request $request)
{
$username = $request->input($this->username());
$password = $request->input('password');
$result = \Illuminate\Support\Facades\Http::post(env('YOUR_API_DOMAIN') . '/api/v0/login' , [
'username' => $username,
'password' => $password
])->json();
if(empty($result['success'])){
return false;
}
// Maybe you need to create the user here if the login is for the first time?
$user = User::where('username', '=', $username)->first();
$this->guard()->login(
$user, $request->boolean('remember')
);
return true;
}

Create token in laravel passport without verify auth

I already use login by active directory and after verify username and password from active directory if correct I want to create access token in laravel passport. But I can't create token without verify Auth in laravel.
I try this code after verify from active directory
$success['token'] = createToken($email)->accessToken;
Error:
Call to undefined function App\Http\Controllers\API\createToken()
How to create access token in laravel passport without using Auth?
After Successfully Login attempt you can create token like.
if (!auth()->attempt($loginData)) {
return response(['message' => 'Invalid credentials']);
}
$accessToken = auth()->user()->createToken('authToken')->accessToken;
OR
$user = User::find($id);
$accessToken = $user->createToken('authToken')->accessToken;

How to store Auth session

I'm new in Laravel and firebase and I did the login and password validation by myself, but I would like to use the Route::group(['middleware' => ['auth']]), function to protect unauthorized access to the system, but I don't know how to tell Laravel that the user is already authenticated without using Auth::attempt($credentials).
So how can I set the user is authenticated already, redirect the user to main page passing the login(name of the user) to Auth.
if (Auth::attempt($credentials)) { //I need to replace this line setting the user is logged already
return redirect()->route('home');
}
I tried: Auth()->login($nickname);
But I received:
Argument 1 passed to Illuminate\Auth\SessionGuard::login() must be an instance of Illuminate\Contracts\Auth\Authenticatable, string given
Auth()->login($user);
is the right method, you should pass $user object instead of a string which includes user nickname, for example:
$use = new User();
$user->id = 1;
$user->email = 'eshtiaghi.amin#gmail.com';
$user->name = $nickname;
$user->save();
\Auth::login($user);

JWT laravel: check auth. Cannot check if user is authenticated even i have set the token

I'm trying make a mobile application with vue and i'm using jwt in laravel.
On first login, I can access the auth()->check() then I get false after the app is cancelled. I'm saving the token. I'm saving the token in local storage. How can I get the authenticated user.
controller:
public function JwtAuth(){
if($this->getAuthenticatedUser()){
return $this->JwtUser = $this->getAuthenticatedUser();
}
return [];
}
I want to acheive something like:
if(auth()->user()){
$user = "something";
}else{
$user = '';
}
return $user;
So sometime I will have token and sometime i dont .. how to check?

How to authorize user in laravel

We have auth microservice and an admin panel based on laravel. We login user by calling auth api and returning user id and token. How I could make user as authorized in laravel 5.3? I did not found any information googling.
$request = Request();
$authorize = new Authorize();
$response = $authorize->logIn($request->all());
if ($response->status == 'success') {
$user = new User();
$userResponse = $user->getUser($response->data->id);
Session::put('userId', $response->data->id);
Session::put('userToken', $response->data->token);
Session::put('userData', $userResponse);
if ($request->input('save_login')) {
Cookie::queue(Cookie::make('savedLogin', $request->input('login'), 129600, null, null, false, false));
} else {
Cookie::queue(Cookie::forget('savedLogin'));
}
return redirect('/');
}
You can manually log in the user with either the id or the User Instance.
From the docs:
Authenticate A User Instance
If you need to log an existing user instance into your application,
you may call the login method with the user instance. The given object
must be an implementation of the
Illuminate\Contracts\Auth\Authenticatable contract. Of course, the
App\User model included with Laravel already implements this
interface:
Auth::login($user);
// Login and "remember" the given user...
Auth::login($user, true);
Authenticate A User By ID
To log a user into the application by their ID, you may use the
loginUsingId method. This method accepts the primary key of the user
you wish to authenticate:
Auth::loginUsingId(1);
// Login and "remember" the given user...
Auth::loginUsingId(1, true);

Resources