Mapping Sinatra Basic HTTP Auth On One Page Only

Any idea how I can make Sinatra HTTP auth appear on only one page in a Sinatra modular application?

+6
source share
3 answers

Adding an answer to @iain since you asked for HTTP Auth (I accept Basic auth).

class MyApp < Sinatra::Base def authorized? @auth ||= Rack::Auth::Basic::Request.new(request.env) @auth.provided? && @auth.basic? && @auth.credentials && @auth.credentials == ["CUSTOM_USERNAME","SECRET_PASSWORD"] end def protected! unless authorized? response['WWW-Authenticate'] = %(Basic realm="Restricted Area") throw(:halt, [401, "Oops... we need your login name & password\n"]) end end get "/protected_content" do protected! "in secure" end get "/" do "anyone can access" end end 
+9
source

Vicki Cijwani's comment is correct, you should give a lot more information (note!), But here is the answer.

You can do this in several ways. If we assume that your authentication method is called protected! :

 class MyApp < Sinatra::Base # assumed for all examples get "/only-this-page-has-auth" do protected! "Only admin allowed!" end get "/this-wont-have-auth" do "Everybody can access this" end end 

Or you can use a filter

  before "/only-this-page-has-auth" do protected! end get "/only-this-page-has-auth" do "Only admin allowed!" end get "/this-wont-have-auth" do "Everybody can access this" end 

Or, if you are going to use Sinatra::Namespace from the sinatra-contrib gem (maybe a little more from advanced use, but I use it a lot, because I think this is a good way to do something), and the protected page will now be in folder "/ admin / only-this-page-has-auth"

  namespace "/admin" do before do protected! end get "/only-this-page-has-auth" do "Only admin allowed!" end end get "/this-wont-have-auth" do "Everybody can access this" end 
+3
source

The best way is to use: https://rubygems.org/gems/sinatra-basic-auth The documentation is excellent:

 require "sinatra" require "sinatra/basic_auth" # Specify your authorization logic authorize do |username, password| username == "john" && password == "doe" end # Set protected routes protect do get "/admin" do "Restricted page that only admin can access" end end 

http://www.rubydoc.info/gems/sinatra-basic-auth/0.1.0 It is very simple to use

+2
source

All Articles