开发者

Rails - getting remote_user to return username from apache

I've looked around quite a bit and did find some information on the topic but couldn't get it to work. I have apache/tomcat installed on my webserver within my company. Previously on the same webserver when I was writing 开发者_如何学编程CGI applications I was successfully able to get the username of visitors on my site by access the environment var REMOTE_USER. Now that I'm riding on rails, the variable, request.env['REMOTE_USER'] returns nothing.

Please note that I am not running Mongrel which many of the online discussions assume. Also, i'm not looking to build an authentication system, I'm just looking to read in (using REMOTE_USER) the username of the people who access my site.

I'm aware that I would need to tweak my .htaccess (located in my public folder) file to forward this information from apache into my application. By looking at examples on the web, I did change it to..

RewriteCond %{REMOTE_USER} (.+)
RewriteRule ^.*$ - [E=RU:%1]
RequestHeader add X-Forwarded-User %{RU}e

..but this didn't help. Thanks.


If you add X-Forwarded-User, you have to read request.headers['X-Forwarded-User'] and not request.env['REMOTE_USER'].

Put this in the below file and use http_remote_user instead of the request.env hash.

# app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
  def http_remote_user
    request.env['HTTP_REMOTE_USER'] || request.headers['X-Forwarded-User']
  end
  helper_method :http_remote_user
end


I struggled with this, but did finally get it working.

  1. Make sure you remember to add RewriteEngine On into the conf file (for me it was inside the VirtualHost section), I forgot and it silently failed, no errors when restarting apache.

  2. Depending on whether you use a .htaccess or a .conf file, you need to change the the RewriteCond rule. The esoteric details - note 5 means we need to use RewriteCond %{LA-U:REMOTE_USER} (.+) if we are inside a conf file.

  3. To help debugging, you can always start by using RequestHeader add X-Forwarded-User 'FixedValue' to make sure the problems are apache not rails or other intermediates.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜