Difference between using Laravel Cookie and plain php $_COOKIE? - php

I set a cookie with javascript and I'm trying to read on the backend with laravel PHP.. When I try running either of these, I get null:
Cookie::get('locale');
$locale = $request->cookie('locale');
Now when I run the plain old php version, I get the cookie normally.
$_COOKIE['locale'];
What's the difference? Why do I get null when using the laravel version?

Laravel cookies are encrypted, so unless you do something like
return response('Hello World')->cookie(
'locale', 'pt-BR'
);
You cant't read it using
Cookie::get('locale');

It's because of laravel cookie encrypting. You can just not include EncryptCookies middleware to avoid this problem. Remove \App\Http\Middleware\EncryptCookies::class from $middlewareGroups in app\Http\Kernel.php

Related

How to set a cookie on response in Laravel Lumen 8

I'm currently building a REST API with Laravel Lumen 8. I want to set a cookie if the user logged in successfully. I saw that in the Lumen 5.1 docs there was a section that showed how to send a cookie with the response (https://lumen.laravel.com/docs/5.1/responses#attaching-cookies-to-responses). But in the documentation for version 8 this section is missing. I also looked into the Laravel 8 docs (https://laravel.com/docs/8.x/responses#attaching-cookies-to-responses) and tried the following things in my routes/web.php file:
Attempt 1
$router->get('/test', function () {
return response('Hello World')->cookie(
'name', 'value', 60
);
});
But then I get the following error:
Argument 1 passed to
Symfony\Component\HttpFoundation\ResponseHeaderBag::setCookie() must
be an instance of Symfony\Component\HttpFoundation\Cookie, string
given
Attempt 2
use Illuminate\Support\Facades\Cookie;
$router->get('/test', function () {
Cookie::queue('name', 'value', 60);
return response('Hello World');
});
Error message: Target class [cookie] does not exist.
Attempt 3
$router->get('/test', function () {
$cookie = cookie('name', 'value', 60);
return response('Hello World')->cookie($cookie);
});
Error message: Call to undefined function cookie()
Attempt 4
use Symfony\Component\HttpFoundation\Cookie;
$router->get('/test', function () {
return response(null)->withCookie(new Cookie('name', 'value'));
});
This solution works, but if i set the third parameter like this new Cookie('name', 'value', 60), I don't get an error message but the cookie doesn't get set anymore.
And I'm also a bit sceptical because I never saw this in any official docs but only in this stack overflow question: Set cookie on response in lumen 5.6.
These weren't the only things I tried but nothing worked so far. Setting a cookie should be such an easy thing but I just can't achieve it. I'm pretty new to Laravel/Lumen, has it something to do with the new Version 8? Or what else am I doing wrong?
I've had the same issue, this is not pretty but it fixed it for me.
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpFoundation\Response;
...
$response = new Response();
$response->headers->setCookie(Cookie::create('foo', 'bar'));
$response->send(); // <- this guy
In case you are using the jwt-auth library by Sean Tymon for JSON Web Token Authentication, this Thread may help you: https://github.com/tymondesigns/jwt-auth/issues/1594#issuecomment-395575980
Cited from the thread:
The root of the culprit I guess is that Lumen by design no longer does
cookies which I find a bit of a flaw in the light of all the blogs and
OWASP suggestions of not storing a JWT in localstorage but rather in a
httponly cookie to prevent XSS and deal with CSRF accordingly. So, the
jwt-auth doesn't include the cookie parser with the
LumenServiceProvider which is what you register in app.php as a
service provider:
$app->register(Tymon\JWTAuth\Providers\LumenServiceProvider::class);
So when you add
use Tymon\JWTAuth\Http\Parser\Cookies;
to the top of jwt-auth\src\Providers\LumenServiceProvider.php
and add
new Cookies($this->config('decrypt_cookies'))
into the array at the very end of the file
$this->app['tymon.jwt.parser']->setChain([<br>
new AuthHeaders,
new QueryString,
new InputSource,
new LumenRouteParams,
new Cookies($this->config('decrypt_cookies')),
]);
then you should be able use the cookie authentication in Lumen as
well.

I'm transitioning my API from slim-3 to slim-4 and I'm struggling to figure out how to add JWT to the middleware

I'm using composer to install the slim-skeleton. Those built in routes work as expected. I understand how to add in my previous routes and database connections, but I've been struggling on how to add in any JWT library. I've searched and searched but I'm not finding much documentation for Slim-4 and what I've tried always seems to fail one way or another.
So for example I use composer to install tuupola/slim-jwt-auth and it says to add the following code:
$app = new Slim\App;
$app->add(new Tuupola\Middleware\JwtAuthentication([
"secret" => "supersecretkeyyoushouldnotcommittogithub"
]));
but where or how exactly do I add it to the middleware? Does it need to be added to app/middleware.php? All the documentation I read has a completely different file structure with other directories and whatnot. Once this is placed in the correct spot it looks like when a request is made without a token I should get a 401 Unauthorized response.
After that part is working I know I need to create a route to get my access token, but I'm not seeing anything about that in this library so I would assume I need another library to encode my token and return it from my request.
Once I actually get a token response and pass it in the headers for my actual request route I would assume I do something like the following
$app->get("/protected-route-name", function ($request, $response, $arguments) {
$token = $request->getAttribute("token");
// Not sure what to put next to verify the token and allow the response or display a error if there is no token or the token in invalid.
});
I'm open to firebase or any JWT library if someone has one they like and that works well, I just need some direction as I feel all the documentation is lacking.
use \Firebase\JWT\JWT;
get token
$headers = apache_request_headers();
if(isset($headers['Authorization'])){
$decoded = JWT::decode($headers['Authorization'], $publicKey, array("RS256"));
.... verify token.
}
$jwt = JWT::encode($payload, $privateKey, "RS256");
boom done.
you don't even really need to use middle ware to do this.
slim made itself way overly complex with that.
But the truth is between slim3 and slim 4, on a very basic setup, the only thing that has changed is the getBody() on the json writing.
honestly, not really sure how useful this is anymore to be honest. everything is cloudbased now. Only reason I found this is trying to figure out how to use Google Identity Platform with Slim.

Laravel cookie unexpected output i.e. encrypted result on service provider

I am developing a package where I am registering ServiceProvider and inside my class methods I am saving cookie data as this
Cookie::queue(Cookie::make('my_name', 'manash', 120));
and I am retrieving like this
Cookie::get('my_name')
but I am not getting the value as I have stored, instead it is outputting me this value
eyJpdiI6InlcL3VxNklrejlKemxLQ012T0pcL3U1QT09IiwidmFsdWUiOiJpbzRmajVEUU90YkhhdTdpeFNlcURBPT0iLCJtYWMiOiI1MTFiMTk5YjY3ZTczMzI2Nzc1MGI1Mzk3NmU1MjJhYjE3MWRhYWE2OGQ4NWE1Y2Y2NDgyZWQ1YmYxOGQ4OWU1In0=
I think it encrypted, but as per my knowledge it should be automatically decrypted when we use get method.
I am using laravel 5.3.28
What happens is that all cookies created by laravel are encrypted and signed with an authentication code.
Have you tried with the request?
Like this:
Illuminate\Http\Request
Request $request;
$request->cookie('my_name');
Check if your middleware is not triggering before Encrypt Cookie middleware
Try https://laravel.com/docs/master/encryption see if it works

PHP Gettext not showing correct language in Laravel

When I change language the first time it works perfectly. However, when I refresh the page the translation is back to english again, even though the language selector still says "Danish" and getLang returns da_DK.... Then when I run php artisan cache:clear it works the first time I refresh, but second time it is back to english again.
Any ideas what could be wrong here?
I am using the package https://github.com/xinax/laravel-gettext to translate. Laravel 5.2.
It is because laravel has it own 'locale' and 'fallback_locale' inthe config file. If you match the language you want, you should be fine.
Ps: I recognize this is an old question, but I was helping just in case...
If you are using Laravel 5.2 and Xinax/LaravelGetText:
Go to SessionHandler.php and change the function to
public function get($default)
{
$locale = $default;
if (!Session::has($this->sessionIdentifier)) {
$locale = Session::get($this->sessionIdentifier);
}
return $locale;
}
For more information you can check http://www.yellowpagesphpscript.com or
http://www.scriptbazar.com

Redirect::away(...) equivalent for Lumen?

I'm attempting to port a portion of a Laravel 4 app to Lumen, but I'm unable to figure out the equivalent of Laravel 4's Redirect::away(...); function for Lumen.
I've tried keeping it the same which doesn't work. I've also tried return redirect()->away($location); as suggested in a similar question I found, but that also fails with the error Call to undefined method Laravel\Lumen\Http\Redirector::away().
I feel like the answer to this is really simple, but unfortunately it's not documented anywhere and I can't figure out the right combination of things to get it to work.
My fallback is to use header('Location : '.$location); but would prefer to avoid it if there's a built in way to do it.
You should be fine to do return redirect($location) in most cases.
See https://medium.com/#zwacky/laravel-redirect-to-vs-redirect-away-dd875579951f for the minor differences (it'll trim() your URL and check that it's valid).

Categories