How to refresh csrf token on each request without session expire issue in Laravel 5.4 - laravel

I want to refresh the CSRF token on each post request in Laravel 5.4
Added code from below SO link, still not helping
How to generate new CSRF Token for each user request in Laravel?
protected function addCookieToResponse($request, $response)
{
$response = next($request); // process petition
$request->session()->regenerateToken(); // regenerate token
return $response; // send response
}

Try this instead
protected function addCookieToResponse($request, $response)
{
session()->regenerateToken();
return parent::addCookieToResponse($request, $response);
}
Although this is not advised as it will break usuability, csrf_token is outputted before the new token is refreshed causing mismatch exception, would only work if you're extracting the token from the cookie with Javascript and not using the blade #csrf directive or csrf_token() helper function

Related

Route type delete does not work in Laravel

I have following route and works
Route::post("delete-role", [RoleApiController::class, "Remove"]);
I tested it through postman like this
http://localhost/delete-role?api_token=hcvhjbhjb12khjbjhc876
Now, if I change above route and convert to type delete..
Route::delete("delete-role/{role_id}", [RoleApiController::class, "Remove"]);
it does not work. I get below error. It seems to be the reason that the api_token is missing.
I get same error when trying to update route like below
Route::delete("delete-role/{role_id}/{api_token}", [RoleApiController::class, "Remove"]);
You have to set header of your request as:
"Accept": "application/json"
in postman.
If you don't set the required header for api, Laravel Passport can't understand request as an API client and so it will redirect to a /login page for the web.
Or you can set a middleware to check it in code:
public function handle($request, Closure $next)
{
if(!in_array($request->headers->get('accept'), ['application/json', 'Application/Json']))
return response()->json(['message' => 'Unauthenticated.'], 401);
return $next($request);
}
You have an incomplete details. but I see few issues here.
You seem to be using web routes for your API requests which is a bad set-up
You do not have a route with login name.
based on the error you posted, your request seems to successfully destroyed the token and logged you out, then called the middleware App\Http\Middleware\Authenticate which supposed to redirect your request to login route which does not exist and the reason you are getting that error.
You can see from that Authenticate middleware it will supposed to redirect you to login route for unauthenticated request. thats why you need to use the api routes so you can handle the response manually
class Authenticate extends Middleware
{
/**
* Get the path the user should be redirected to when they are not authenticated.
*
* #param \Illuminate\Http\Request $request
* #return string|null
*/
protected function redirectTo($request)
{
if (! $request->expectsJson()) {
return route('login');
}
}
}
Also, I'm not so sure about this, but the reason you are not getting the same issue with your POST request is probably because your POST request does not call the Authenticate middleware or whatever in your routes file or class function that calls the authenticate middleware.
But again, just use api routes if you don't want un-authenticated request to automatically redirect your request to login routes which does not exist in your application
The problem is that he doesn't define route ('login'),
add in Exceptions/Handler.php
$this->renderable(function (AuthenticationException $e, $request) {
if ($request->is('api/*')) {
return response()->json(['meassge' => 'Unauthenticated']);
}
});
Then you should use Passport Or Sanctum for auth with Api,
Continue from here https://laravel.com/docs/9.x/passport
Probably, this thread could help you. Route [login] not defined
(OR)
You need to setup auth scaffolding to get login route defined.
Important: your project will be overridden if you setup auth scaffold.
So, I would only recommend doing this if it is a new project or a testing app.
See this for detail doc but install Laravel Breeze would be suffice.
It Appears you have called route('login') without having defined it in your routes, Please remove route('login') from your code or define it in your routes. eg::
Route::get('login', [YourController::class, 'methodName'])->name('login');

Laravel passport change header authentication

I am using Laravel passport and it requires to send in every request the header Authentication to be sent.
Is it possible to change the name of the header to X-Access-Token?
I saw passport uses the package
League\OAuth2\Server\AuthorizationValidators;
method:
/**
* {#inheritdoc}
*/
public function validateAuthorization(ServerRequestInterface $request)
{
dd($request);
if ($request->hasHeader('authorization') === false) {
throw OAuthServerException::accessDenied('Missing "Authorization" header');
}
$header = $request->getHeader('authorization');
$jwt = trim(preg_replace('/^(?:\s+)?Bearer\s/', '', $header[0]));
I tried to change here but seems the validation of the headers happen before this method.
There are many fundamental pieces of code that rely on the existence of the authorization header.
You could roll your own if you felt so inclined.
Note also that authorization is a web standard request header. X-Access-Token is a response header pattern.
*Edit**
Given our conversation below, you can use Middleware and Middleware priority to dictate which runs first, observe requests that have an X-Access-Token and use addHeader to convert the value of that header to authorization:
php artisan make:middleware AuthorizationToolMiddleware
Then in the handle function:
public function handle($request, Closure $next)
{
$request->headers->set('Authorization', $request->headers->get('X-Access-Token'));
return $next($request);
}
This middleware should execute before other middleware in order to ensure the headers are set by the time that passport handles the request.
For Laravel 5.8 you'd have to force your custom middleware to always be on top of the call chain
So in your app\kernel.php add this -
protected $middlewarePriority = [
\App\Http\Middleware\AuthorizationToolMiddleware::class,
];

Laravel 5.3 API route not saving session between requests

I am trying to build a static HTML viewer through Laravel's 5.3 API routing logic and JWT. The files are all stored on S3 and need to be protected so I thought the best way to do this was to make a kind of proxy that all the files pass through. That way I can check the token of the user from the API request and load the files accordingly.
The first file loads fine.
http://example.com/api/proxy/file.html?token={token}
The issue arises when the HTML file tries to load files from itself. It works when I strip out the authentication functions so I know it's not an issue with getting the files. It's because the token is not appended to future requests. It sends this instead without the token.
http://example.com/api/proxy/some_image.png
I attempted to add the following code to my token checker logic.
public function __construct(JWTAuth $jwtAuth)
{
$this->middleware(function ($request, $next) use ($jwtAuth) {
if (!$jwtAuth->getToken()) {
if (!Auth::user()) {
return response()->error('The token could not be parsed from the request', 400);
} else {
$this->authUser = Auth::user();
}
} else {
$this->authUser = $jwtAuth->parseToken()->authenticate();
Auth::setUser($this->authUser);
}
return $next($request);
});
}
But for some reason this does not work. When the first .html loads up with the token it tries to authenticate the user using Laravel's Auth middleware but Auth::user() returns null on the image request.

Using laravel socialite and jwt-auth without session

Short version: What would be the appropriate way to send the JWT generated from Facebook login (laravel/socialite) to the angularjs front end without using session.
Long Version
I am making an app that has angularjs front end and laravel 5.2 backend. I am using tymondesigns/jwt-auth for authentication instead of session.
I am also using laravel/socialite for social Facebook authentication. For that I am using the stateless feature of socialite so that I don't need session in any ways.
The basic authentication works perfectly. But, when I try to use Facebook login, I follow these steps
User clicks on a button on the angular side that redirects to the provider login page of the back end.
public function redirectToProvider() {
return Socialite::with('facebook')->stateless()->redirect();
}
2. User gives his login information. After logging in he is redirected to my handlecallback function.
try {
$provider = Socialite::with('facebook');
if ($request->has('code')) {
$user = $provider->stateless()->user();
}
} catch (Exception $e) {
return redirect('auth/facebook');
}
return $this->findOrCreateUser($user);
Next I use the findorcreate function to determine whether the user exists or not. If not than I just create a new user and create JWT from that.
$user = User::where('social_id', '=', $facebookUser->id)->first();
if (is_object($user)) {
$token = JWTAuth::fromUser($user);
return redirect()->to('http://localhost:9000/#/profile?' . 'token=' . $token);#angular
} else {
$result = array();
$result['name'] = $facebookUser->user['first_name']
$result['email'] = $facebookUser->user['email'];
$result['social_id'] = $facebookUser->id;
$result['avatar'] = $facebookUser->avatar;
$result['gender'] = $facebookUser->user['gender'];
$result['status'] = 'active';
$result['login_type'] = 'facebook';
$result['user_type'] = 'free_user';
try {
$user = User::create($result);
} catch (Exception $e) {
return response()->json(['error' => 'User already exists.'], HttpResponse::HTTP_CONFLICT);
}
$token = JWTAuth::fromUser($user);
return redirect()->to('http://localhost:9000/#/profile?' . 'token=' . $token);#angular
}
My problem is, in the last block of code I am having to send the jwt to my frontend via url. Which isn't secure at all. What would be the right way to send the generated JWT to the frontend without using session. Thank you
The official documentation of Laravel Socialite says:
Stateless Authentication
The stateless method may be used to disable session state verification. This is useful when adding social authentication to an API:
return Socialite::driver('google')->stateless()->user();
Then, you can authenticate using the jwt-auth method:
JWTAuth::fromUser($user)
If you're using $http on the Angular side, try returning the token as a JSON response from Laravel:
return response()->json(compact('token'));
Then store the token in localStorage or sessionStorage or what have you.
If you're generating your Angular page from within Laravel (i.e. not using Laravel as an API, but showing your Angular page from /public/index.php, for instance) you could load the view with the token in the data for the view.
As long as you're using HTTPS either of these two scenarios are better than passing the token in the redirect URL.
You can store token and use client side redirect without storing to browser history to redirect user to profile page without token in URL:
document.location.replace({profile-url})

Laravel 5 POST data to DB

i want to insert data to db using POST request
table food_directory
id (auto incremenat)
name
fructose
polylos
fructan
public function postDirec()
{
if (\Request::ajax()) {
$FodMaps = \Request::get('name');
\DB::table('food_directory')->insert([
'food_directory' => $FodMaps,
]);
}
}
Route
Route::post('postDirec', 'FodMapController#postDirec');
this will return Tokenmismatch issue.. please advice
You need to add the CSRF-token in your form, by adding this line somewhere between your form's opening and closing tag:
{!! csrf_field() !!}
Goto App\Http\Kernel.php
And comment out this line
\App\Http\Middleware\VerifyCsrfToken::class,
It should be Line 20 in that file if you haven't made any other changes.
if you want to disable csrf protection on certain routes you can to this approach.
in the app/Http/Middlewares/VerifyCsrfToken.php modify handle method to
//disable CSRF check on following routes
$skip = [
'/your-uri/you-want-to-disable-protection-for',
route('or_some_route')
];
foreach ($skip as $route) {
if ($request->is($route)) {
return $this->addCookieToResponse($request, $next($request));
}
}
return parent::handle($request, $next);
Put uri you want to disable into the skip array. It will then call the parent's class addCookieToResponse method that will set CSRF token to the cookie and request would be treated as protected.

Resources