A.S. SAMARASINGHE
A.S. SAMARASINGHE

Reputation: 225

How to implement the best OAuth authentication?

I'm using zendesk OAuth for authorization. I'm using the MERN stack and the current implementation works like this,

  1. User clicks login and redirected to zendesk
  2. once the user signs I get redirected back to /callback path
  3. Where I sent another request to get an auth token
  4. After I get the token I redirect the user to frontend as ?token=XXXX attached to the URL

Is this the correct way? How should I proceed with the token should I keep it in session storage? It's not a good idea to expose the token?


export const authCallback = (req: Request, res: Response): void => {
  const body = {
    grant_type: 'authorization_code',
    code: req.query.code,
    client_id: process.env.ZENDESK_CLIENT_ID,
    client_secret: process.env.ZENDESK_SECRET,
  }

  axios
    .post(`https://${process.env.SUBDOMAIN}.zendesk.com/oauth/tokens`, body, {
      headers: {
        'Content-Type': 'application/json',
      }
    })
    .then((response) => {
      const token = response.data.access_token
      return res.redirect(`${process.env.ORIGIN}?token=${token}`)
    })
    .catch((err) => {
      return res.status(400).send({ message: err.message })
    })
}

Upvotes: 0

Views: 150

Answers (1)

Heiko Theißen
Heiko Theißen

Reputation: 17517

Either use express-session and store the token on the server in req.session.token:

(response) => {
  req.session.token = response.data.access_token;
  req.session.save(function() {
    res.redirect(`${process.env.ORIGIN}`)
  });
}

Or send the token in a session cookie directly:

(response) => {
  res.cookie("token", response.data.access_token, {
    httpOnly: true,
    secure: true,
    sameSite: "None"
  });
  res.redirect(`${process.env.ORIGIN}`)
}

Upvotes: 1

Related Questions