Authentication for Sinatra REST API Application

I am creating an API with Sinatra (using Angular for the client side and want others to have access to the API), and it is also an OAuth provider. I am wondering what is the best route to take (work with existing gems or roll your own solution with Warden or something else).

Used the device and gatekeeper for authentication and oauth before with Rails, wondering what the best solution for Sinatra is.

Ideally, I don’t want views or cannot extend / modify the actions of an existing solution, since I interact with it exclusively as an API.

+6
source share
3 answers

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

What is a very simple authentication scheme for Sinatra / Rack

It implies a user model, but instead I just set the user and administrator password in my configuration file. Then I had a login form that just took the password. When the user enters this password, I checked it against what was in the settings and set the ['user'] session to: admin or: the user according to what he agreed (or nil if not). Then on each of my routes I called auth :: user or auth :: admin, respectively.

+1
source

The APIs usually take your login request and send you an authentication token, which you need to pass in every call. This is very similar to cookie-based sessions in which your browser automatically transmits cookies that were acquired when you first visited the website.

From what I saw in the Sinatra docs, you can 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 have to do in your client is to pass back the cookie token returned in response to the initial visit when requesting the API function. This can be done with any web client library that supports cookie stores (e.g. libcurl) or by manually inserting a session cookie into the request header. Rack::Minitest Functionality also supports cookies, so you can test your API with minitest.

+1
source

See Sinatra API Authentication .

Short summary:

  • Sinatra does not have built-in auth.
  • It is best to build auth (see link).
  • There are gems available, but you probably won't need them for something simple API.
0
source

Source: https://habr.com/ru/post/952031/


All Articles