Doing a Http basic authentication in rails

后端 未结 8 1061
独厮守ぢ
独厮守ぢ 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:20

    In Ruby on Rails 4 you can easily apply basic HTTP Authentication site wide or per controller depending on the context.

    For example, if you need site wide authentication:

    class ApplicationController < ActionController::Base
      http_basic_authenticate_with name: "admin", password: "hunter2"
    end
    

    Or on a per controller basis:

    class CarsController < ApplicationController
      http_basic_authenticate_with name: "admin", password: "hunter2"
    end
    
    0 讨论(0)
  • 2020-12-14 16:24

    There is a great Rails Cast on this topic

    http://railscasts.com/episodes/82-http-basic-authentication

    0 讨论(0)
  • 2020-12-14 16:31

    Write the below code, in the controller which you want to restrict using http basic authentication

    class ApplicationController < ActionController::Base
      http_basic_authenticate_with :name => "user", :password => "password" 
    end
    

    Making a request with open-uri would look like this:

    require 'open-uri'
    
    open("http://www.your-website.net/", 
      http_basic_authentication: ["user", "password"])
    
    0 讨论(0)
  • 2020-12-14 16:31

    I upvoted @Nishant's answer but wanted to add another tidbit. You can always set filters so it only applies to certain controller actions by passing only or except like so:

    http_basic_authenticate_with name: "admin", password: "strongpasswordhere", only: [:admin, :new, :edit, :destroy]

    or

    http_basic_authenticate_with name: "admin", password: "strongpasswordhere", except: [:show]

    Very helpful in many instances.

    0 讨论(0)
  • 2020-12-14 16:32

    Above answers are correct, but it is better to not put the user and password in the source code.

    Better have the password in environment variables for production (in the code is OK for development)

    class YourController..
      http_basic_authenticate_with name: ENV["HTTP_BASIC_AUTH_USER"], password: ENV["HTTP_BASIC_AUTH_PASSWORD"], if: -> { ENV['RAILS_ENV'] == 'production' }
      http_basic_authenticate_with name: "user", password: "pass", if: -> { ENV['RAILS_ENV'] != 'production' }
    
    0 讨论(0)
  • 2020-12-14 16:34

    For the latest rails version there is a ASCIIcast that explains with steps the HTTP Basic Authentication.

    The link goes here.

    Side Note: Be warned that HTTP Basic Authentication transmits the username and password in clear text, so you should not use this method for applications where a higher level of security is required.

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