Comments (4)
Can you show minimal code which reproduces the problem. If you call a protected route without token a 401
should be returned.
<?php
require __DIR__ . "/vendor/autoload.php";
$app = new Slim\App([
"settings" => [
"determineRouteBeforeAppMiddleware" => true,
"displayErrorDetails" => true
]
]);
$app->add(new \Slim\Middleware\JwtAuthentication([
"secret" => "supersecretkeyyoushouldnotcommittogithub"
]));
$app->get("/", function($request, $response, $arguments) {
print_r($response);
});
$app->run();
$ curl --include http://localhost:8081
HTTP/1.1 401 Unauthorized
Host: localhost:8081
Connection: close
X-Powered-By: PHP/7.0.12
Content-Type: text/html; charset=UTF-8
Content-Length: 0
from slim-jwt-auth.
Of course, when setting up a middleware for a route group with only the option of secret and trying to make a request, it returns me a white page with only the 401 statude being inside the if in the invoke method it passes a message to the error method. I suggest implementing an else in the error method, when a function is not informed in the option configuration error, the same fill with the message the response passed as parameter.
<?php
$app->group('/user', function () use ($app){
$app->get('', '\App\User\Controller\UserController');
})->add(new Slim\Middleware\JwtAuthentication([
"secret" => getenv('JWT_SECRET'),
]));
$ curl --include http://localhost/user
HTTP/1.1 401 Unauthorized
Host: localhost
Connection: close
X-Powered-By: PHP/7.0.12
Content-Type: text/html; charset=UTF-8
Content-Length: 0
/**
* Call the middleware
*
* @param \Psr\Http\Message\RequestInterface $request
* @param \Psr\Http\Message\ResponseInterface $response
* @param callable $next
* @return \Psr\Http\Message\ResponseInterface
*/
public function __invoke(RequestInterface $request, ResponseInterface $response, callable $next)
{
$scheme = $request->getUri()->getScheme();
$host = $request->getUri()->getHost();
/* If rules say we should not authenticate call next and return. */
if (false === $this->shouldAuthenticate($request)) {
return $next($request, $response);
}
/* HTTP allowed only if secure is false or server is in relaxed array. */
if ("https" !== $scheme && true === $this->options["secure"]) {
if (!in_array($host, $this->options["relaxed"])) {
$message = sprintf(
"Insecure use of middleware over %s denied by configuration.",
strtoupper($scheme)
);
throw new \RuntimeException($message);
}
}
**/* If token cannot be found return with 401 Unauthorized. */
if (false === $token = $this->fetchToken($request)) {
return $this->error($request, $response, [
"message" => $this->message
])->withStatus(401);
}**
/* If token cannot be decoded return with 401 Unauthorized. */
if (false === $decoded = $this->decodeToken($token)) {
return $this->error($request, $response, [
"message" => $this->message,
"token" => $token
])->withStatus(401);
}
/* If callback returns false return with 401 Unauthorized. */
if (is_callable($this->options["callback"])) {
$params = ["decoded" => $decoded];
if (false === $this->options["callback"]($request, $response, $params)) {
return $this->error($request, $response, [
"message" => $this->message ? $this->message : "Callback returned false"
])->withStatus(401);
}
}
/* Add decoded token to request as attribute when requested. */
if ($this->options["attribute"]) {
$request = $request->withAttribute($this->options["attribute"], $decoded);
}
/* Everything ok, call next middleware and return. */
return $next($request, $response);
}
public function error(RequestInterface $request, ResponseInterface $response, $arguments)
{
if (is_callable($this->options["error"])) {
$handler_response = $this->options["error"]($request, $response, $arguments);
if (is_a($handler_response, "\Psr\Http\Message\ResponseInterface")) {
return $handler_response;
}
}
return $response;
}
Sugestion
public function error(RequestInterface $request, ResponseInterface $response, $arguments)
{
if (is_callable($this->options["error"])) {
$handler_response = $this->options["error"]($request, $response, $arguments);
if (is_a($handler_response, "\Psr\Http\Message\ResponseInterface")) {
return $handler_response;
}
} else {
return $response->withJson($arguments);
}
}
I implemented a class with static method and passed in the configuration of error of the middleware, following example:
<?php
namespace Base\Jwt;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;
class Error
{
static function withJson(Request $request, Response $response, $arguments) : Response
{
return $response->withJson($arguments);
}
}
<?php
$app->group('/user', function () use ($app){
$app->get('', '\App\User\Controller\UserController');
})->add(new Slim\Middleware\JwtAuthentication([
"secret" => getenv('JWT_SECRET'),
"error" => '\Base\Jwt\Error::withJson'
]));
from slim-jwt-auth.
Looking at the example Curl request you provided the middleware is working as expected. It returns a 401
response without a body because authentication fails.
If you need to set a body when authentication fails do it in using the error
function. Example taken from the README.
$app->add(new \Slim\Middleware\JwtAuthentication([
"secret" => "supersecretkeyyoushouldnotcommittogithub",
"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));
}
]));
from slim-jwt-auth.
Ok, thanks!
from slim-jwt-auth.
Related Issues (20)
- Question: Prevent a token generated on System A to be used on System B HOT 1
- $request->getAttribute("token"); - not works in my handler HOT 10
- Strange Behaviour HOT 1
- chore: support firebase/php-jwt v6 HOT 16
- setting header on error response does not work HOT 1
- This works with public keys? HOT 2
- Route in ignore if it has the authorization header is it decoded?
- Drop support for unsupported PHP versions
- How to tackle with 2 authorization cookies HOT 2
- How to add a leeway? HOT 2
- How do you allow only some get routes to have auth HOT 3
- Authentication middleware should NOT interfere with Authorization HOT 3
- Starting with `3.2.0` it is possible to pass in array of secret keys. HOT 4
- how to update dependencies? HOT 3
- Relaxed setting should also accept IP address HOT 4
- JWT suddently stopped working HOT 2
- Is Slim4 supported? HOT 3
- Is there a plan to support psr/http-message 2.0? HOT 1
- when authentication fails! HOT 1
- How does the before/after parameter work? HOT 1
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from slim-jwt-auth.