如何在rails api中使用devise-jwt设计登录,注册和注销

时间:2018-05-23 05:44:50

标签: ruby-on-rails reactjs devise

我使用devise-jwt为后端使用rails并对前端部分做出反应。

我正在关注此https://github.com/waiting-for-dev/devise-jwt/blob/master/README.md

  

我的routes.rb文件包含:

 Rails.application.routes.draw do
  # remove this in production
  require 'sidekiq/web'
  mount Sidekiq::Web => '/sidekiq'

  namespace :api, defaults: { format: 'json' } do
    namespace :v1 do
      devise_for :users, :controllers => {sessions: 'api/v1/sessions', registrations: 'api/v1/registrations'}
    end
  end
end

我的registrations_controller.rb(app / controllers / api / registrations_controller.rb)

class Api::V1::RegistrationsController < Devise::RegistrationsController
  respond_to :json, :controllers => {sessions: 'sessions', registrations: 'registrations'}

  before_action :sign_up_params, if: :devise_controller?, on: [:create]

  def create
    build_resource(sign_up_params)

    if resource.save
      render :json => resource, serializer: Api::V1::UserSerializer, meta: { message: 'Sign up success', token: request.headers["Authorization"] }, :status => :created
    else
      render :json => resource, adapter: :json_api, serializer: ActiveModel::Serializer::ErrorSerializer, meta: { message: 'Sign up success' }, :status => :created
    end
  end


  protected

  def sign_up_params
    params.require(:sign_up).permit(:first_name, :last_name, :mobile, :email, :password, :password_confirmation)
  end
end

my sessions_controller.rb(app / controllers / api / sessions_controller.rb)

class Api::SessionsController < Devise::SessionsController  
  respond_to :json
end

我的application_controller.rb(app / controllers / application_controller.rb)

class ApplicationController < ActionController::Base
end

基本上,下一步是什么才能使令牌变为现实。我很迷惑。我将如何获得访问令牌并使用它在前端反应部分进行身份验证。

1 个答案:

答案 0 :(得分:3)

假设您有服务器端设置,响应将包含 window.fetch(LOGIN_URL, dataWithLoginInfo).then(response => { const jwt = response.headers.get('Authorization').split('Bearer ')[1]; window.sessionStorage.setItem('jwt', jwt); }).catch(handleError)

在前端,您将请求登录并进行回调以捕获回复:

Authorization

接下来使用const token = window.sessionStorage.getItem('jwt') const headers = { Authorization: `Bearer ${token}` } 标题包含:

import jwt from 'jsonwebtoken';
const decodedToken = jwt.decode(window.sessionStorage.getItem('jwt'));

if (decodedToken.isAdmin) {
  return <AdminPage />;
} else {
  return <NotAdminPage />;
}

或在解码后在您的应用中使用它:

//GSAP Animations
const fadeIn = node => {
  TweenLite.set(node, {
    opacity: 0
  });
  TweenLite.to(node, 1, {
    opacity: 1,
    ease: Power2.easeInOut
  });
};

const fadeOut = node => {
  TweenLite.set(node, {
    opacity: 1,
    scale: 1
  });
  TweenLite.to(node, 1, {
    opacity: 0,
    scale: 0.5,
    ease: Power2.easeInOut
  });
}; 

export default class MyApp extends App {
  static async getInitialProps({ Component, router, ctx }) {
    let pageProps = {};

    if (Component.getInitialProps) {
      pageProps = await Component.getInitialProps(ctx);
    }

    return { pageProps };
  }


  render() {
    const { Component, pageProps, style } = this.props;
    return (
      <Container>
          <Layout>
            <TransitionGroup>
              <Transition
                key={this.props.router.pathname}
                timeout={1000}
                in={true}
                onEnter={fadeIn}
                onExit={fadeOut}
                mountOnEnter={true}
                unmountOnExit={true}
              >
                <Component {...pageProps} />
              </Transition>
            </TransitionGroup>
          </Layout>
      </Container>
    );
  }
}

您将使用https://www.npmjs.com/package/jwt-decodehttps://www.npmjs.com/package/jsonwebtoken之类的内容来解码令牌并从中读取信息,如ID,角色,权限等。

您确实需要遵循以下教程:https://auth0.com/blog/secure-your-react-and-redux-app-with-jwt-authentication/http://jasonwatmore.com/post/2017/12/07/react-redux-jwt-authentication-tutorial-example。然后让一些当地专家看看你的所有代码。