0

I am building an app that uses an express backend that will power a next.js and react native front end.

For the web app I would like to use express-session and mysql-express-session, but obviously this won't work for the native app. So what I would like to do is protect the api routes using JWT.

I am abit confused on how to achieve the above. My thoughts are, I would create seperate routes for the react native app, for example I prefix them with /rn, I could then use JWT for these routes and sessions for the web app routes.

Would that be an optimal solution?

adherb
  • 304
  • 3
  • 12
  • I'm not sure I understand the question. It sounds like you want advice on creating an Identity Provider - AWS Cognito and AWS Amplify would certainly solve this. Otherwise you'll need to create your own Identity Provider in which case I'd suggest taking a look at this: https://www.oauth.com/playground/. – Ash Dec 26 '21 at 22:29
  • Does this answer your question? [Invalidating JSON Web Tokens](https://stackoverflow.com/questions/21978658/invalidating-json-web-tokens) – Heartbit Dec 26 '21 at 22:30
  • Not really, I understand JWT and sessions. I think you wanting to support both is overcomplicating things and essentially duplicating your implementation. It sounds like you want Authorization Code grant and PCKE grant, which will handle both apps. The link i added above will simulate the process and explain things to you. – Ash Dec 26 '21 at 22:39
  • @Heartbit unfortunately not, I have edited the question to give more clarity. – adherb Dec 26 '21 at 23:04
  • @Ash I have edited the question, I want to use them in the same express backend but for seperate uses, JWT for React Native, sessions for the Next.js web app. – adherb Dec 26 '21 at 23:05

1 Answers1

1

For the react-native app you can set a header like APP-AUTH-STRATEGY = 1. So before any JWT token validation, you should check that the request comes from the app then you can validate the token of Authorization header.

Another solution would be using the req.hostname if you get all requests of your app from another subdomain like app.yourdomain.com. more about the hostname in express

Heartbit
  • 1,698
  • 2
  • 14
  • 26
  • So for examples, I could create seperate login and signup routes for the apps, one would create a session, then the other would create a JWT. Then could I build a middle wear that uses req.hostname to check where the request has come from, for example webapp.com, then it would either validate the JWT or session depending where the route has come from? – adherb Dec 27 '21 at 01:55
  • 2
    @adherb You don't need separate routes. just use the conditions – Heartbit Dec 27 '21 at 09:49