Authentication for Sinatra REST API app
Asked Answered
P

3

6

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.

Psychro answered 19/8, 2013 at 13:40 Comment(1)
you might want to checkout grape github.com/intridea/grapeLobster
R
1

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.

Reiter answered 8/5, 2015 at 21:38 Comment(0)
L
1

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.

Ladawnladd answered 6/2, 2016 at 6:35 Comment(0)
M
-1

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.
Mcdougald answered 4/11, 2013 at 23:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.