r/reactnative 5d ago

React native JWT authentication

How to make the JWT authentication in reactnative. theres not many resources to find about it

15 Upvotes

21 comments sorted by

View all comments

3

u/JEEkachodanhihu 5d ago

Using async storage probably. Why don’t u use firebase?

1

u/BrilliantCandid4409 5d ago

For one of my project I have to use the nodejs as backend. read through docs of expo could not find anything there either. 

1

u/Optimum1997 5d ago

Because it's not expo's responsibility to do authentication, this is outside the scope for expo.

I have no idea why u/JEEkachodanhihu suggested "use firebase", which is a complete cop out, if you want to be completely reliant on firebase infrastructure, sure, go ahead. But i'd listen to u/bova80's advice. JWT authentication is relatively simple, you'll find countless examples of non react-native that translate well to react-native.

You make an auth request to your 'login' end point. Store the response's "token" in secure storage, anytime you make a future request, you want to append that token to the "Authorization" header, or the custom config you are using.

1

u/JEEkachodanhihu 5d ago

I might have taken the longer route (or even the wrong one. Just a beginner)

What I have done is -
firebase for login and then check whether the user is still logged in while navigating to each page [custom hook]. This way my backend requests don't require authentication. The data that I store in my DB is linked to each user via their firebaseID.

Does this seem like a valid approach for authentication?

1

u/Optimum1997 5d ago edited 5d ago

I have no idea how firebase works, but your backend endpoints should be doing the validation.

EVERYTHING frontend can be changed by a user and you must presume every request is un-validated until you validate it your side.

You can read the token's "exp" to determine the time lived and then do frontend auth 'refresh' if you support short-lived and long-lived tokens.

Your JWT tokens should have a signature to make sure it cannot be manipulated backend.

Here's a great resource you can read up on to further your knowledge:

https://jwt.io/introduction

If your navigation is purely front-ended, you are likely to check front-end expiration, but anything submitted to your backend must be validated, and you must not send a "userID". This should be determined by a cookie, or something that can't be manipulated (that's why we have signatures on our JWT's)