Thin,Sinatra和拦截静态文件请求进行CAS身份验证

时间:2010-04-23 16:02:27

标签: ruby sinatra rack cas

我正在使用casrack-the-authenticator gem进行CAS身份验证。我的服务器在Sinatra上运行Thin。我已经获得了CAS身份验证位,但我不确定如何告诉Rack拦截“/index.html”请求以确认CAS登录,如果不允许用户查看该页面,则返回HTTP 403响应而不是提供实际页面。有任何人对此有经验吗?感谢。

我的应用:

class Foo < Sinatra::Base
    enable :sessions
    set :public, "public"
    use CasrackTheAuthenticator::Simple, :cas_server => "https://my.cas_server.com"
    use CasrackTheAuthenticator::RequireCAS

    get '/' do
        puts "Hello World"
    end
end

我的机架文件:

require 'foo'

use Rack::CommonLogger
use Rack::Lint

run Foo

最初尝试让Rack了解其文件服务中的身份验证(欢迎提出意见和建议):

builder = Rack::Builder.new do
    map '/foo/index.html' do
        run Proc.new { |env|
            user = Rack::Request.new(env).session[CasrackTheAuthenticator::USERNAME_PARAM]
            [401, { "Content-Type" => "text/html" }, "CAS Authentication Required"] unless user
            # Serve index.html because we detected user
         }
    end

    map '/foo' do
        run Foo
    end
end

run builder

1 个答案:

答案 0 :(得分:2)

Casrack-the-Authenticator会将CAS信息放入Rack会话中。您可以在另一个Rack中间件或Sinatra应用程序中将其拉出来。

以下是针对Rails应用程序,但Sinatra或Rack中间件的概念类似:

# in app/controllers/application_controller.rb:
protected

def require_sign_in!
  render :nothing => true, :status => 403 unless signed_in?
end

def signed_in?
  current_user.present?
end

def current_user
  @current_user ||= Person.find_by_username(session[CasrackTheAuthenticator::USERNAME_PARAM])
end
相关问题