Express protect only select endpoints

Hello, I want to protect only POST and DELETE endpoints on my api and leave the GET ones public. Is there a way to achieve this using the express-oauth2-jwt-bearer library?

Hey there @vdemcak welcome to the community!

You can absolutely achieve this with express-oauth2-jwt-bearer - You more or less just need to include checks on the access token for protected endpoints while omitting them for public endpoints. For example:

//Using claimIncludes to check if the permissions claim contains read:msg
app.get('/api/external', checkJwt, claimIncludes('permissions', 'read:msg'), (req, res) => {
  res.json({ message: `Hello ${req.auth.payload.sub} - Permissions: ${req.auth.payload.permissions}` });

//Public endpoint
app.get('/api/external/public', (req, res) => {
    res.json({ message: `Hello - This is a public endpoint, welcome!` });

//Protected, requires create:msg permission'/api/external/create', checkJwt, claimIncludes('permissions', 'create:msg'), (req, res) => {
  res.json({message: `Hello ${req.auth.payload.sub} - Successful POST` })

In this case, checkJWT is an instance of the auth middleware. You can choose to be more granular with claimIncludes, requiredScopes, etc. The API reference can be found here:

Hope this helps!

Thanks! Worked like a charm!

1 Like

Awesome! Thanks for confirming :rocket:

Quick question, how would I go on about checking if valid token was provided and it if has claims inside of a request? I would like to add entries to the response based on if a valid token has been provided and it has the required claims.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.