Laravel Vue JWT Authentication - How to automatically login the user after login - laravel

I can find anything on web getting this done. I understand a token has to be generated before a user can login, but is there a way to automatically log in the user after they register? Here my register method.
public function register(Request $request)
{
$v = Validator::make($request->all(), [
'email' => 'required|string|email|unique:users|max:255',
'password' => 'required|min:8|confirmed',
]);
if ($v->fails())
{
return response()->json([
'status' => 'error',
'errors' => $v->errors()
], 422);
}
$user = new User;
$user->email = $request->email;
$user->password = bcrypt($request->password);
$user->save();
return response()->json(['status' => 'success'], 200);
}

You are using JWT tokens so after registration you have to send a token belongs to the user which tells other API that this is the logged-in user.
Generate JWT token and return the response with token
$token = JWTAuth::fromUser($user);
return response()->json(['status' => 'success', 'token' => $token], 200);

you can use below methods
Auth::loginUsingId(1);
or
Auth::login($user);

Related

Laravel Socialite Call Back Redirect To Login Again After Auth Login

I'm using Laravel socialiteproviders Microsoft for authentication. The callback is working fine and user details also return correctly. But after I check some conditions and redirect to user profile it navigates to login again.
public function Callback($provider) {
$userSocial = Socialite::driver($provider)->stateless()->user();
$user = User::where(['email' => $userSocial->getEmail()])->first();
if($user) {
Auth::login($user);
return redirect()->route('profile');
} else {
$user = User::create([
'name' => $userSocial->getName(),
'email' => $userSocial->getEmail(),
'provider_id' => $userSocial->getId(),
'provider' => $provider,
]);
Auth::login($user);
return redirect()->route('profile');
}
}

Laravel 8 connection at the web app with api

For my job, I have to make an app which never use the database directly. I have to only request an API even for the connection.
So... There is my problem. I try to make an auth with a user that i'm getting from API but i'm always redirect to the login page.
My API auth :
public function login(Request $request)
{
$credentials = request(['use_username', 'password']);
$this->guard()->factory()->setTTL(config('jwt.ttl') * 12);
if (!$token = $this->guard()->attempt($credentials)) {
return response()->json(['error' => 'Unauthorized'], 401);
}
$user = auth()->user();
return $this->respondWithToken($user, $token);
}
protected function respondWithToken($user, $token)
{
$cookie = cookie('jwt', $token, 60 * 12); // 12h
return response()->json([
'user' => $user,
'token' => $token
])->withCookie($cookie);
}
My web app auth :
public function login(Request $request)
{
$response = Http::post(env('app_url').'/api/auth/login', $request->only('use_username', 'password'));
$cookie = cookie('jwt', $response['token'], 60 * 12); // 12h
$user = ( new User() )->forceFill( $response['user'] );
if (Auth::login($user)) {
$request->session()->regenerate();
return redirect('/');
}
flash('error')->error();
return back()->withErrors([
'email' => 'The provided credentials do not match our records.',
]);
}
My API guard (default guard) :
'api' => [
'driver' => 'jwt',
'provider' => 'users',
'hash' => false
]
The goal is to authenticate the user in the API, get a JWT token and auth the user in the web app with the same user that got in the API. After, all my request to the API have to use the JWT token get during the login... Maybe with a HttpOnly cookie ?
Well, i can't connect my user to the web app, i'm always unauthenticate and redirect to th elogin form, can someone help me ?
I'm using tymon/jwt-auth library with PHP 8

Why is the request user null in my logout function?

I am implementing an Authentication api in Laravel using passport.
I have implemented the login api, but there is a problem with logout api. My login code is working successfully:
public function login(Request $request){
$request->validate([
'email'=> 'required|string|email',
'password'=> 'required|string',
'remember_me'=> 'boolean',
]);
$credentials= request(['email','password']);
if(!Auth::attempt(['email' => $request->email, 'password' => $request->password])){
return response()->json([
'message'=> 'Unauthorized'
],401);
}
Auth::attempt(['email' => $request->email, 'password' => $request->password]);
$user=$request->user();
$tokenResult = $user->createToken('Personal Access Token');
$token = $tokenResult->token;
if($request->remember_me)
$token->expires_at= Carbon::now()->addWeek(1);
$token->save();
return response()->json([
'access_token'=>$tokenResult->accessToken,
'token_type'=>'Bearer',
'expires_at'=>Carbon::parse($tokenResult->token->expires_at)
->toDateTimeString()
]);
}
This works successfully, however, when I use the same bearer token to revoke the token of the user I am receiving the following exception:
Call to a member function token() on null
This is referring to the first line of the logout method below.
public function logout(Request $request){
$request->user()->token()->revoke();
return response()->json([
'message'=> 'Successfully logged out'
]);
}
Why is the output of $request->user() null?
Create a token for the authenticated user, not the guest user who made the request
$user= auth()->user();
$tokenResult = $user->createToken('Personal Access Token');
$token = $tokenResult->accessToken;
And when revoking
public function logout(Request $request)
{
auth()->user()->token()->revoke();
return response()->json([
'message'=> 'Successfully logged out'
]);
}
Hope this helps

Laravel socialite with passport unsupported grant type

I am trying to generate a bearer token with access and refresh tokens after user authenticates with socialite.
public function handleProviderCallback($provider, EmailConfirmationMailer $mailer)
{
$user = Socialite::driver($provider)->user();
if(User::where('email', '=', $user->getEmail())->exists()){
$exist_user = User::where('email', '=', $user->getEmail())->first();
Auth::loginUsingId($exist_user->id);
$http = new GuzzleHttp\Client;
$response = $http->post('http://localhost:8000/oauth/token', [
'form_params' => [
'grant_type' => 'refresh_token',
'refresh_token' => 'the-refresh-token',
'client_id' => 1,
'client_secret' => 'c4ojSmOjl04QrshdSXlOmbKUOIxm6zqyhND34AT0',
'scope' => '',
],
]);
return json_decode((string) $response->getBody(), true);
}else{
//create new user here
}
}
I got the error from vendor\laravel\socialite\src\Two\AbstractProvider.php
user function, message is "".
public function user()
{
if ($this->hasInvalidState()) {
throw new InvalidStateException;//here is the highlighted
}
$response = $this->getAccessTokenResponse($this->getCode());
$user = $this->mapUserToObject($this->getUserByToken(
$token = Arr::get($response, 'access_token')
));
return $user->setToken($token)
->setRefreshToken(Arr::get($response, 'refresh_token'))
->setExpiresIn(Arr::get($response, 'expires_in'));
}
What is the best practice for this situation? Any help is greatly appreciated.
resorted to generate accessToken with no refreshToken:
public function handleProviderCallback($provider)
{
$user = Socialite::driver($provider)->user();
if(User::where('email', '=', $user->getEmail())->exists()){
$existUser = User::where('email', '=', $user->getEmail())->first();
Auth::login($existUser,true);
//remove existing tokens from user
$tokenResult = $existUser->createToken('Personal Access Token');
return \response()->json([
'token_type' => 'Bearer',
'expires_in' => $tokenResult->token->expires_at->diffInSeconds(Carbon::now()),
'access_token' => $tokenResult->accessToken,
'info' => 'Existing user'
]);
}else{
//create new user entry
}
}

Redirect to view after API login using Passport

I added API authentication to my Laravel app using passport. I followed this tutorial:
https://medium.com/techcompose/create-rest-api-in-laravel-with-authentication-using-passport-133a1678a876
Now how do I redirect to a view after the user is been authenticated? I need this to embed my webapp to another portal using single sign on.
This returns the user values:
public function details()
{
$user = Auth::user();
return response()->json(['success' => $user], $this->successStatus);
}
This tells me the user is unauthorized:
public function details()
{
$user = Auth::user();
return redirect('/home');
}
This is my route:
Route::post('details', 'API\UserController#details')->middleware('auth:api');
This is my login:
public function login(){
if(Auth::attempt(['email' => request('email'), 'password' => request('password')])){
$user = Auth::user();
$success['token'] = $user->createToken('MyApp')->accessToken;
return response()->json(['success' => $success], $this-> successStatus);
}
else{
return response()->json(['error'=>'Unauthorised'], 401);
}
}
You can validate user after
Auth::attempt(['email' => request('email'), 'password' => request('password')])
if(Auth::check())
return redirect()->route('<route_name>');

Resources