Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doorkeeper gives 401 Unauthorized

i am using doorkeeper gem

my ApplicationController look like this:

private
def current_resource_owner
    Person.find(doorkeeper_token.resource_owner_id) if doorkeeper_token
end

my DemosController look like this:

doorkeeper_for :index
respond_to :json 
def index
    respond_with current_resource_owner
end

response comes like this:

Started GET "/?code=f88d2e95b1b286645d31772c395e0e36708a5i0p970836af640f631bb4f043b5" for 127.0.0.1 at 2014-01-28 11:10:56 +0530
Processing by DemosController#index as HTML
Parameters: {"code"=>"f88d2e95b1b286645d31135c395e0e36708a5b5b970836af640f631bb4f043b5"}
Filter chain halted as #<Proc:0xb608b90@/home/xyz/.rvm/gems/ruby-1.9.3-p484@verticalserver/gems/doorkeeper-1.0.0/lib/doorkeeper/helpers/filter.rb:8> rendered or redirected
Completed 401 Unauthorized in 1ms (ActiveRecord: 0.0ms)
like image 847
user3134821 Avatar asked Oct 21 '22 15:10

user3134821


2 Answers

This is actually an issue on Doorkeeper. To have a custom JSON response for 401 Unauthorized errors instead of a blank page, in ApplicationController I added:

def doorkeeper_unauthorized_render_options
  {json: '{"status": "failure", "message":"401 Unauthorized"}'}
end
like image 124
Rebel Rider Avatar answered Nov 15 '22 04:11

Rebel Rider


I'm not 100% sure if I understand your question correctly. Your code looks fine, but the request seems to be wrong.

With Doorkeeper you need an Access Token and not the Code parameter to access the resource (DemosController#index). So first of all you have to get the Access Token from the Authorization Code. Therefore make a request

GET "/oauth/token?code=...&grant_type=authorization_code&redirect_uri=...&client_id=...&client_secret=..."

Make sure that the redirect_uri matches with the one registered with your client application and add the correct client_id and client_secret to the request. Also use always a fresh code parameter. Per default it is only valid for 10 minutes after generation. Notice, in case of customized Doorkeeper routes the url (/oauth/token) might be different.

If you done the request correctly, the response will contain a valid access token.

Then make a GET request to "/index.json?access_token=..." instead of "/?code=...". '.json' tells Rails your client can handle JSON. Otherwise you will get a 406 Response, which means that the requested format (by default HTML) is not supported. Instead of '.json' you can also send Accept="application/json" in the HTTP header.

The 401 Unauthorized response, what you're currently receiving, means that the authentication information (in your case a valid Access Token) is wrong or missing at all.

Hope that helps.

like image 28
Timo Avatar answered Nov 15 '22 04:11

Timo