Skip to content
This repository has been archived by the owner on Sep 11, 2024. It is now read-only.

Help with integration with Firebase token #184

Open
leossmith opened this issue Mar 23, 2020 · 9 comments
Open

Help with integration with Firebase token #184

leossmith opened this issue Mar 23, 2020 · 9 comments

Comments

@leossmith
Copy link

leossmith commented Mar 23, 2020

I have used this in the past to authenticate using my own JWT, but now i want to use the Firebase token for users. I have tried multiple things, without any luck. This is my code:

$app->add(new Tuupola\Middleware\JwtAuthentication([
    "ignore" => ["/users/register","/users/activate","/users/login",
                 "/users/requestPasswordReset","/users/passwordReset",
                 "/admins/login"],
    "header" => 'X-Authorization',
    "secret" => $secrets,
    "algorithm" => ["RS256"]
]));

But it keeps going to 401 not authorized. Do you have an example using Firebase Auth for authentication?

Thank you.

Using Php Slim 4

@gregorispielmann
Copy link

Hello @leossmith did you make this work? I'm with the same difficulty to do this!

@leossmith
Copy link
Author

Yes I managed to make it work. It seems like the issue was the secrets I used. I was splitting the keys I got from google to arrays, but this is already done by JwtAuthentication. So the final working code is this:

return function (App $app) {
    $app->add(CorsMiddleware::class);

    $container = $app->getContainer();
    
    $rawPublicKeys = file_get_contents('https://www.googleapis.com/robot/v1/metadata/x509/[email protected]');
    $keys = json_decode($rawPublicKeys, true);

    $logger = new Logger("slim");
    $rotating = new RotatingFileHandler(__DIR__ . "/logs/slim.log", 0, Logger::DEBUG);
    $logger->pushHandler($rotating);

    $app->add(new Tuupola\Middleware\JwtAuthentication([
        "ignore" => ["/api/records/countries","/faqs"],
        "algorithm" => ["RS256"],
        "header" => "X-Authorization",
        "regexp" => "/Bearer\s+(.*)$/i",
        "logger" => $logger,
        "secret" => $keys,
        "secure" => false,
        "error" => function ($response, $arguments) {
            $data["status"] = "error";
            $data["message"] = $arguments["message"];
            return $response
                ->withHeader("Content-Type", "application/json")
                ->getBody()->write(json_encode($data, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT));
        }
    ]));
};

@gregorispielmann
Copy link

@leossmith thank you so much for this help! I will see if it works with me too! Thanks again!

@leossmith
Copy link
Author

@gregorispielmann no worries. If you have any issues it should probably be an issue with the CorsMiddleware, which has to be setted up properly for X-Authorization.

@gregorispielmann
Copy link

gregorispielmann commented Apr 13, 2020

@leossmith, I changed now with your comment. My Cors middleware is that now:

$app->add(new \Bairwell\MiddlewareCors([
    'origin'           => ['*'],
    'exposeHeaders'    => '',
    'maxAge'           => 120,
    'allowCredentials' => true,
    'allowMethods'     => ['GET', 'POST', 'OPTIONS'],
    'allowHeaders'     => ['Accept', 'Accept-Language', 'X-Authorization' ,'Authorization', 'Content-Type','DNT','Keep-Alive','User-Agent','X-Requested-With','If-Modified-Since','Cache-Control','Origin'],
]));

I'm forgetting something? Thanks again!!!

@leossmith
Copy link
Author

I am not sure if it the above works. This is what i use:

final class CorsMiddleware implements MiddlewareInterface
{
    /**
     * Invoke middleware.
     *
     * @param ServerRequestInterface $request The request
     * @param RequestHandlerInterface $handler The handler
     *
     * @return ResponseInterface The response
     */
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $routeContext = RouteContext::fromRequest($request);
        $routingResults = $routeContext->getRoutingResults();
        $methods = $routingResults->getAllowedMethods();
        $requestHeaders = $request->getHeaderLine('Access-Control-Request-Headers');

        $response = $handler->handle($request);

        $response = $response->withHeader('Access-Control-Allow-Origin', '*');
        $response = $response->withHeader('Access-Control-Allow-Methods', implode(', ', $methods));
        $response = $response->withHeader('Access-Control-Allow-Headers', $requestHeaders ?: 'X-Authorization');

        // Allow Ajax CORS requests with Authorization header
        $response = $response->withHeader('Access-Control-Allow-Credentials', 'true');

        return $response;
    }
}

@realrecordzLab
Copy link

I'm trying to use your solution to verify the idToken passed from the firebase auth in my chrome extension but without success. Do you used the return function() in the main index.php file of your slim app?

@leossmith
Copy link
Author

This is part of my midleware which is initiated in my index.php . I am using Slim 4.

@realrecordzLab
Copy link

I've figured out how to implement my own middleware after some tests and headache. The mai problem was to figure out what is the correct token to use as bearer. Firebase javascript sdk provides two different tokens. The first one is returned is the idToken and I obtained it after the success login using this code

const provider = new firebase.auth.GoogleAuthProvider();
provider.addScope("profile");
provider.addScope("email");
firebase.auth().signInWithPopup(provider).then( (result) => {
 console.log(result.credential.idToken);   
});

This token will be not valid if passed to the middleware. The correct way to get the working token is by calling the firebase.auth().onAuthStateChanged() method that will return an user object who implement this method user.getIdToken(). By calling it is possible to get a valid token to use in the X-Authorization header as a Bearer and that will be correctly validated using the Tuupola slim JWT library.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

4 participants