Oleksandr Verhun
Oleksandr Verhun

Reputation: 854

Can I send requests to app with devise without credentials?

I have backend app with devise and a ionic app from which I make requests to backend.
Whenever I send requests, gets me 401 status unauthorized.

In this project I've already doorkeeper to manage authorization, so I don't rly need authorization from devise.
Can I somehow make these requests( add something to headers ) always authorized without sending post request with credentials?

Upvotes: 0

Views: 279

Answers (1)

Jimeux
Jimeux

Reputation: 3026

You need to identify the user somehow. If you're not using a session, you'll need to generate some kind of access token, which Doorkeeper can do for you. I'm not sure if this is helpful or not, but I set up the following flow recently.

One option when using OAuth2 through a trusted client, e.g. a front-end app you build/distribute yourself, is the Resource Owner Password Credentials Grant. Doorkeeper has a guide in the docs for this with advice on dealing with Devise.

I ended up with something like this in my Doorkeeper initializer. You don't need to authorize the client, because you trust it:

resource_owner_from_credentials do |routes|
  request.params[:user] = {:email => request.params[:email], :password => request.params[:password]}
  request.env['devise.allow_params_authentication'] = true
  request.env['warden'].authenticate!(:scope => :user)
end

skip_authorization do |resource_owner|
  true
end

Then you should be able to send a request using the password grant type as follows (also shown in the docs).

RestClient.post 'http://localhost:3000/oauth/token', {grant_type: 'password', email: '[email protected]', password: 'password'}, {:accept => 'application/json'}

You should receive the same JSON back as shown in the docs.

{
  "access_token": "1f0af717251950dbd4d73154fdf0a474a5c5119adad999683f5b450c460726aa",
  "token_type": "bearer",
  "expires_in": 7200
}

Now you have a way of identifying your user. You just attach this token to each request to endpoints protected by doorkeeper_for.

RestClient.get 'http://localhost/api/v1/users', { 'Authorization' => 'Bearer 1f0af717251950dbd4d73154fdf0a474a5c5119adad999683f5b450c460726aa', :accept => 'application/json'}

Upvotes: 1

Related Questions