Reputation: 67
I'm encountering an issue with my API-only Rails application. I attempted to set up token-based authentication using Devise and Devise-JWT, but it seems that I'm not receiving the Bearer token in my response when testing the API with Postman. I'm relatively new to Devise, tokens, and security in general. Could you offer some guidance and potential solutions for this problem? Thanks in advance.
# devise.rb
config.jwt do |jwt|
jwt.secret = ENV['DEVISE_JWT_SECRET_KEY']
jwt.dispatch_requests = [['POST', /api/]]
jwt.expiration_time = 12.hours.to_i
end
# routes.rb
Rails.application.routes.draw do
namespace :api do
devise_for :users, controllers: {
sessions: 'api/sessions'
}
end
end
# api/sessions_controller.rb
class Api::SessionsController < Devise::SessionsController
def create
user = User.find_by('lower(email) = ?', params[:email])
if user.blank? || !user.valid_password?(params[:password])
render json: {
errors: ['Invalid email/password combination']
}, status: :unauthorized
return
end
sign_in(:user, user)
render json: {
user: user,
token: user.token
}
end
# user.rb
# frozen_string_literal: true
class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
devise :database_authenticatable,
:registerable,
:recoverable,
:rememberable,
:validatable,
:trackable,
:jwt_authenticatable,
jwt_revocation_strategy: JwtDenylist
end
# jwt_denylist.rb
class JwtDenylist < ApplicationRecord
include Devise::JWT::RevocationStrategies::Denylist
self.table_name = 'jwt_denylist'
end
# cors.rb
Rails.application.config.middleware.insert_before 0, Rack::Cors do
allow do
origins '*'
resource '*',
headers: :any,
methods: %i[get post put patch delete options head]
end
end
Upvotes: 1
Views: 163