Saturday, April 28, 2018

Session-less Facebook and Google Login with Passport using Cookie + JWT

The id and display name returned to app after logging to Facebook or Google, is encrypted with JWT and then stored to cookie. Line 74 and 77





Authenticating a page or a service is done by adding the passport-jwt middleware to a route. Line 15 and line 22.





Extraction of JWT from the cookie is done by creating a custom extractor for passport-jwt. Line 66 and 73




Full code can be downloaded from https://github.com/MichaelBuen/test-code-auth


Here's the structure of ILoggedUserJwtPayload:

import { ILoggedUser } from './ILoggedUser';

export interface ILoggedUserJwtPayload
{
    // subject
    sub: ILoggedUser;

    // expires
    exp: number;
}

This is the ILoggedUserJwtPayload sub property's structure:

export interface ILoggedUser
{
    source: string | undefined; // provider, e.g., facebook, google
    id: string | undefined; // id
    shownName: string | undefined; // displayName
}


Here's another route authenticated by passport-jwt middleware:

app.get('/api/v1/me',
    passport.authenticate('jwt', {session: false}),
    (req, res) =>
    {
        const user = req.user as ILoggedUser;

        res.json(user);
    }
);



Happy coding!

No comments:

Post a Comment