development

Rails 3 session_store domain : all이 실제로하는 일은 무엇입니까?

big-blog 2020. 12. 25. 22:42
반응형

Rails 3 session_store domain : all이 실제로하는 일은 무엇입니까?


더 명확하게 질문을 업데이트했습니다.

다음과 같이 하위 도메인간에 세션을 공유하도록 session_store의 도메인을 설정할 수 있음을 이해합니다. Rails.application.config.session_store :cookie_store, :key => '_my_key', :domain => "mydomain.com"

Rails 3에서 설정 :domain => :all은 무엇을합니까? 최상위 도메인에서 세션을 공유 할 수 없으며 쿠키는이를 수행 할 수 없습니다. 문서는 하나의 최상위 도메인을 가정한다고 말합니다. 그렇다면 여러 도메인이 앱에 액세스하면 어떻게 될까요?

내 앱에서 내 사용자는 하나의 기본 도메인의 개인 하위 도메인을 만들 수 있지만, 그런 다음 자체 사용자 지정 도메인을 통해 해당 하위 도메인에 액세스 할 수도 있습니다.

a) 기본 도메인의 모든 도메인 (예 : "mydomain.com")에서 세션을 공유 할 수있는 올바른 session_store 도메인 설정은 무엇입니까? b) CNAME 사용자 지정을 통해 개인 하위 도메인에 액세스하는 사용자 (예 : "user1.mydomain.com") "some.otherdomain.com"과 같은 URL은 여전히 ​​별도의 세션을 생성 할 수 있습니다.

감사


좋습니다.이를 수행하는 방법은 세션 쿠키에 도메인을 동적으로 설정하는 것입니다. 이 작업을 충분히 일찍 수행하려면 랙 미들웨어로 수행해야합니다.

# Custom Domain Cookie
#
# Set the cookie domain to the custom domain if it's present
class CustomDomainCookie
  def initialize(app, default_domain)
    @app = app
    @default_domain = default_domain
  end

  def call(env)
    host = env["HTTP_HOST"].split(':').first
    env["rack.session.options"][:domain] = custom_domain?(host) ? ".#{host}" : "#{@default_domain}"
    @app.call(env)
  end

  def custom_domain?(host)
    host !~ /#{@default_domain.sub(/^\./, '')}/i
  end
end

제목에있는 질문에 직접 답한 기존 답변이 없다고 생각해서 칩을 넣고 싶었습니다.

클라이언트 (브라우저)가 웹 사이트로 이동하면 웹 사이트는 클라이언트에게 쿠키를 설정하도록 지시합니다. 그렇게 할 때 쿠키 이름, 값, 도메인 및 경로를 지정합니다.

:domain => :all Rails에게 쿠키 도메인 (브라우저가 탐색 한 호스트) 앞에 점을 표시하여 쿠키가 모든 하위 도메인에 적용되도록합니다.

다음은 Rails 4.1 ( actionpack/lib/action_dispatch/middleware/cookies.rb) 의 관련 코드입니다 .

  def handle_options(options) #:nodoc:
    options[:path] ||= "/"

    if options[:domain] == :all
      # if there is a provided tld length then we use it otherwise default domain regexp
      domain_regexp = options[:tld_length] ? /([^.]+\.?){#{options[:tld_length]}}$/ : DOMAIN_REGEXP

      # if host is not ip and matches domain regexp
      # (ip confirms to domain regexp so we explicitly check for ip)
      options[:domain] = if (@host !~ /^[\d.]+$/) && (@host =~ domain_regexp)
        ".#{$&}"
      end
    elsif options[:domain].is_a? Array
      # if host matches one of the supplied domains without a dot in front of it
      options[:domain] = options[:domain].find {|domain| @host.include? domain.sub(/^\./, '') }
    end
  end

하위 도메인에 별도의 세션을 허용하는 것에 대한 질문의 두 번째 부분에 이미 답변하셨습니다.


tl; dr : @Nader 의 코드를 사용 합니다. 그러나 나는 그것을 내 안에 추가하고 conifg/environments/[production|development].rb내 점 접두사 도메인을 인수로 전달 해야한다는 것을 알았습니다 . 이것은 Rails 3.2.11에 있습니다.

쿠키 세션은 일반적으로 최상위 도메인에 대해서만 저장됩니다.

을 살펴보면 와에 Chrome -> Settings -> Show advanced settings… -> Privacy/Content settings… -> All cookies and site data… -> Search {yourdomain.com}대한 별도의 항목이 있음을 알 수 있습니다.sub1.yourdomain.comothersub.yourdomain.comyourdomain.com

문제는 모든 하위 도메인에서 동일한 세션 저장소 파일을 사용하는 것입니다.

Step 1: Use @Nader's CustomDomainCookie code

This is where Rack Middleware comes in. Some more relevant rack & rails resources:

Basically what this does is that it will map all of your cookie session data back onto the exact same cookie file that is equal to your root domain.

Step 2: Add To Rails Config

Now that you have a custom class in lib, make sure are autoloading it. If that meant nothing to you, look here: Rails 3 autoload

The first thing is to make sure that you are system-wide using a cookie store. In config/application.rb we tell Rails to use a cookie store.

# We use a cookie_store for session data
config.session_store :cookie_store,
                     :key => '_yourappsession',
                     :domain => :all

The reason this is here is mentioned here is because of the :domain => :all line. There are other people that have suggested to specify :domain => ".yourdomain.com" instead of :domain => :all. For some reason this did not work for me and I needed the custom Middleware class as described above.

Then in your config/environments/production.rb add:

config.middleware.use "CustomDomainCookie", ".yourdomain.com"

Note that the preceding dot is necessary. See "sub-domain cookies, sent in a parent domain request?" for why.

Then in your config/environments/development.rb add:

config.middleware.use "CustomDomainCookie", ".lvh.me"

The lvh.me trick maps onto localhost. It's awesome. See this Railscast about subdomains and this note for more info.

Hopefully that should do it. I honestly am not entirely sure why the process is this convoluted, as I feel cross subdomain sites are common. If anyone has any further insights into the reasons behind each of these steps, please enlighten us in the comments.


This option is used to make sure the application will be able to share sessions across subdomains. The :all option assumes that our application has a top-level domain size of 1. If not then we can specify a domain name instead and that will be used as the base domain for the session.


Hmmm,

I deploy an application that is hosted under www.xyz.com and under xyz.com.

For me, :domain => :all sets the domain for the session-cookie to xyz.com. So not for a top-level domain but for 1 level above the tld.

Jan Willem

ReferenceURL : https://stackoverflow.com/questions/4060333/what-does-rails-3-session-store-domain-all-really-do

반응형