Rails에서 HTTP Basic Auth 적용하기

HTTP Basic Auth는 HTTP에서 기본적으로 사용되는 인증 방식입니다. ID/PW를 Base64로 인코딩해서 Auth 헤더에 넣어 서버가 신뢰된 사용자인지 검증하는 방식으로 동작합니다.

물론 http 환경, MITM이 가능한 상태의 환경에선 굉장히 위험할 수 있는 방식이지만, 별다른 걱정 없이 쉽게 인증을 적용할 수 있기 때문에 간단한 토이 프로젝트에선 사용해볼만 합니다.

오늘은 간단하게 Rails에서 HTTP Auth 적용하는 방법에 대해 이야기합니다.

Step1 Concern 모듈 만들어주기

인증 처리를 위해 controller 하위에 concerns를 만들어줍시다. 저는 app/controllers/concerns/http_auth_concern.rb 경로로 진행했습니다.

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

코드는 단순합니다. authenticate_or_request_with_http_basic를 통해 Basic Auth를 만들어줬습니다. Basic auth가 단순히 Base64 값이기 때문에 직접 문자열을 더해서 만든 후 검증해도 됩니다.

Step2 Add Basic Auth

include로 필요한 부분(e.g Controller)에 만들어둔 모듈을 로드(include HttpAuthConcern)해주면 끝납니다.

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 ;D