rails api+react+jwt验证教程

1.生成railsAPI项目

rails new 项目名 --datebase=postgresql

2.创建model的User模型,username与密码字段

rails g model user username password_digest

3.生成user的控制器与创建动作页

rails g controller users create

4.注释掉Gemfile中的bcrypt,并添加jwt gem包

gem 'bcrypt', '~> 3.1.7'
gem 'jwt'

5.在models的application_record.rb中添加has_secure_password字段

class User < ApplicationRecord
  has_secure_password
end

6.在applicatio_controller.rb中添加如下字段:

class ApplicationController < ActionController::Base
  protect_from_forgery except: :create
end

7.bundle intsall

8.创建数据库并迁徙

rails db:create db:migrate

9.路由设置

resources:users

10.users_controller添加

class UsersController < ApplicationControlle
  def create
      input = User.new(params.permit(:username, :password))
    if(input.save)
      :ok
    else
      :bad_request
     end
  end
end

11.创建token控制器与create动作

rails g controller tokens create

12.路由中

Rails.application.routes.draw do
 
  get 'tokens/create'
  resources :users
  resources :tokens, only: [:create] 
  # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end

13,tokens控制器

class TokensController < ApplicationController
  def create

  	user = User.find_by(username: params[:username])
  	
  	if user&.authenticate(params[:password])
  	  render json: {
        jwt: encode_token({id: user.id, username: user.username})
  	  }
    else
     head :not_found
    end
   end

  private 

  def encode_token(payload={})
    exp = 24.hours.from_now
    payload[:exp] = exp.to_i
    JWT.encode(payload, Rails.application.credentials.fetch(:secret_key_base))
  end

end

14.生成新密钥

rails secret

15.使用vim编辑密钥

EDITOR=vim bin/rails credentials:edit

16.配置

require_relative 'boot'

require 'rails/all'

# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)

module Jwt
  class Application < Rails::Application
    # Initialize configuration defaults for originally generated Rails version.
    config.load_defaults 5.2

    config.generators.system_tests = nil

    config.middleware.insert_before 0, Rack::Cors do
      allow do
          origins '*'
          resource '*',headers: :any, methods: [
          :delete, :put, :patch, :get, :psot, :options



          ]
        
    end

    # Settings in config/environments/* take precedence over those specified here.
    # Application configuration can go into files in config/initializers
    # -- all .rb files in that directory are automatically loaded after loading
    # the framework and any gems in your application.
  end
end

17.生成react

原创声明,本文系作者授权云+社区发表,未经许可,不得转载。

如有侵权,请联系 yunjia_community@tencent.com 删除。

发表于

我来说两句

0 条评论
登录 后参与评论

扫码关注云+社区

领取腾讯云代金券