Laravel Sanctum with session issue when trying to logout and login - laravel

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();
}

Related

how to get user access tokens

I have code in Laravel that allows users to log in using their OTP, and it will authenticate the login by using the OTP. For it to work on mobile, I need an access_token to show it as a response.
this is my code
public function phone_login_checker(Request $request){
$validator = Validator::make($request->all(), [
'phone' => 'required',
'otp_no' => 'required',
]);
if ($validator->fails()) {
return $this->sendError('', ['errors' => $validator->errors()]);
}
if ($user = DB::table('users')
-> where('otp_no', '=' , $request->input('otp_no'))
-> where('phone', '=' , $request->input('phone'))
->exists())
{
$userdetail = DB::table('users')-> where('phone', '=' , $request->input('phone'))->first();
Auth::loginUsingId($userdetail ->id, $remember = true);
$token = $userdetail->remember_token;
return response()->json([
'status'=>1,
'access_token' => "", // Here, I have to add the access token
'user' =>Auth::user(),
'token_type' => 'bearer',
'expires_in' => auth('api')->factory()->getTTL() * 60
]);
}
else{
return response()->json([
'action' => 'showError',
'type' => 'error',
'message' => 'otp is incorrect'
]);
}
}
how can i have access_token?

JwtAuth is not generating tokens in Backpack Laravel

I am using backpack laravel. Though I am also using Backpack's own authentication, yet I need to maintain a different customer table for App usage. For the customer table, I am using JWTAuth for token generation, but token generation gets failed each time.
public function register(Request $request)
{
$checkEmail = Customer::where('email', $request->email)->first();
if ($checkEmail) {
$response = [
'email_already_used' => true,
];
return response()->json($response);
}
$payload = [
'password' => \Hash::make($request->password),
'email' => $request->email,
'first_name' => $request->first_name,
'last_name' => $request->last_name,
'auth_token' => '',
];
try {
$user = new \App\Models\Customer($payload);
if ($user->save()) {
$token = self::getToken($request->email, $request->password); // generate user token
if (!is_string($token)) {
return response()->json(['success' => false, 'data' => 'Token generation failed'], 201);
}
$user = \App\Models\Customer::where('email', $request->email)->get()->first();
$user->auth_token = $token; // update user token
$user->save();
$response = [
'success' => true,
'data' => [
'id' => $user->id,
'auth_token' => $token,
'first_name' => $user->first_name,
'last_name' => $user->last_name,
'email' => $user->email,
],
];
} else {
$response = ['success' => false, 'data' => 'Couldnt register user'];
}
} catch (\Throwable $e) {
echo ($e);
$response = ['success' => false, 'data' => 'Couldnt register user.'];
return response()->json($response, 201);
}
return response()->json($response, 201);
}
I believe there might be some issue with guards.
Do I need to specify something in app/config.php for this?

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);

Auth::attempt value always false

I have some problem when I want to make login, I got an issue for my Auth::attempt always false value, Is am I got something wrong in my code?
Controller :
public function register(Request $register)
{
$validator = Validator::make($register->all(), [
'name' => 'required',
'email' => 'required|email',
'password' => 'required',
]);
if ($validator->fails()) {
return response()->json(['error' => $validator->errors()], 401);
} else {
$name = $register->input('name');
$email = $register->input('email');
$pwd = $register->input('password');
$c_pwd = $register->input('c_password');
// Crypting password & c_password to md5
$md5_pwd = md5($pwd);
$md5_c_pwd = md5($c_pwd);
// Salt password & c_password
$password = crypt($md5_pwd, "asd");
$c_password = crypt($md5_c_pwd, "asd");
$data = new User();
if ($password == $c_password) {
$user = User::create([
'name' => $name,
'email' => $email,
'password' => $password,
]);
$success['token'] = $user->createToken('SSOApp')->accessToken;
return response()->json([
'success' => true,
'token' => $success,
'user' => $user
]);
} else {
return response()->json(['error' => "Password doesn't match"], 401);
}
}
}
public function login()
{
$email = request('email');
$pwd = request('password');
$md5 = md5($pwd);
$password = crypt($md5, "asd");
if (Auth::attempt(['email' => $email, 'password' => $password])) {
$user = Auth::user();
$success['token'] = $user->createToken('SSOApp')->accessToken;
return response()->json([
'success' => true,
'token' => $success,
'user' => $user
]);
} else {
return response()->json([
'success' => false,
'message' => 'Invalid Email or Password',
], 401);
}
}
I assume you messed up with Laravel Default Password Hashing System
public function register(Request $register)
{
$validator = Validator::make($register->all(), [
'name' => 'required',
'email' => 'required|email',
'password' => 'required',
'c_password' => 'required|same:password',
]);
if ($validator->fails()) {
return response()->json(['error' => $validator->errors()], 401);
} else {
$name = $register->input('name');
$email = $register->input('email');
$pwd = $register->input('password');
$c_pwd = $register->input('c_password');
// $data = new User();
$user = User::create([
'name' => $name,
'email' => $email,
'password' => bcrypt($password . 'salt'),
]);
$success['token'] = $user->createToken('SSOApp')->accessToken;
return response()->json([
'success' => true,
'token' => $success,
'user' => $user
]);
}
}
public function login()
{
$email = request('email');
$pwd = request('password');
if (Auth::attempt(['email' => $email, 'password' => $password . 'salt'])) {
$user = Auth::user();
$success['token'] = $user->createToken('SSOApp')->accessToken;
return response()->json([
'success' => true,
'token' => $success,
'user' => $user
]);
} else {
return response()->json([
'success' => false,
'message' => 'Invalid Email or Password',
], 401);
}
}
Try this code. I don't know what happened to your code about the password you tried to encrypt it in attempt.
public function login(LoginRequest $request) {
if(!Auth::attempt([
'email' => $request->email,
'password' => $request->password,
'active' => true
])) {
return response()->json('Email or Password is incorrect', 500);
}
$this->user = Auth::user()->load('roles');
return $this->createUserAccessTokenResponse();
}
protected function createUserAccessTokenResponse() {
return response()->json([
'status' => 'success',
'data' => [
'token' => $this->user->createToken($this->user->name)->accessToken,
'user' => $this->user
],
], 200);
}
your problem is that laravel by default hashes the password. so when you do Auth::attempt it's going to hash the password you provided. And the result is what you get, it will always false.
Instead, you need to Other Authentication Methods.
Auth::login($user);
// Login and "remember" the given user...
Auth::login($user, true);
Above is the easiest way to fix your code.
It's recommended to hash your password rather than encrypting the password.
Hashing password in laravel is also
Hash::make($password);
And then you can use Auth::attempt to log in your user.
Laravel Auth uses the bcrypt hashing when saving password via model you may use either of the 2 method
$account->password = bcrypt("YOUR_PASSWORD"); or $account->password = Hash::make("YOUR_PASSWORD");
Then if you're dealing with the auth attempt function, just simply call the method like this
if($account = Auth::attemp(['email' => "YOUR_EMAIL#DOMAIN.COM", 'password' => "YOUR_PASSWORD"])){
//success login, do your extra job here
}else{
//invalid credentials here
}
Instead of using md5 or crypt use \Hash::make() it is much secure
I refactored your code and it does the same thing
You only need to rename your c_password to password_confirmation
Source
Below code does the same thing that your code do
public function register(Request $register)
{
$this->validate($register, [
'name' => 'required',
'email' => 'required|email',
'password' => 'required|confirmed',
]);
$user = User::create([
'name' => $register->input('name'),
'email' => $register->input('email'),
'password' => $register->input('password'),
]);
$success['token'] = $user->createToken('SSOApp')->accessToken;
return response()->json([
'success' => true,
'token' => $success,
'user' => $user,
]);
}
public function login(Request $request)
{
$request->merge(['password' => \Hash::make($request->input('password'))]);
if (Auth::attempt($request->only(['email', 'password']))) {
$user = Auth::user();
$success['token'] = $user->createToken('SSOApp')->accessToken;
return response()->json([
'success' => true,
'token' => $success,
'user' => $user,
]);
}
return response()->json([
'success' => false,
'message' => 'Invalid Email or Password',
], 401);
}
when you hashing password using crypt it has a key to unlock it that's why there is a decrypt but when you use Hash::make() it doesn't have a key to break or unlock it, it will check it's algorithm to see if given password is matching the algorithm that already exists in the database that's why crypt is not safe and Hash::make is much much more safe

Laravel Passport: Unauthenticated Message when asking for User Information

I want to implement Passport authentication in Laravel. this is the register function:
public function register(Request $request)
{
$credentials = $request->only('name', 'email', 'password');
$rules = [
'name' => 'required|max:100',
'email' => 'required|email|max:120|unique:users',
'password' => 'required',
];
$validator = Validator::make($credentials, $rules);
if($validator->fails()) {
return response()->json(['success'=> false, 'error'=> $validator->errors()]);
}
$user = User::create(['name' => $request->name, 'email' => $request->email, 'password' => bcrypt($request->password)]);
if(Auth::attempt($credentials)){
$user = Auth::guard('api')->user();
$data['id'] = $user->id;
$data['name'] = $user->name;
$data['phone'] = $user->phone;
$data['token'] = $user->createToken('API')->accessToken;
return response()->json([
'success'=> true,
'data'=> $data
]);
}
return response()->json([
'success'=> false,
'data'=> $response
]);
}
and this is my routes:
Route::post('register', 'Api\AuthController#register');
Route::middleware('auth:api')->get('/user', function (Request $request) {
return response()->json($request->user());
});
I want to display the user information in postman, and this is the request header to the url: http://127.0.0.1:8004/api/user:
Accept:application/json
Authorization:Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJhdWQiOiIxIiwianRpIjoiOThjYjM0YjkzOWJhMzczMDEwMGI0NmEyNTBhOGEzYTc5MTAyMjI1M2E2OTM0OGY0NGU1YWU4Njg3MzZkYmVlZjNlNzI1MDNiZTRhMjE5NGUiLCJpYXQiOjE1ODQ1NDczMDcsIm5iZiI6MTU4NDU0NzMwNywiZXhwIjoxNjE2MDgzMzA3LCJzdWIiOiI1NyIsInNjb3BlcyI6W119.GcqelFT2d3kKi8fR2vNbgMB1Fe_sQjrd2Mb3cRQLbS20IR_445bcTbcl17yKJrldboFktobeSIHx1GQENIzQbO0RStysmisiKuLk8eoXUvNVJq3t1bpZrjPBiNEGDRPqezq5VEsGhotVgbKRLK1gbVHwvE7mtSuGQTp9nIf6PEsmiJLsGmUJ0GdCmWXXLvJ0dBac1DZ_KauppDs_Lymx9SEXgzTDW60rpYrwHNbbaLfa6wdW3M5tUZM3vMRcKhCgYitvK_DfttKHcWqvEX8_lZT0h5GcQSsori_K8Lj_ynKfjrTfbodUKzT4kDZ8z-RnE4-SgG75LWDeqcpDRhuDmiL0KTIzwtrNFtU0NEo-v0t6dTkAuJCl1ZnTT72sLZoI6rsTPHtNKIDxwN9VrXiTU5pxGEc6ju5e30NQnkjBRjMRsVIcCHR-WohObuWkZOGRq-RP5on3oiLe2VGk0PENXXziMX3D5urpLWK3WR-ZY0Bz3fKitgE8TFaT1cOMSyK6d3zskUEdMjDyLCxbS7vKhmNuAy2moOj7f7DI9yr8XNeyF00WJKw0WJi76XX_Y06O-VtNhqzgeEyu6QM6qRivpBBcj-WkdbSTmveNZlSqAesLm6WD8qWKc9FR-S_41fCc2qLEY_VOotSA8tOYASVKpdsvj2liTbbMH9905HQJe-o
Content-Type:application/json
but the result is always:
{
"message": "Unauthenticated."
}
How could I display user information? thanks in advance
Change
Auth::attempt($credentials)
to
Auth::guard('api')->attempt($credentials)

Resources