Login a User in laravel application after API endpoint authentication - laravel

I am working on this application where i created an API to do the business logic and using Laravel as the core part of my application that calls the API endpoints for resources.
Authentication is been done by the API which only returns a JSON resource. I am a bit confused as to what is the best way to log a user into my laravel application after successful authentication from the API.
//
public function login(Request $request)
{
$data = [
'username' => $request->username,
'password' => $request->password,
];
$data = Json_encode($data, TRUE);
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "http://localhost:8080/api/v1/auth/login",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => $data,
CURLOPT_HTTPHEADER => array(
"Content-Type: application/json"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
$response = Json_decode($response);
// var_dump($response);
if ($err) {
echo "cURL Error #:" . $err;
} else {
if ($response->status === 'failed') {
if ($response->message === "Incorrect login details") {
return redirect()->back()->with('error' , $response->message);
}elseif ($response->message === "User's account has not been activated") {
return view('activation', ['email' => $response->data]);
}
}elseif ($response->status === 'success' && $response->message === "Ok") {
$user = $response->data;
Auth::login($user , true);
return view('dashboard', ['user' => $user]);
}
}
After getting the required response from the API, intend logging the user straight into the application.
What is the best way for this?

If you have same database to connect with on the user. you can just simply call
Auth::loginUsingId($id);
this will automatically log in user with that id.

Related

Why does not my post request to an API using Guzzle not work?

I am trying to make a post request to the example URL endpoint. When I make a post request in my localhost, it works fine, but when I try to request live serve with the same come, it returns null every time. So if I make a request that time, my end point gives a response, but it returns null when I make a post request.
public function saveEnquiry($request)
{
$ClientObj = new Client();
$url = 'endpoint_base_url/v1/business/enquiry';
$data = [
'name' => $request->name,
'lastname' => $request->lastname,
'email' => $request->email,
'mobile' => $request->mobile,
'country_code' => $request->country_code,
'from_page' => $request->from_page,
'message' => $request->message,
'package_slug' => $request->package_slug,
];
$body = ['debug', true, 'form_params' => $data];
try {
$response = $ClientObj->request('POST', $url, $body);
$res = json_decode($response->getBody()->getContents(), true);
if ($res['success'] == true && $res['data'] != null) {
/// logic part
} else {
throw new TripshifuException($res['message']);
}
} catch (BadResponseException $e) {
throw new TripshifuException(json_decode($e->getResponse()->getBody()->getContents()));
}
}

$request->header('Authorization') return null using laravel

public function productData(Request $request)
{
$product_no = $request->product_no;
$response = array();
if($request->product_no)
{
try
{
$header = $request->header();
$Authorization = $request->header('Authorization');
dd($Authorization);
if (empty($Authorization))
{
$data = "Authorization key invalid";
return $data;
}
else
{
$sp_token = str_replace("Bearer ", "", $Authorization);
$varify_token = 'ZQWmRjUyNDJDQUFGRjBBOUMzMUZGQUVEOTA4QkYzOEU2RENBNEQ4OTIwMzRGQzY1NDA0QzIyMjk3RkJENkRzdsg=====';
if($sp_token == $varify_token)
{
$response = array(
'status' => 200,
'message' => 'success',
);
}
else
{
$response = array(
'status' => 300,
'message' => 'Invalid Bearer Token',
);
}
}
}
catch (\Exception $e)
{
$response = array(
'status' => 500,
'message' => 'Data Not Found',
'msgErr' => 'Something went wrong',
'result' => '0');
}
}
else
{
$response = array(
'status' => 0,
'message' => 'product Number Empty',
);
}
return response()->json($response);
}
Above code working in local server and when print $Authorization then it return Bearer Token but same code not working on production server when I hit API using production URL using postman then it return Authorization key invalid and when I print or dd $Authorization then it return null. I don't know why?. Please help me.
Thank you
The Authorization header might be stripped by your webserver or reverse proxy. Try renaming it to anything that isn't a default HTTP header. For example: Token.
Any route or url that uses Auth() must be encapsulated in the web middleware.
Let me explain using e.g
Route::group(['middleware' => '['web','auth']', function () {
Auth::user();
//Other auth routes
});

Laravel Sanctum with session issue when trying to logout and login

I am using the latest version of Laravel Sanctum to create a validation method for my SPA, but I ran into an issue(notice that I dont work that long with laravel). When I login it works, but when I logout and try to login it stops working. After some testing I noticed that this was because of a cookie that was added by laravel.
// loginController
public function login(Request $request)
{
if ($this->validator($request->all())->fails()) {
//validation stuff
} else {
$credentials = [
'email' => $request->email,
'password' => $request->password,
];
$user = User::where('email', $request->email)->firstOrFail();
if (auth()->attempt($credentials)) {
$token = $user->createToken('auth')->plainTextToken;
$response_code = 200;
$response = [
'user' => $user,
'success' => true,
'errors' => false,
'message' => 'Login successfully',
'access_token' => $token,
'token_type' => 'Bearer',
];
} else {
$response_code = 422;
$response = [
'success' => false,
'errors' => [],
'message' => 'Invalid login'
];
}
}
public function logout(Request $request)
{
$request->user()->tokens()->delete();
}

Laravel Passport how to login without a password, only using a mobile phone?

I get the following error when logging in with my mobile phone:
Uncaught (in promise) Error: Request failed with status code 422
how can i fix this?
My Controller
public function login(Request $request)
{
$req = Request::create(route('passport.token'), 'POST', [
//'grant_type' => 'password',
'client_id' => 2,
'client_secret' => '326g3KM3giN4o3UHITByxPLHaZlWzqfZbWs0vWLd',
'phone_number' => $request->phone_number,
//'password' => $request->password,
]);
$response = app()->handle($req);
if ($response->status() == 400) {
return response()->json([
'message' => ''
]);
} else if ($response->status() == 401) {
return response()->json([
'message' => ''
]);
}
return $response;
I also redefined functions in the user model
public function findForPassport($identifier) {
return $this->where('phone_number', $identifier)->first();
}
public function validateForPassportPasswordGrant($password)
{
return true;
}
I've read your description. So, you have to store phone and code in the table users. To simplify it, you can store code in DB field password as an encrypted value.
$user->phone_number = $request->phone_number;
$user->password = bcrypt($code);
And then during login you can use your own code:
$req = Request::create(route('passport.token'), 'POST', [
'grant_type' => 'password',
'client_id' => 2,
'client_secret' => '326g3KM3giN4o3UHITByxPLHaZlWzqfZbWs0vWLd',
'phone_number' => $request->phone_number,
'password' => $request->code,
]);
$response = app()->handle($req);

Laravel Passport. Why can’t I create an access token?

When I execute login, access token is not created, in the log files I get the following errors:
local.ERROR: The resource owner or authorization server denied the request.
and
(InvalidArgumentException(code: 0): The JWT string must have two dots at.
I made a request using the insomnia program and everything works fine there, the access token appears in the database
My function login:
public function login(Request $request)
{
$req = Request::create(route('passport.token'), 'POST', [
'grant_type' => 'password',
'client_id' => 2,
'client_secret' => 'lvDjvx5UgzeYJxQMjjLMSFL3psqXj2iuw2xLL6Yh',
'phone_number' => $request->phone_number,
'password' => $request->password,
]);
$response = app()->handle($req);
if ($response->status() == 400) {
return response()->json([
'message' => 'Н',
]);
} else if ($response->status() == 401) {
return response()->json([
'message' => '',
]);
}
return $response;
}
try this code:
public function login(Request $request)
{
$req = Request::create(route('passport.token'), 'POST', [
'grant_type' => 'password',
'client_id' => Your client_id,
'client_secret' => 'Your client_secret ',
'username' => $request->username,
'password' => $request->password
]);
$response = app()->handle($req);
if ($response->status() === 400) {
return response()->json([
'message' => 'Н',
]);
}
if ($response->status() === 401) {
return response()->json([
'message' => '',
]);
}
return $response;
}
In model User
public function findForPassport($identifier) {
return $this->where('phone_number', $identifier)->first();
}
Make sure "password_client" column is true in database for the client you're using.
If it's a "personal_access_token" it cannot provide password grant_type response. They are used to get client_credentials grant_type response.
You can find that out in your oauth_clients table.
I hope the answer will help you

Resources