tuupola / slim-jwt-auth

PSR-7 and PSR-15 JWT Authentication Middleware
https://appelsiini.net/projects/slim-jwt-auth
MIT License
821 stars 140 forks source link

How do you allow only some get routes to have auth #230

Open rodude123 opened 1 year ago

rodude123 commented 1 year ago

I'm making an API where some data is publicly available for my site and some need auth. I know I can add this,

$app->add(new Tuupola\Middleware\JwtAuthentication([
    "rules" => [
        new Tuupola\Middleware\JwtAuthentication\RequestPathRule([
            "path" => "/",
            "ignore" => []
        ]),
        new Tuupola\Middleware\JwtAuthentication\RequestMethodRule([
            "ignore" => ["OPTIONS", "GET"]
        ])
    ]
]));

This allows all GET methods to have no auth on them. so is there a way to specify /projectData as a GET route that has no auth but /projetData as a POST, PUT, PATCH, DELETE routes have auth on them

tuupola commented 1 year ago

Something like this should work.

$app->add(new Tuupola\Middleware\JwtAuthentication([
    "rules" => [
        new Tuupola\Middleware\JwtAuthentication\RequestPathRule([
            "path" => ["/projectData"],
            "ignore" => []
        ]),
        new Tuupola\Middleware\JwtAuthentication\RequestMethodRule([
            "ignore" => ["OPTIONS", "GET"]
        ])
    ]
]))
rodude123 commented 1 year ago

This worked perfectly! Although a quick follow-up question. How would I allow some GET routes to have auth on them? I tried to put the route in the path, like so:

$app->add(new Tuupola\Middleware\JwtAuthentication([
    "rules" => [
        new Tuupola\Middleware\JwtAuthentication\RequestPathRule([
            "path" => ["/projectData", "/user/getUserInfo"],
            "ignore" => []
        ]),
        new Tuupola\Middleware\JwtAuthentication\RequestMethodRule([
            "ignore" => ["OPTIONS", "GET"]
        ])
    ]
]))

This however didn't work and it didn't require auth for the get route of /user/getUserInfo when I want it to

tuupola commented 1 year ago

In your config you are ignoring all GET requests so GET /user/getUserInfo will not be authenticated. Easiest thing would be to organize your routes so that you do not need complicated rules. For example:

$app->add(new JwtAuthentication([
    "path" => ["/api", "/admin"]
]));

Now any path starting with /api/ and /admin/ will be authenticated while the rest will not. Alternatively some frameworks allow you to bind middlewares manually to your selected routes. With Slim this is something like:

/* Add to single route */
$app->get("/", function () { ... })->add(new JwtAuthentication());

/* Add to route group */
$app->group("/", function () { ... })->add(new JwtAuthentication());