Secured jwt method to be used?


#1

Hi All,
I am very new to slim. I need to implement jwt for both generating and authentication. I am stucked I saw this https://github.com/tuupola/slim-jwt-auth. I dont know how is this link to a particular router? How is that being set ?


#2

That package is middleware, so you would add the middleware to your application, to specific routes, or to route groups. See How do I add middleware? in the docs.


#3

Dear tflight,
Thank you let me explore further. Actually I want to implement jwt token authentication? Which is the correct method go about with this implementation ? I saw this sample is the most being reference ?


#4

I did it with tuupola jwt auth, here is my middleware.php

<?php
 // Application middleware

 // e.g: $app->add(new \Slim\Csrf\Guard);
   use Tuupola\Middleware\HttpBasicAuthentication;

   $container = $app->getContainer();
   $container['logger'] = function($c) {
   $logger = new \Monolog\Logger('my_logger');
   $file_handler = new \Monolog\Handler\StreamHandler("../logs/app.log");
   $logger->pushHandler($file_handler);
     return $logger;
};

$container["jwt"] = function ($container) {
 return new StdClass;
};

 $app->add(new \Slim\Middleware\JwtAuthentication([
 "path" => "/",
"logger" => $container['logger'],
"secret" => "123456789helo_secret",
 "rules" => [
    //Si se quiere agregar una ruta que no requiere del token
    //Se debe agregar a la siguiente lista
  new \Slim\Middleware\JwtAuthentication\RequestPathRule([
      "path" => "/",
      "passthrough" => ["/usuarios", "/login","/usuario","/informacion"]
  ]),
  new \Slim\Middleware\JwtAuthentication\RequestMethodRule([
       "passthrough" => ["OPTIONS"]
  ]),
  ],
   "callback" => function ($request, $response, $arguments) use ($container) {
  $container["jwt"] = $arguments["decoded"];
},
 "error" => function ($request, $response, $arguments) {
  $data["status"] = "error";
  $data["message"] = $arguments["message"];
  return $response
      ->withHeader("Content-Type", "application/json")
      ->write(json_encode($data, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT));
}
]));

$app->add(new \Slim\Middleware\HttpBasicAuthentication([
 "path" => "/api/token",
 "users" => [
  "user" => "password"
 ]
]));

Hope this helps you.


#5

Hi Jaimec,
So you dont implement the cors actually how does it help ? I dont this portion
$app->add(new \Slim\Middleware\HttpBasicAuthentication([
“path” => “/api/token”,
“users” => [
“user” => “password”
]
]));
How this works ?


#6

CORS its not implemented there, that code is only for JWT auth, And that portion you wrote thats for basic auth, you dont need a token if you implement basic auth, just username and password.


#7

Hi Jaimec,
Ok I will remove the basic auth cause I want to use just the JWT. Will cors help improve the security?