DexCurl
DexCurl

Reputation: 1703

Authentication for Sinatra REST API app

I'm building an API with Sinatra (using Angular for the client side and want others to have access to API) and have it also be an OAuth provider. I am wondering what the best route to take (work off existing gems or roll own solution off Warden or something).

Have used devise and doorkeeper for authentication and oauth before with Rails, wondering what best solution for Sinatra is.

Ideally I don't want the views or be able to extend/mod the actions of an existing solution, as I'm interacting with it purely as an API.

Upvotes: 6

Views: 6860

Answers (3)

nurettin
nurettin

Reputation: 11746

APIs normally accept your login request and send you an authentication token which you need to pass back in each call. This is very similar to cookie based sessions where your browser automatically passes back the cookie which is acquired on initial website visit.

From what I've seen in Sinatra's docs, you could make a session-based authentication system like this:

enable :session
disable :show_exceptions

use Rack::Session::Pool,
  key: 'session_id'

post '/login' do
  user = User.login_success(params)
  halt 401 if user.nil?
  session[:user] = user
  200
end

get '/fun' do
  user = session[:user]
  halt 401 if user.nil?
  halt 403 if !user.has_permission_for '/fun'
  "fun was had"
end

Now all you need to do in your client is to pass back the cookie token returned in response to initial visit when requesting an API function. This can be done with any web client library that supports cookie stores (such as libcurl) or by inserting the session cookie into the request header manually. Rack::Minitest functionality also supports cookies, so you can test your API with minitest.

Upvotes: 1

Josh Hunter
Josh Hunter

Reputation: 1687

I just recently did the same thing using the following answer from S/O

What is a very simple authentication scheme for Sinatra/Rack

It implies a user model, but instead of using that, I just set a user and admin password in my config file. Then I had a login form that just took a password. When the user enters that password, I checked it against the one in settings and set the session['user'] to :admin or :user according to whichever it matched (or nil if none). Then on each of my routes, I called auth: :user or auth: :admin accordingly.

Upvotes: 1

Nicky McCurdy
Nicky McCurdy

Reputation: 19564

See Sinatra API Authentication.

Quick summary:

  • Sinatra has no built-in auth.
  • It's best to build auth yourself (see the link).
  • There are gems available, but you probably won't need them for something as simple as an API.

Upvotes: -1

Related Questions