Search code examples
ruby-on-railsrubyrandomtokensecure-random

How to use SecureRandom.urlsafe_base64?


I'm really new to this and need to create an url-safe token of between 2 and 20 characters and only alphanumeric chars (letters and numbers) are allowed. I use this token for processing by a payment provider.

I have the method below, but I got an error that the token was invalid. How can I rewrite the method so that it's still url-safe but does not exceed 20 characters and only uses alphanumeric chars?

token = SecureRandom.urlsafe_base64

Solution

  • As per documentation SecureRandom.urlsafe_base64 will return “-” and “_” which are characters you've said you don't want.

    You can use SecureRandom.hex(n) to get 2*n chars containing a-z and 0-9. It's still URL safe. Your final code will be:

    token = SecureRandom.hex # without `n` token will be 16 characters long.