Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Some routes need protection, some routes are ok for public access, but still need UserID #197

Open
apprithm opened this issue Jun 29, 2018 · 3 comments

Comments

@apprithm
Copy link

apprithm commented Jun 29, 2018

Hi all,

I have the following scenarios:

  1. route /profile need require user have the token. If there is no token return 401
  2. route /feed allow public access, but if user sends token in the header, it will return additional information(specific to this user) in the response.

Will the following code give me the expected result without side effects? Is this a good practice ? Or, should I add each case to specific route in the routes file ?

var unProtected = [
    /feed
]
app.use(expressJwt({secret: config.secret}).unless({path: unProtected}))
app.use(expressJwt({secret: config.secret,credentialsRequired:false}))

So far, I tested the code with those 2 routes, it's working well.
But I have many more routes and I haven't tested 1 by 1 yet.

@johnfrades
Copy link

following. also need this kind of thing

@crinitic
Copy link

crinitic commented Sep 10, 2018

@johnfrades
Copy link

johnfrades commented Sep 10, 2018

I've solved it by creating this middleware

const looselyAuthenticatedMiddleware = (req): boolean => {
    const token = req.headers.authorization;
    if (token) {
        JWT.verify(token, config.secret, function(err, decode) {
            return true
        })
    } else {
        return true;
    }
}

const looseAuthenticatedRoute = jwt({ secret: config.secret }).unless({custom: looselyAuthenticatedMiddleware});

Just pass "looseAuthenticatedRoute" middleware on the route that you want to be open for 2 use cases:

  1. Still be able to access the route even if theres no token
  2. If theres token, there will be a value inside the "req.user"

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

No branches or pull requests

3 participants