how to fix Cookies not setting in laravel 9? - laravel

I'm trying to set a httpOnly cookie for token but it's not saving cookie.
I'm trying to login users via OTP and when user entered correct OTP, I'll sign them in app and so far I've done it like below :
$user = User::where('mobile_number', $request->mobileNumber)->first();
if ($user) {
Auth::login($user);
$token = $user->createToken('authToken')->accessToken;
$cookie = cookie('token', $token, 60 * 24 * 24); // 24 day
return response([
'status' => 'success',
'message' => 'loggedIn',
'user' => auth()->user(),
])->withCookie($cookie);
}else{
return response()->json([
'status' => 'success',
'message' => 'notExist'
], 200);
}
User will successfully login and if I refresh the page I should login again, and when I check Application\Storage\Cookies in Firefox and Storage\Cookies in chrome there's no sign of returned cookie(even if I don't refresh the page cookies won't be saved at all).
I'm using Laravel Passport, and so far, i don't think there should be any problem related to VUE side, since cookies not even saving in browser.
I've also tried to add more cookies to just test if everything work, but same problem happened again and nothing saved in browser.
I've also tried other solutions in Stackoverflow but they didn't worked.
Edit 01 : Removed refresh page...
Edit 02 : Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse and Queue tested.

Well, i found it, looks like problem was from VUE side actually. app URL was 127.0.0.1 for default in env file, but in VUE it was calling API via Localhost, and it was working but cookie wasn't saving due to this conflict, and when i changed it to 127.0.0.1 as default baseURL in axios, it worked.

Add cookie name in $except.
/app/Http/Middleware/EncryptCookies.php

Use the Cookie Facade that Laravel provides:
use Illuminate\Support\Facades\Cookie;
Cookie::queue('token', $token, 60 * 24 * 24);
In your Kernel.php, search for AddQueuedCookiesToResponse and uncomment it if it's commented.

Related

When I click the email verification link sended by laravel to my gmail it redirects me to the page which says - 403 This action is unauthorized

In my laravel project, i created the authentication successfully. register, login, and logout works fine. i did made the email verification, it sends the verification email to the user successfully. but when i click the verification email sended to my gmail by laravel, it redirects me to a page which says: 403 This action is unauthorized.
I am using Laravel 7.
my routes in web.php file
Route::get('/', function () {
return redirect(app()->getLocale());
});
Route::get('email/verify', 'Auth\VerificationController#show')->name('verification.notice');
Route::get('email/verify/{id}', 'Auth\VerificationController#verify')->name('verification.verify');
Route::post('email/resend', 'Auth\VerificationController#resend')->name('verification.resend');
Route::group([
"prefix" => "{language}",
'where' => ['locale' => '[a-zA-Z]{2}'],
'middleware' => 'setlocale'
], function () {
Auth::routes();
Route::get('/home', 'HomeController#index')->name('home');
});
I set the email verification routes manually, because priviously when i set the
Auth::routes(['verify' => true]);
I got an error, so i set the email verification outside the route group manually to fix that error.
In verify.blade.php the resend verification email also works fine, it resends the verification email successfully.
I have solved the problem. the problem was that verification.verify route was wrong,
when you set the
Auth::routes(['verify' => true]);
the actual verification.verify route is like this
email/verify/{id}/{hash}
The verification.verify route calls verify method which is located in vendor\laravel\ui\auth-backend\VerifiesEmails.php In this method there are two if statements which throws AuthorizationException which causes 403 This action is unauthorized page. The first if checks the route user id with the current authenticated user id, and the second if checks the route hash with the current authenticated user hash.
And make soure to configure your trusted proxies correctly.
check in laravel documentation click here.
I hope this help you.
I my case I was clicking the wrong 'verify email url' Because my all verfication emails in google were accumulating under same 'Subject' so instead of clicking the last email, I was clicking the first email

Can't take Laravel cookie that's been set

I have a checkbox in my login form and if it is checked I want to save user's email and password in a cookie so then he'll be automatically logged in. This is the part of my code that checks if the checkbox is checked and sets the cookie.
if ($remember == 'on') {
$array = array(
"email" => $email,
"password" => $password
);
$time = time() + (10 * 365 * 24 * 60 * 60);
Cookie::queue('user', serialize($array), $time);
}
But when I try to get the cookie and print it out it prints "false".
$cookie = Cookie::get('user');
dd(unserialize($cookie));
How can I get the cookie? It shows the cookie that's been set in inspect.
What's the best way to check if the cookie is set so i'll redirect the user to profile view straight away? Do I have to write a middleware for it?
The problem is your dd function call.
Cookies will store in user's browser when he retrieve the response with your Cookies attached (set-cookie headers), and you can read them in the next request that he will send to you.
when you call dd, it breaks the response chain and removes the set-cookie headers.
just remove the dd and in another route write:
dd(unserialize(\Request::cookie('user')));

Acessing auth user attribute

I am in the guzzle controller making a request to an external api.
I wanna use an id from the user who is logged in.
I have been doing the request with a static id, but now i want it dynamically.
I tried like this:
$science = Auth::user()->science_id;
$client = new Client(['headers' => ['Accept' => 'application/json']]);
$request = $client->get(
'https://url_to_the_api/'.$science.'/degree',
[
'auth' => ['client', 'secret'],
]
);
$data = $request->getBody()->getContents();
return $data;
And i have the error
500(internal server error)
and this message:
"Trying to get property 'science_id' of non-object"
What am i missing?
Thanks for your time
If you are using it in web app then make sure you first check if user is already authenticated by using auth middleware or manually by using Auth::check() function.
Or
If you are trying to hit this by api that will not work here because session will not be maintained in that case. That's why JWT tokens were introduced to maintain the state of an application.
I've solved it like this:
$science = auth('api')->user()->science_id;
Thanks for the help!

Facebook losing logged in user with ajax

I am writing a Facebook app and have used the Facebook php SDK so it can be authorized server side. I can see this is working because after authorization when Facebook redirects back to my app, I have the following code in my index.php...
require_once 'facebook.php';
$facebook = new Facebook(array(
'appId' => '111111111111111',
'secret' => '11111111111111111111111111111111',
'cookie' => true
));
// Get User ID
$user = $facebook->getUser();
...and $user returns not null. So far, so good!
I have a link on my app that loads content via ajax when clicked. Here's the JS:
$.post('my_content.php', {
action: 'render'
}, function(res){
if (res.html.length) {
$('.content').html(res.html);
}
},'json');
The problem is, the my_content.php script seems to be losing the fact the user has logged in and authorized the app.
The code I run in the my_content.php script to check whether the user is logged in is the same as in index.php
require_once 'facebook.php';
$facebook = new Facebook(array(
'appId' => '111111111111111',
'secret' => '11111111111111111111111111111111',
'cookie' => true
));
// Get User ID
$user = $facebook->getUser();
This time though $user = $facebook->getUser() returns null.
Is there a way to check if the user is logged in and authorized when running a PHP script with an AJAX call?
Should I store something in a session variable in my index.php script?
EDIT
After even more reading, I'm wondering if I need to retrieve the access token using the JavaScript SDK and pass it to my_content.php. Does anyone know if that's the correct way to do it?
EDIT 2
Turns out the line giving me the problem isn't $user = $facebook->getUser():
It is this one
$user_profile = $facebook->api('/me');
This line fails with the error 'OAuthException: An active access token must be used to query information about the current user.'
Strangely though, if I do this
$access_token = $facebook->getAccessToken();
$user = $facebook->getUser();
echo $access_token;
echo $user;
I do indeed have an access token and a user ID, so it looks like it may well be the bug reported by CBroe - check comments below.

remember me functionality in codeigniter

I have implemented remember me functionality as this question
How to create "remember me checkbox" using Codeigniter session library?
first answer.
I created a cookie with a random number code as value and it stored in db(user table). On login, db code checks with cookie value.It works fine on my localhost server. But in live server which has a subdomain url has problem.Also I tested it with another server with ip address as url. There also it is not working. In both cases cookie created but cant read the cookie. Please help me.
cookie set by
$auto_login_hash_code = uniqid();
$domain = $_SERVER['SERVER_NAME'];
$cookie = array(
'name' => 'rememberMe',
'value' => $auto_login_hash_code,
'expire' => 31536000,
'domain' => $domain,
'path' => '/'
);
$this->input->set_cookie($cookie);
and reading cookie by
if (get_cookie('rememberMe')) {
$hashcode = $this->CI->input->cookie('rememberMe');
$this->CI->load->model('loginmodel', '', true);
$username = $this->CI->loginmodel->get_username_by_hashcode($hashcode);//in this function setting session variables
}
Thanks in advance
iijb
you are getting library for that on github.
search remember me on github, load it and just follow below steps.
Verify cookie if token is present in database go to home page
$this->load->library('rememberme');
$cookie_user = $this->rememberme->verifyCookie();
if ($cookie_user)
{
$this->load->view('search_view');
}
else
{
// If checkbox is checked it return true either false
$checked = (isset($_POST['Checkbox1']))?true:false;
if($checked== true)
{
//$this->load->view('tested');
$this->load->library('rememberme');
$this->rememberme->setCookie($this->input->post('loginemil'));
//$this->rememberme->setCookie('set cookie here');
}
else{
dont set anything
}
}
Also this can be done by editing/extending system Session library.
First: In user login function add remember me check-
if($remember)
{
$data['new_expiration'] = 60*60*24*30;//30 days
$this->session->sess_expiration = $data['new_expiration'];
}
$this->session->set_userdata($data);
Second: Edit system Session library [I am not sure whether extending Session will work or not]
Go to this line in sess_read() method
if (($session['last_activity'] + $this->sess_expiration) < $this->now)
Before that line add following code
if(isset($session['new_expiration'])){
$this->sess_expiration = $session['new_expiration'];
}
This works fine for me.

Resources