I am learning how to develop API for rails app. I am trying to develop it to use for mobile app. So far I developed an small api for most of the controller. But I am having problem with login. I am using devise for user management and rails 4.1.
I watched railscast video for doorkeeper implementation . But in the video they used doorkeeper with oauth gem. I want to implement it without oauth. How can I do that?
So far I added doorkeeper gem
and in initialize
folder added doorkeeper.rb
with following code
Doorkeeper.configure do
resource_owner_authenticator do
User.find_by_id(session[:current_user_id]) || redirect_to(login_url)
end
end
And added before_action :doorkeeper_authorize!
in a controller
module Api
module V1
class CoursesController < ApplicationController
#before_action :doorkeeper_authorize!
before_action :set_course, only: [:show, :edit, :update, :destroy]
respond_to :json
# GET /courses/1
# GET /courses/1.json
def show
@course = Course.find(params[:id])
@assignment = @course.assignments
respond_with @assignment
end
end
end
end
Now when I hit this link on browser
http://localhost:3000/api/v1/courses/5
I get no output but in console get this
Filter chain halted as :doorkeeper_authorize! rendered or redirected
Completed 401 Unauthorized
And If I comment out before_action :doorkeeper_authorize!
in the controller I get json output with expected data. So how can I configure doorkeeper and make this work?
First things first: you would need to authenticate the user to the API first, after which you would receive an OAuth access token. There's multiple flows (= ways of getting an access token) all listed in RFC 6749. You would then use said access token in subsequent requests to request the resource. Normally you would put this token in the Authorization header of the request.
Right now you're counting on a session variable session[:user_id], which doesn't exist, so it leads to
:doorkeeper_authorize!
redirecting, ending the chain, thus resulting in a 401 Unauthorized response from Doorkeeper.If, in your case, you wish to authenticate with the user's credentials, as per section 1.3.4, you would need to configure Doorkeeper for that. See the wiki.
I hope this gets you going.