Req.user undefined when calling backend api with passport-twitter auth

Req.user undefined when calling backend api with passport-twitter auth
0

#1

I have an app (repo here) with a backend server api and client bootstrapped with create-react-app.
I am using react-router-dom.BrowserRouter for the client routing and passport-twitter for auth through the backend.

The auth part is working, I go to twitter auth page and return to app ok.
Passport deserializeUser is called and req.user is defined during auth process.

From what I have read and inspecting my db, express-session is creating a new
session for each request. deserializeUser is not called and req.user is not
present when I try to access it in backend calls e.g. /auth/user (checking user auth status).
I have read in github issues that this is because I need to be consistent with
my links to the backend.

So, the nub of the issue is my call(s) to twitter auth, I start it off with an a href link:

<a rel="external" href="http://localhost:5000/auth/login/twitter" >Login</a>

I think the rel=“external” maybe a red herring - found it in a thread somewhere
but not sure it does anything.

If I try just:

<a rel="external" href="/auth/login/twitter" >Login</a>

I am redirected back to “/” without hitting the backend router.
The folks at react training say the router does not intercept <a href> links and whilst it doesn’t seem that way, I don’t feel I can argue with them.

So I’m a bit lost now. It seems I have to use http://localhost:5000/... to redirect to
twitter auth but then auth is not setup for /some/route type routes to talk to
backend.
This thread suggests using passport-authenticate on every route I want authed,
which I tried but it didn’t seem to help and I’m well out of my depth by this point.

Does anyone have any suggestions for a way forward?

I read a SO thread about the service worker cache being part of the problem, so that is commented out currently.

I read a thread suggesting use cookie-session instead of express-session but this gave me:

Error: OAuth authentication requires session support

thanx for your time,
nik.


React with backend passport-twitter CORS issue
#2

It wasn’t a cors issue. Browser fetch wasn’t sending cookie to server, found answer here:

fetch( "/auth/user",{
  method: "GET",
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
    'Cache': 'no-cache'
  },
  credentials: 'same-origin'
})

React with backend passport-twitter CORS issue