Doing a Http basic authentication in rails

后端 未结 8 1062
独厮守ぢ
独厮守ぢ 2020-12-14 16:09

Hi I\'m from Grails background and new to Rails. I wish to do http basic authentication in rails.

I have a code in grails which does basic authentication like this:<

相关标签:
8条回答
  • 2020-12-14 16:35
    # app/controllers/application_controller.rb
      before_filter :http_basic_auth
    
      def http_basic_auth
        if ENV['HTTP_AUTH'] =~ %r{(.+)\:(.+)}
          unless authenticate_with_http_basic { |user, password|  user == $1 && password == $2 }
            request_http_basic_authentication
          end
        end
      end
    

    and then you just need to export your environment variable with the user:password for example:

       export HTTP_AUTH=user:pass
    

    if you are using heroku.com:

       heroku config:set HTTP_AUTH=user:pass
    
    0 讨论(0)
  • 2020-12-14 16:35

    When connecting to HTTP endpoints protected by basic HTTP authentication I usually use HTTParty. HTTParty is simple wrapper for lower Ruby STD classes like net/http.

    Example usage of HTTParty with basic auth.

    class Delicious
      include HTTParty
      base_uri 'https://api.del.icio.us/v1'
    
      def initialize(u, p)
        @auth = {username: u, password: p}
      end
    
      def recent options={}
        options.merge!({basic_auth: @auth})
        self.class.get('/posts/recent', options)
      end
    end
    
    delicious = Delicious.new("<username>", "<password>")
    
    pp delicious.recent #=> list of recent elements
    

    Check for more examples on GitHub.

    0 讨论(0)
提交回复
热议问题