Rails에서 HTTP Basic Auth 적용하기(How to add HTTP basic auth on Rails)
HTTP Basic Auth는 HTTP에서 기본적으로 사용되는 인증 방식이고, ID/PW를 Base64로 인코딩해서 Auth 헤더에 넣어 서버가 신뢰된 사용자인지 검증하는 방식으로 동작합니다. 물론 http 환경, MITM이 가능한 상태의 환경에선 굉장히 위험할 수 있는 방식이지만, 별다른 걱정 없이 쉽게 인증을 적용할 수 있기 때문에 간단한 토이 프로젝트에선 사용해볼만 합니다. (다른 인증은 만들기 귀찮..)
간단하게 Rails에서 HTTP Auth 적용하는 방법 메모할겸 포스팅합니다.
(자꾸 까먹네요..)
(path는 개인 취향입니다. 그냥 controller 아래 만들어도.. 상관은 없어요)
e.g
간단하게 Rails에서 HTTP Auth 적용하는 방법 메모할겸 포스팅합니다.
(자꾸 까먹네요..)
Step 1. concern 모듈 만들어주기.
app/controllers/concerns/http_auth_concern.rb
(path는 개인 취향입니다. 그냥 controller 아래 만들어도.. 상관은 없어요)
module HttpAuthConcern
extend ActiveSupport::Concern
included do
before_action :http_authenticate
end
def http_authenticate
authenticate_or_request_with_http_basic do |username, password|
username == 'username' && password == 'password'
end
end
end
Step 2. Basic auth가 필요한 컨트롤러에 적용하기
include로 필요한 부분에 만들어둔 모듈을 로드해주면 끝납니다.include HttpAuthConcern
e.g
class YourPrivateController < ApplicationController
before_action :set_zzz, only: [:show, :edit, :update, :destroy]
skip_before_action :verify_authenticity_token, :only => [:testzzsfdfsd]
include HttpAuthConcern
Step 3. There’s no third one.
![]() |
https://i.giphy.com/d8YBM0IgPszle.gif |