My solution was to use RSA digital signing to sign a my token string to ensure it hasn't been tampered with. Then I'd have to send the signature as part of the token string in order to have something to check on the other end. Digital signing with RSA uses the private key to sign some data, and then the public key (or private key, if in a safe environment) to verify the signature.
EDIT: I wanted to express the advantage of having a public key, because I didn't really say anything about that in my initial post: A big advantage to using an asymmetric algorithm to do the digital signing is the fact that you can share a public key. If you have third party applications consuming your API, you can assign each of them a key pair, storing their private key yourself and giving them the public key. They can then use the public key to verify your tokens independently without making a call to your API for any reason.
There are a few drawbacks to doing things this way rather than some sort of token where you're looking up the token in a database:
- The biggest drawback is you're limited in the amount of information that can be attached to your token without making your token huge. How big is too big? Well, that's up to you, really. But I like to keep mine under 200-300 characters or so, depending on how I'm sending it back and forth.
- The other drawback is you must expire these types of tokens, since there is no way to manually expire tokens like this from the server side. Otherwise once you issue the token, it's good forever until you change your private key.
What follows is a simplified version of my solution. What I did was a bit different, as I did some custom binary serialization to reduce the size of my token string, but overall this is the general idea: