Using OAuth2 with both Live and Paper accounts

Hi guys,

I’m using the new OAuth2 authentication but I found that when I ask for a new token for both live and paper account, the paper account returns this:

com.deepwolf.trader.HttpException: {"code":40410000,"message":"invalid_request"}

Then I delete the code and I re-execute the authentication (popup + redirect to Alpaca + Approve) and everything works until the next reboot.

Is there any conflict on using a code to ask for a token on a paper account? Is there any expiration?


What do you mean ask for a new token for both live and paper accounts? The OAuth token exchange is only to be done with the POST endpoint - the token you get from that actually belongs to the user instead of a specific account and can be used for both paper and live accounts (using vs The token also currently does not expire so there is no need to request a new one unless you lose it and require the user to sign in again.

This is exactly what I thought, but for an unknown reason, the paper account is not valid anymore with that error. By the way, what does mean “code”:40410000?

Can you please share the verbose output of your curl request that’s returning that? (hide any sensitive info)

40410000 isn’t a specific code for a single error - it’s the code used for when any endpoint returns a 404, which could really be for a number of reasons. In specific to OAuth endpoints, 40410000 is returned when either the redirect_uri doesn’t match (make sure it’s encoded correctly) or if the authorization_code is not found.

I’m not using CURL, but from my app.

Anyway, this is the sequence. Having both live and paper accounts:

  1. Request a token with code X (received 24h ago) from the previous trading session)
  2. token Y received, authenticated
  3. Request a token for the paper account with a code Y (received 24h ago from the previous trading session)
  4. error

So I’ve got 2 different codes for paper and live. Is this ok or you guys save the latest code, so when a new token is requested with an old code goes in error?


Authorization codes actually expire in 10 minutes so you can’t use them 24 hours later. You’re supposed to exchange the authorization code for an access token immediately after receiving it.

If you must request authorization twice from the user for each account, you may do so and end up with two access tokens that would both be valid.

Ok, now it’s much clearer to me. I think it would be better to ask for a code, then immediately a token and store the token in my database rather than the code, because the token does not expire, but the code does. Correct?

That’s right. Storing the authorization code is not useful as it’s temporary and expires in 10 minutes.

Tried and works like a charm. Thank you Neal.