JWT 构建Rails API 授权登录

参考下面的连接
https://www.jianshu.com/p/56467f890516

  def screen_login_v2
    puts "params[:login] : #{params[:login]} params[:password]:#{params[:password]}"

    if params[:login].blank? || params[:password].blank?
      render json: { status: false }
      return
    end
    user = User.find_by(username: params[:login])
    if user.blank?
      return render json: { status: false, msg: "wrong user name or password" }
    end
    if user.valid_password?(params[:password]) #devise验证用户的密码
      token = request.headers['Auth-Token'] #获取headers里的信息
      puts "token111: #{token}"
      payload = {
        user: user.username,
        email: user.email,
        exp: 1.weeks.from_now.to_i
      }
      jwt_key = "12312SM6retKX1Z82Y53N3LFGL"
      @token = JWT.encode(payload, jwt_key) #生成token
      begin
        decoded_token = JWT.decode(@token, jwt_key, true) #解密token
      rescue => e
        render(json: { error: e.message }, status: 500) and return
      end
      return render json: { status: true, msg: "login success", token: @token, decoded_token: decoded_token }
    end
    return render json: { status: false, msg: "wrong user name or password" }

  end
[Haima的博客] http://www.cnblogs.com/haima/
posted @ 2021-08-19 14:42  HaimaBlog  阅读(57)  评论(0编辑  收藏  举报