Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save evanbeard/2662058 to your computer and use it in GitHub Desktop.
Save evanbeard/2662058 to your computer and use it in GitHub Desktop.
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
@owahab
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\":\"[email protected]\",\"password\":\"123456\"}}

@johnjohndoe
Copy link

I made some changes to the latest version of @Bomadeno

@nwalter08
Copy link

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
Copy link

IvRRimum commented Jan 21, 2017

You should update this: before_filter => before_action

@mortik
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.

@indyarocks
Copy link

Thank you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment