Giter VIP home page Giter VIP logo

Comments (4)

tuupola avatar tuupola commented on May 19, 2024

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.

jorgeluizjr avatar jorgeluizjr commented on May 19, 2024

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.

tuupola avatar tuupola commented on May 19, 2024

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.

jorgeluizjr avatar jorgeluizjr commented on May 19, 2024

Ok, thanks!

from slim-jwt-auth.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo 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.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.