![](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh2X0-8e6QY-BWgP4eKJLgP9cjBvexQqp4XjawtK-75KLj7Cpg102YssAZrd6uEBZrK9c-38eC3H6b6u0ToO4p38eI5DfcgrfW25irXBQic5h8kHA9pbH8ReER01qulirxpEgzlKKBTONSS/s1600/Screen+Shot+2018-04-28+at+6.04.25+PM.png)
Authenticating a page or a service is done by adding the passport-jwt middleware to a route. Line 15 and line 22.
![](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiqokf2D2hps5nCzGuFJiH0vc3jrUFwSFulHqzR0l94nEnwxV9-GlbtsF53u_vtTR3O1zv3GHZlsOoxmocdvE64C_ElO8XfhFKNgqS-yMEv1Oo6ApQtU0kRg8uHpljmQgcZs4yShC3nQLVs/s1600/Screen+Shot+2018-04-28+at+6.07.06+PM.png)
Extraction of JWT from the cookie is done by creating a custom extractor for passport-jwt. Line 66 and 73
![](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjyPRFduMVp13rGNz5P3iV7uwDfe8WlGJgBELwZsFF0HF7gnjnHC00n5sCN3A5PzkC9ZPrJHci8uqpigYfIWC9TuFudjUZfYy77GlKoVELKrqTgi663wgYsen2Lzb-tIQu0rKc4ji-xl7Ht/s1600/Screen+Shot+2018-04-28+at+6.12.14+PM.png)
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