加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

sinatra – 为什么BCrypt在这种情况下无法进行身份验证?

发布时间:2020-12-17 02:06:16 所属栏目:百科 来源:网络整理
导读:当我创建用户(在sinatra中)时,我这样做 require 'Bcrypt'post '/users' do @user = User.new(params[:user]) @user.password_hash = BCrypt::Password.create(params[:password]) p @user.password_hash == params[:password] # this prints TRUE! @user.sav
当我创建用户(在sinatra中)时,我这样做

require 'Bcrypt'

post '/users' do
    @user = User.new(params[:user])
    @user.password_hash = BCrypt::Password.create(params[:password])
    p @user.password_hash == params[:password]              # this prints TRUE!
    @user.save!
    session[:user_id] = @user.id
    redirect '/'
end

然后,当我尝试验证同一个用户时,我得到了这个

post '/sessions' do
  @user = User.find_by_email(params[:email])
  p @user.id                                                # prints 14
  p @user.password_hash                                     # prints correct hash
  p @user.password_hash.class                               # prints String
  p BCrypt::Password.new(@user.password_hash).class         # prints BCrypt::Password 
  p params[:password]                                       # prints "clown123"
  p BCrypt::Password.new(@user.password_hash) == params[:password] # prints FALSE!

    # redirect '/'
end

什么破了?
BCrypt文档(不使用数据库)中给出的示例每次都有效.
我的db(postgres)中有什么东西可以改变password_hash吗?

使用最新版本的bcrypt和ruby 1.9.3(我已经尝试过ruby 2.0以及相同的结果)

解决方法

你使用什么DB列类型?您可以尝试不使用数据库并使用会话.以下对我来说工作正常,

# app.rb

require 'sinatra'
require 'bcrypt'

enable :sessions

get '/user' do
  session[:password_hash] = BCrypt::Password.create(params[:password])
  return 'success'
end

get '/session' do
  result = BCrypt::Password.new(session[:password_hash]) == params[:password]
  return "Result: #{result}"
end

然后在浏览器中

http://localhost:4567/user?password=secret

# => success

http://localhost:4567/session?password=secret

# => Result: true

http://localhost:4567/session?password=invalid

# => Result: false

如果可行,请尝试再次引入数据库,

require 'sinatra'
require 'bcrypt'

# your postgres config here...

get '/pg-user' do
  user = User.new(password_hash: BCrypt::Password.create(params[:password]))
  user.save!
  return 'success'
end

get '/pg-session' do
  user = User.last
  result = BCrypt::Password.new(user.password_hash) == params[:password]
  return "Result: #{result}"
end

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读