<img src=“https://secure.travis-ci.org/rubycas/rubycas-client.png” alt=“Build Status” /> <img src=“https://codeclimate.com/badge.png” />
- Authors
-
Matt Zukowski <matt AT roughest DOT net> and Matt Campbell <matt AT soupmatt DOT com>; inspired by code by Ola Bini <ola.bini AT ki DOT se> and Matt Walker <mwalker AT tamu DOT edu>
- Copyright
-
Portions contributed by Matt Zukowski are copyright © 2009 Urbacon Ltd. Portions contributed by Matt Campbell, Rich Yarger and Rahul Joshi are copyright © 2011 Vibes Media LLC. Other portions are copyright of their respective authors.
- License
-
MIT License
- Websites
-
github.com/rubycas/rubycas-client github.com/rubycas/rubycas-client/wiki rubydoc.info/github/rubycas/rubycas-client/master/frames
RubyCAS-Client is a Ruby client library for Yale’s Central Authentication Service (CAS) protocol.¶ ↑
CAS provides a secure single sign on solution for web-based applications. The user logs in to your organization’s CAS server, and is automatically authenticated for all other CAS-enabled applications.
For general information about the open CAS protocol, please have a look at www.ja-sig.org/products/cas.
If your organization does not already have a CAS server, you may be interested in RubyCAS-Client’s sister project, RubyCAS-Server.
The RubyCAS-Client package includes adapters for Rails and Merb, although the client library itself can be adapted for other frameworks (for example an implementation for Camping is available via the Picnic library).
If you need help, try posting to the RubyCAS discussion group at groups.google.com/group/rubycas-server.
To report problems, please use the Google Code issue tracker at code.google.com/p/rubycas-client/issues/list.
API documentation (i.e. the RDocs) are available at rubycas-client.rubyforge.org
The current version of RubyCAS-Client should work with Rails 2.3.6 and up. For compatibility with older Rails try using an older version of the client.
You can download the latest version of RubyCAS-Client from the project’s rubyforge page at rubyforge.org/projects/rubycas-client.
However, if you’re using Rails, it’s easier to install the CAS client as a plugin:
cd <your rails app> ./script/plugin install git://github.com/rubycas/rubycas-client.git
Alternatively, the library is also installable as a RubyGem:
gem install rubycas-client
If your Rails application is under Subversion control, you can also install the plugin as an svn:external, ensuring that you always have the latest bleeding-edge version of RubyCAS-Client:
./script/plugin install -x http://svn.github.com/rubycas/rubycas-client.git
If you’d rather jump right in, have a look at the example Rails and Merb applications pre-configured for CAS authentication:
github.com/rubycas/rubycas-client/tree/master/examples
Otherwise, continue reading for a step-by-step guide for integrating RubyCAS-Client with Rails:
Note that from this point on we are assuming that you have a working CAS server up and running!
After installing RubyCAS-Client as a plugin (see above), add the following to your app’s config/environment.rb
(make sure that you put it at the bottom of the file, after the Rails Initializer):
CASClient::Frameworks::Rails::Filter.configure( :cas_base_url => "https://cas.example.foo/" )
(Change the :cas_base_url
value to your CAS server’s base URL; also note that many CAS servers are configured with a base URL that looks more like “cas.example.foo/cas”.)
Then, in your app/controllers/application.rb
(or in whichever controller you want to add the CAS filter for):
before_filter CASClient::Frameworks::Rails::Filter
That’s it. You should now find that you are redirected to your CAS login page whenever you try to access any action in your protected controller. You can of course qualify the before_filter
as you would with any other ActionController filter. For example:
before_filter CASClient::Frameworks::Rails::Filter, :except => [ :unprotected_action, :another_unprotected_action ]
Once the user has been authenticated, their authenticated username is available under session[:cas_user]
, If you want to do something with this username (for example load a user record from the database), you can append another filter method that checks for this value and does whatever you need it to do.
Note: If Rails complains about missing constants, try adding this before the CASClient configuration:
require 'casclient' require 'casclient/frameworks/rails/filter'
Here is a more complicated configuration showing most of the configuration options along with their default values (this does not show proxy options, which are covered in the next section):
# enable detailed CAS logging cas_logger = CASClient::Logger.new(::Rails.root+'/log/cas.log') cas_logger.level = Logger::DEBUG CASClient::Frameworks::Rails::Filter.configure( :cas_base_url => "https://cas.example.foo/", :login_url => "https://cas.example.foo/login", :logout_url => "https://cas.example.foo/logout", :validate_url => "https://cas.example.foo/proxyValidate", :username_session_key => :cas_user, :extra_attributes_session_key => :cas_extra_attributes, :logger => cas_logger, :enable_single_sign_out => true )
Note that normally it is not necessary to specify :login_url
, :logout_url
, and :validate_url
. These values are automatically set to standard CAS defaults based on the given :cas_base_url
.
The :username_session_key
value determines the key under which you can find the CAS username in the Rails session hash.
Any additional info that the CAS server might have supplied about the user during authentication will be found under the :extra_attributes_session_key
value in the Rails session hash (i.e. given the above configuration, you would find this info under session[:cas_extra_attributes]
).
An arbitrary Logger instance can be given as the :logger parameter. In the example above we log all CAS activity to a log/cas.log
file in your Rails app’s directory.
By default, the Rails filter will only authenticate with the CAS server when no session value exists. Once the user has been authenticated, no further CAS forwarding is done until the user’s session is wiped. This saves you the trouble of having to do this check yourself (since in most cases it is not advisable to go through the CAS server on every request – this is slow and would potentially lead to problems, for example for AJAX requests). However, the disadvantage is that the filter no longer checks to make sure that the user’s CAS session is still actually open. In other words it is possible for the user’s authentication session to be closed on the CAS server without the client application knowing about it.
To address this, RubyCAS-Client now supports the new “Single Sign-Out” functionality in CAS 3.1, allowing the server to notify the client application that the CAS session is closed. The client will automatically intercept Single Sign-Out requsts from the CAS server, but in order for this to work you must configure your Rails application as follows:
-
The Rails session store must be set to ActiveRecord:
config.action_controller.session_store = :active_record_store
-
The server must be able to read and write to Rails.root/tmp/sessions. If you are in a clustered environment, the contents of this directory must be shared between all server instances.
-
Cross-site request forgery protection must be disabled. In your
application.rb
:self.allow_forgery_protection = false
. (Or rather you may want to disable forgery protection only for actions that are behind the CAS filter.) -
Finally, you must add
:enable_single_sign_out => true
to your CAS client config (a similar option must be enabled on the CAS server, if you’re using RubyCAS-Server).
The best way to debug single-sign out functionality is to configure your CAS client with logging (see above) and then watch the log to ensure that single-sign out requests from the server are being processed correctly.
Alternatively, it is possible to disable authentication persistence in the client by setting the :authenticate_on_every_request
configuration option to true as, in the example in the previous section. However, this is not recommended as it will almost certainly have a deleterious impact on performance and can interfere with certain HTTP transactions (AJAX requests, for example).
Your Rails application’s controller(s) will probably have some sort of logout function. Here you can do any necessary local cleanup, and then call CASClient::Frameworks::Rails::Filter.logout(controller)
. For example:
class ApplicationController < ActionController::Base # ... def logout # optionally do some local cleanup here # ... CASClient::Frameworks::Rails::Filter.logout(self) end end
By default, the logout method will clear the local Rails session, do some local CAS cleanup, and redirect to the CAS logout page. Additionally, the request.referer
value from the controller
instance is passed to the CAS server as a ‘destination’ parameter. This allows RubyCAS server to provide a follow-up login page allowing the user to log back in to the service they just logged out from using a different username and password. Other CAS server implemenations may use this ‘destination’ parameter in different ways.
“Gatewaying” essentially allows for optional CAS authentication. Users who already have a pre-existing CAS SSO session will be automatically authenticated for the gatewayed service, while those who do not will be allowed to access the service without authentication. This is useful for example when you want to show some additional private content on a homepage to authenticated users, but also want anonymous users to be able to access the page without first logging in.
To allow users to access a page without authenticatin, simply use CASClient::Frameworks::Rails::GatewayFilter
in place of CASClient::Frameworks::Rails::Filter
in your controller. For example, you may want to require CAS authentication for all actions in a controller except the index action:
class ExampleController < ApplicationController before_filter CASClient::Frameworks::Rails::GatewayFilter, :only => :index before_filter CASClient::Frameworks::Rails::Filter, :except => :index # ... end
To provide a login URL for unauthenticated users:
<%= link_to("Login", CASClient::Frameworks::Rails::Filter.login_url(controller)) %>
CAS 2.0 has a built-in mechanism that allows a CAS-authenticated application to pass on its authentication to other applications. An example where this is useful might be a portal site, where the user logs in to a central website and then gets forwarded to various other sites that run independently of the portal system (but are always accessed via the portal). The exact mechanism behind this is rather complicated so I won’t go over it here. If you wish to learn more about CAS proxying, a great walkthrough is available at www.ja-sig.org/wiki/display/CAS/Proxy+CAS+Walkthrough.
RubyCAS-Client fully supports proxying, so a CAS-protected Rails application can act as a CAS proxy.
Additionally, RubyCAS-Client comes with a controller that can act as a CAS proxy callback receiver. This is necessary because when your application requests to act as a CAS proxy, the CAS server must contact your application to deposit the proxy-granting-ticket (PGT). Note that in this case the CAS server CONTACTS YOU, rather than you contacting the CAS server (as in all other CAS operations).
Confused? Don’t worry, you don’t really have to understand this to use it. To enable your Rails app to act as a CAS proxy, all you need to do is this:
In your config/environment.rb
:
# enable detailed CAS logging for easier troubleshooting cas_logger = CASClient::Logger.new(::Rails.root+'/log/cas.log') cas_logger.level = Logger::DEBUG CASClient::Frameworks::Rails::Filter.configure( :cas_base_url => "https://cas.example.foo/", :proxy_callback_url => "https://cas-proxy-callback.example.foo/cas_proxy_callback/receive_pgt", :logger => cas_logger )
In config/routes.rb
make sure that you have a route that will allow requests to /cas_proxy_callback/:action to be routed to the CasProxyCallbackController. This should work as-is with the standard Rails routes setup, but if you have disabled the default route, you should add the following:
map.cas_proxy_callback 'cas_proxy_callback/:action', :controller => 'cas_proxy_callback'
Now here’s a big giant caveat: your CAS callback application and your CAS proxy application must run on separate Rails servers. In other words, if you want a Rails app to act as a CAS ticket-granting proxy, the cas_proxy_callback controller must run on a different server. This is because Rails does not properly support handling of concurrent requests. The CAS proxy mechanism acts in such a way that if your proxy application and your callback controller were on the same server you would end up with a deadlock (the CAS server would be waiting for its callback to be accepted by your Rails server, but your Rails server wouldn’t respond to the CAS server’s callback until the CAS server responded back first).
The simplest workaround is this:
Run rails using a server that handles multiple concurrent requests. In development, you can use Phusion Passenger Standalone, POW (pow.cx/), unicorn and many others. In production, I imagine you already support multiple concurrent requests.
That’s it. The proxy_callback_controller doesn’t require any additional configuration. It doesn’t access the database or anything of that sort.
Once your user logs in to CAS via your application, you can do the following to obtain a service ticket that can then be used to authenticate another application:
service_uri = "http://some-other-application.example.foo" proxy_granting_ticket = session[:cas_pgt] proxy_ticket = CASClient::Frameworks::Rails::Filter.client.request_proxy_ticket(proxy_granting_ticket, service_uri)
proxy_ticket
should now contain a valid proxy ticket. You can use it to authenticate other services by sending it together with the service URI as parameters to your target application:
http://some-other-application.example.foo?service=#{CGI::escape(proxy_ticket.service)}&ticket=#{proxy_ticket.ticket}
This is of course assuming that some-other-application.example.foo is also protected by the CAS filter. Note that you should always URI-encode your service parameter inside URIs!
Note that #request_proxy_ticket returns a CASClient::ProxyTicket object, which is why we need to call #ticket on it to retrieve the actual service ticket string.
The proxy url must be an https address. Otherwise CAS will refuse to communicate with it. This means that if you are using the bundled cas_proxy_callback controller, you will have to host your application on an https-enabled server. This can be a bit tricky with Rails. WEBrick’s SSL support is difficult to configure, and Mongrel doesn’t support SSL at all. One workaround is to use a reverse proxy like Pound, which will accept https connections and locally re-route them to your Rails application. Also, note that self-signed SSL certificates likely won’t work. You will probably need to use a real certificate purchased from a trusted CA authority (there are ways around this, but good luck :)
Make sure you have the Ruby OpenSSL library installed. Otherwise you may get errors like:
no such file to load -- net/https
To install the library on an Debian/Ubuntu system:
sudo apt-get install libopenssl-ruby
For other platforms you’ll have to figure it out yourself.
In some cases, especially those using Cucumber or other tools that simply can’t work with CAS, it may be necessary to work around CAS instead.
In your test or Cucumber step definition, simply fake out CAS.
CASClient::Frameworks::Rails::Filter.fake("homer")
This functionality was present in the original version of this plugin. The value of the username is stored in session (or the user specified field) and session for backwards-compatibility.
If you need to fake out extra attributes, you can do so like this:
CASClient::Frameworks::Rails::Filter.fake("homer", {:role => "user", :email => "homer@test.foo"})
And the extra attributes will get put in the proper place in the session.
RubyCAS-Client is licensed for use under the terms of the MIT License. See the LICENSE.txt file bundled with the official RubyCAS-Client distribution for details.