Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
API JSON authentication with Devise
class Api::RegistrationsController < Api::BaseController
respond_to :json
def create
user = User.new(params[:user])
if user.save
render :json=> user.as_json(:auth_token=>user.authentication_token, :email=>user.email), :status=>201
return
else
warden.custom_failure!
render :json=> user.errors, :status=>422
end
end
end
class Api::SessionsController < Api::BaseController
before_filter :authenticate_user!, :except => [:create, :destroy]
before_filter :ensure_params_exist
respond_to :json
def create
resource = User.find_for_database_authentication(:email => params[:user_login][:email])
return invalid_login_attempt unless resource
if resource.valid_password?(params[:user_login][:password])
sign_in(:user, resource)
resource.ensure_authentication_token!
render :json=> {:success=>true, :auth_token=>resource.authentication_token, :email=>resource.email}
return
end
invalid_login_attempt
end
def destroy
resource = User.find_for_database_authentication(:email => params[:user_login][:email])
resource.authentication_token = nil
resource.save
render :json=> {:success=>true}
end
protected
def ensure_params_exist
return unless params[:user_login].blank?
render :json=>{:success=>false, :message=>"missing user_login parameter"}, :status=>422
end
def invalid_login_attempt
render :json=> {:success=>false, :message=>"Error with your login or password"}, :status=>401
end
end
@nmondollot

This comment has been minimized.

Copy link

nmondollot commented Nov 7, 2012

Thank you for this, it works great!

@corywilkerson

This comment has been minimized.

Copy link

corywilkerson commented May 16, 2013

Couldn't I just kill anyone's token here?

@Bomadeno

This comment has been minimized.

Copy link

Bomadeno commented May 28, 2013

I think my modification here https://gist.github.com/Bomadeno/5662871 prevents you destroying other people's tokens.

@arelenglish

This comment has been minimized.

Copy link

arelenglish commented Jul 22, 2013

Thanks for doing this!! It was a huge help!

@arelenglish

This comment has been minimized.

Copy link

arelenglish commented Jul 22, 2013

This might be obvious, but how to you create a new account? What do you have to pass? and what url do you post to?

@owahab

This comment has been minimized.

Copy link

owahab commented Jul 24, 2013

@arelenglish This works for user creation:
curl -v -H 'Content-Type: application/json' -H 'Accept: application/json' -X POST http://localhost:3000/api/sessions -d "{\"user\":{\"email\":\"foo@example.com\",\"password\":\"123456\"}}

@johnjohndoe

This comment has been minimized.

Copy link

johnjohndoe commented Aug 16, 2013

I made some changes to the latest version of @Bomadeno

@nwalter08

This comment has been minimized.

Copy link

nwalter08 commented Jan 22, 2014

If you are using Rails 4 then you need to edit the RegistrationsController to fix this error http://stackoverflow.com/questions/17335329/activemodelforbiddenattributeserror-when-creating-new-user

And if you are using a current version of Devise that doesn't create authentication tokens anymore, you need to make your own like this http://stackoverflow.com/a/19071745/875670

@IvRRimum

This comment has been minimized.

Copy link

IvRRimum commented Jan 21, 2017

You should update this: before_filter => before_action

@mortik

This comment has been minimized.

Copy link

mortik commented Apr 16, 2017

Here is a working version for devise_jwt gem

    class SessionsController < Api::BaseController
      skip_authorization_check # cancancan
      before_action :authenticate_user!, except: [:create, :destroy]

      respond_to :json

      def create
        resource = User.find_for_database_authentication(email: login_params[:email])
        return invalid_login_attempt unless resource

        if resource.valid_password?(login_params[:password])
          sign_in(:user, resource)
          render json: { success: true }
          return
        end
        invalid_login_attempt
      end

      def destroy
        resource = User.find_for_database_authentication(email: login_params[:email])
        sign_out(resource)
        render json: { success: true }
      end

      private def login_params
        @login_params ||= params.permit(:email, :password)
      end

      protected def ensure_params_exist
        return unless params[:user_login].blank?
        render json: { success: false, message: "missing user_login parameter" }, status: 422
      end

      protected def invalid_login_attempt
        render json: { success: false, message: "Error with your login or password" }, status: 401
      end
    end

This Returns on create a response header with a valid jwt token and revokes this token on logout.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.