Simon
Simon

Reputation: 1761

Why is it okay to store the state parameter for Authorization Code flow in a cookie?

When implementing Authorization code flow in a regular web app, it's permitted to store the state parameter in cookies. See here and [here] (https://auth0.com/docs/protocols/oauth2/mitigate-csrf-attacks)

Why is storing the state (aka nonce) in a cookie an acceptable solution? For example if we do this in nodejs, the code will look something like this.

  app.use('/login', (_req, res) => {
    state = randomString(32)
    const authorizationEndpointUrl = new URL(`${activeConfig.authorization.domain}/authorize`);
    authorizationEndpointUrl.search = new URLSearchParams({
      audience: activeConfig.authorization.audience,
      response_type: 'code',
      redirect_uri: 'http://localhost:8443/callback',
      client_id: activeConfig.authorization.clientId,
      scope: activeConfig.authorization.scope,
      state,
    }).toString();
    res.cookie('state', state, { httpOnly: true }); // cookie set here
    res.redirect(authorizationEndpointUrl.toString());
  });

  app.use('/callback', req => {
     // check that url state matches req.cookie.state???
  })

But if we do that, what stops an attacker from just setting the same "fake" state in the response url and cookie? What am I missing here?

Upvotes: 2

Views: 3087

Answers (2)

stillcollating
stillcollating

Reputation: 26

According to the links you posted, the state param (nonce) should be added as a url parameter to the request. oauth will validate against the url parameters and not the cookie. So, having the nonce stored in the cookie shouldn't be a problem, it's not looking for the nonce in the cookie. The attacker doesn't know the nonce to be able to craft the url parameters, I think is the point. where you store the nonce doesn't matter really.

It is confusing they are calling this 'state'. It's specifically for CSRF attacks. Not to be confused with oauth tokens. Those are already encrypted.

Upvotes: 0

vibronet
vibronet

Reputation: 7394

The cookie you use for tracking the state should not be something that can be forged. The client should at a minimum sign it, so that no one but the client itself can generate it. At that point an attacker would only be able to replay such a cookie if they happen to have access to the device right after the request was generated and before the legitimate response is returned, but not to forge an unprompted authorization response from an arbitrary device.

Upvotes: 2

Related Questions