简体   繁体   English

在ruby> = 2.5.1 /> = rails 5中生成随机令牌

[英]Generate a random token in ruby >= 2.5.1 / >= rails 5

I can see from here that has_secure_token can generate a random token for a new record in a (User) model. 这里可以看到has_secure_token可以为(用户)模型中的新记录生成随机令牌。 How can I simply generate a random token without needing to do it for a model? 如何简单地生成随机令牌而无需为模型做呢? (ie suppose an app has no model(s) or to put it really simply, to run some (preferably very simple) method, and it should return a random string like pX27zsMN2ViQKta1bGfLmVJE (即,假设某个应用没有模型,或者说它很简单,可以运行某种方法(最好是非常简单)),并且它应该返回一个随机字符串,例如pX27zsMN2ViQKta1bGfLmVJE

I have tried gems SecureRandom and digest as recommended in other answers, but neither seems to bundle install successfully (the SO answers were oldish so perhaps those gems are deprecated?) - I'm using ruby 2.5.1 and rails 5.2.3 我已经按照其他答案中的建议尝试了宝石SecureRandomdigest ,但是似乎都没有成功捆绑安装(SO答案很旧,所以也许这些宝石已被弃用?)-我使用的是ruby 2.5.1和rails 5.2.3

My goal is simply to generate tokens to use as keys for an API, so I essentially just need randomly generated strings that are safe to use in urls, perhaps a method that I can specify the length of the token (but I'll take what I can get for now!) 我的目标只是生成令牌以用作API的键,因此,我基本上只需要可以在url中安全使用的随机生成的字符串,也许我可以指定令牌的长度(但是我会选择我现在可以得到!)

Just use SecureRandom . 只需使用SecureRandom It's not a gem that you have to install. 它不是必须安装的宝石。 It's built into Ruby: 它内置在Ruby中:

⇒ ruby -v
ruby 2.5.1p57 (2018-03-29 revision 63029) [x86_64-darwin18]
⇒ irb
2.5.1 :001 > require 'securerandom'
 => true
2.5.1 :002 > SecureRandom.hex(32)
 => "89d45edb28859a905672b707c8f7599f766d12074584ef48a997230dfc0e0998"
2.5.1 :003 > SecureRandom.base64(12)
 => "KaZbhQ7o7U/f9pMs"
2.5.1 :004 > SecureRandom.uuid
 => "ade17ef5-0943-4c70-b417-df7c96c198cd"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM