2017-12-02 5 views
0

나는 Ruby On Rails에서 토큰 스토어를 데이터베이스에 저장해야합니까?

나는 토큰이 존재 여부를 확인하는 모델 인증을 생성, 사용자 로그인 시스템을 구축 보석 jwt, devise를 사용합니다. 내가 user/sessions에 POST 요청을 수행 할 때

class Authentication < ApplicationRecord 
    def self.generate_access_token(email) 
    payload = {:email => email} 
    secret = 'secret' 
    token = JWT.encode payload, secret, 'HS256' 
    return token 
    end 
end 

컨트롤러/사용자/sessions_controller.rb가

def create 
    user = User.where(email: params[:email]).first 
    if user&.valid_password?(params[:password]) 
     @token = Authentication.generate_access_token(user.email) 
     Authentication.create(access_token: @token) 
     authentications = {token: @token, email: user.email} 
     render json: authentications, status: :created 
    else 
     head(:unauthorized) 
    end 
    end 

내가 토큰을 얻을 것이다

모델/authentication.rb :

이 코드를 따라 사용자 이메일을 보내어 클라이언트의 로컬 저장소에 저장하고 토큰이 유효한지 확인하는 데 도움을줍니다. 토큰 데이터베이스에 저장할 필요가 없습니다 수 있도록하는 방법이 있습니다, 내 질문에

def authenticate_token 
    token = Authentication.find_by_access_token(params[:token]) 
    head :unauthorized unless token 
end 

:

이 규정을 따르십시오?

답변

1

토큰을 디코딩하고 거기에 저장된 전자 메일을 가져올 수 있으며 해당 전자 메일로 사용자를 찾을 수 있습니다. 내가 당신이라면

class ApplicationController < ActionController::API 
    before_action :authenticate_token 

    def authenticate_token 
    token = request.headers['Authorization'].to_s =~ /^Bearer (.*)$/i && $1 
    return head :unauthorized unless token 
    payload = JWT.decode(token, 'secret', true, algorithm: 'HS256') 
    user = User.find_by(email: payload['email']) 
    return head :unauthorized unless user 
    # TODO set the `user` as current_user 
    # How to patch devise's `current_user` helper is another story 
    end 
end 

, 내가의 사용자 ID를 둘 것 :

Authorization: Bearer <token> 

처럼 당신이 할 수있는 before_action을 정의 할 수 있습니다, 당신은 Authorization 헤더에 토큰을 가지고 가정 ID가 더 짧아서 데이터베이스에서 조회하기가 더 빠르고 전자 메일이 아닌 토큰 (인터넷이 아니라 개인 정보는 공개되지 않습니다.

devise 대신 knock을 사용하면 이러한 지저분한 것들을 모두 건너 뛸 수 있습니다.

+0

감사합니다. –