Module CASServer::CAS
In: lib/casserver/cas.rb

Encapsulates CAS functionality. This module is meant to be included in the CASServer::Controllers module.

Methods

Included Modules

CASServer::Model

Public Instance methods

Strips CAS-related parameters from a service URL and normalizes it, removing trailing / and ?. Also converts any spaces to +.

For example, "google.com?ticket=12345" will be returned as "google.com". Also, "google.com/" would be returned as "google.com".

Note that only the first occurance of each CAS-related parameter is removed, so that "google.com?ticket=12345&ticket=abcd" would be returned as "google.com?ticket=abcd".

[Source]

     # File lib/casserver/cas.rb, line 297
297:   def clean_service_url(dirty_service)
298:     return dirty_service if dirty_service.blank?
299:     clean_service = dirty_service.dup
300:     ['service', 'ticket', 'gateway', 'renew'].each do |p|
301:       clean_service.sub!(Regexp.new("&?#{p}=[^&]*"), '')
302:     end
303: 
304:     clean_service.gsub!(/[\/\?&]$/, '') # remove trailing ?, /, or &
305:     clean_service.gsub!('?&', '?')
306:     clean_service.gsub!(' ', '+')
307: 
308:     $LOG.debug("Cleaned dirty service URL #{dirty_service.inspect} to #{clean_service.inspect}") if
309:       dirty_service != clean_service
310: 
311:     return clean_service
312:   end

[Source]

    # File lib/casserver/cas.rb, line 12
12:   def generate_login_ticket
13:     # 3.5 (login ticket)
14:     lt = LoginTicket.new
15:     lt.ticket = "LT-" + CASServer::Utils.random_string
16: 
17:     lt.client_hostname = @env['HTTP_X_FORWARDED_FOR'] || @env['REMOTE_HOST'] || @env['REMOTE_ADDR']
18:     lt.save!
19:     $LOG.debug("Generated login ticket '#{lt.ticket}' for client" +
20:       " at '#{lt.client_hostname}'")
21:     lt
22:   end

[Source]

     # File lib/casserver/cas.rb, line 74
 74:   def generate_proxy_granting_ticket(pgt_url, st)
 75:     uri = URI.parse(pgt_url)
 76:     https = Net::HTTP.new(uri.host,uri.port)
 77:     https.use_ssl = true
 78: 
 79:     # Here's what's going on here:
 80:     #
 81:     #   1. We generate a ProxyGrantingTicket (but don't store it in the database just yet)
 82:     #   2. Deposit the PGT and it's associated IOU at the proxy callback URL.
 83:     #   3. If the proxy callback URL responds with HTTP code 200, store the PGT and return it;
 84:     #      otherwise don't save it and return nothing.
 85:     #
 86:     https.start do |conn|
 87:       path = uri.path.empty? ? '/' : uri.path
 88:       path += '?' + uri.query unless (uri.query.nil? || uri.query.empty?)
 89:       
 90:       pgt = ProxyGrantingTicket.new
 91:       pgt.ticket = "PGT-" + CASServer::Utils.random_string(60)
 92:       pgt.iou = "PGTIOU-" + CASServer::Utils.random_string(57)
 93:       pgt.service_ticket_id = st.id
 94:       pgt.client_hostname = @env['HTTP_X_FORWARDED_FOR'] || @env['REMOTE_HOST'] || @env['REMOTE_ADDR']
 95: 
 96:       # FIXME: The CAS protocol spec says to use 'pgt' as the parameter, but in practice
 97:       #         the JA-SIG and Yale server implementations use pgtId. We'll go with the
 98:       #         in-practice standard.
 99:       path += (uri.query.nil? || uri.query.empty? ? '?' : '&') + "pgtId=#{pgt.ticket}&pgtIou=#{pgt.iou}"
100: 
101:       response = conn.request_get(path)
102:       # TODO: follow redirects... 2.5.4 says that redirects MAY be followed
103:       # NOTE: The following response codes are valid according to the JA-SIG implementation even without following redirects
104:       
105:       if %w(200 202 301 302 304).include?(response.code)
106:         # 3.4 (proxy-granting ticket IOU)
107:         pgt.save!
108:         $LOG.debug "PGT generated for pgt_url '#{pgt_url}': #{pgt.inspect}"
109:         pgt
110:       else
111:         $LOG.warn "PGT callback server responded with a bad result code '#{response.code}'. PGT will not be stored."
112:         nil
113:       end
114:     end
115:   end

[Source]

    # File lib/casserver/cas.rb, line 58
58:   def generate_proxy_ticket(target_service, pgt)
59:     # 3.2 (proxy ticket)
60:     pt = ProxyTicket.new
61:     pt.ticket = "PT-" + CASServer::Utils.random_string
62:     pt.service = target_service
63:     pt.username = pgt.service_ticket.username
64:     pt.granted_by_pgt_id = pgt.id
65:     pt.granted_by_tgt_id = pgt.service_ticket.granted_by_tgt.id
66:     pt.client_hostname = @env['HTTP_X_FORWARDED_FOR'] || @env['REMOTE_HOST'] || @env['REMOTE_ADDR']
67:     pt.save!
68:     $LOG.debug("Generated proxy ticket '#{pt.ticket}' for target service '#{pt.service}'" +
69:       " for user '#{pt.username}' at '#{pt.client_hostname}' using proxy-granting" +
70:       " ticket '#{pgt.ticket}'")
71:     pt
72:   end

[Source]

    # File lib/casserver/cas.rb, line 44
44:   def generate_service_ticket(service, username, tgt)
45:     # 3.1 (service ticket)
46:     st = ServiceTicket.new
47:     st.ticket = "ST-" + CASServer::Utils.random_string
48:     st.service = service
49:     st.username = username
50:     st.granted_by_tgt_id = tgt.id
51:     st.client_hostname = @env['HTTP_X_FORWARDED_FOR'] || @env['REMOTE_HOST'] || @env['REMOTE_ADDR']
52:     st.save!
53:     $LOG.debug("Generated service ticket '#{st.ticket}' for service '#{st.service}'" +
54:       " for user '#{st.username}' at '#{st.client_hostname}'")
55:     st
56:   end

Creates a TicketGrantingTicket for the given username. This is done when the user logs in for the first time to establish their SSO session (after their credentials have been validated).

The optional ‘extra_attributes’ parameter takes a hash of additional attributes that will be sent along with the username in the CAS response to subsequent validation requests from clients.

[Source]

    # File lib/casserver/cas.rb, line 30
30:   def generate_ticket_granting_ticket(username, extra_attributes = {})
31:     # 3.6 (ticket granting cookie/ticket)
32:     tgt = TicketGrantingTicket.new
33:     tgt.ticket = "TGC-" + CASServer::Utils.random_string
34:     tgt.username = username
35:     tgt.extra_attributes = extra_attributes
36:     tgt.client_hostname = @env['HTTP_X_FORWARDED_FOR'] || @env['REMOTE_HOST'] || @env['REMOTE_ADDR']
37:     tgt.save!
38:     $LOG.debug("Generated ticket granting ticket '#{tgt.ticket}' for user" +
39:       " '#{tgt.username}' at '#{tgt.client_hostname}'" +
40:       (extra_attributes.blank? ? "" : " with extra attributes #{extra_attributes.inspect}"))
41:     tgt
42:   end

Takes an existing ServiceTicket object (presumably pulled from the database) and sends a POST with logout information to the service that the ticket was generated for.

This makes possible the "single sign-out" functionality added in CAS 3.1. See www.ja-sig.org/wiki/display/CASUM/Single+Sign+Out

[Source]

     # File lib/casserver/cas.rb, line 242
242:   def send_logout_notification_for_service_ticket(st)
243:     uri = URI.parse(st.service)
244:     uri.path = '/' if uri.path.empty?
245:     time = Time.now
246:     rand = CASServer::Utils.random_string
247: 
248:     begin
249:       response = Net::HTTP.post_form(uri, {'logoutRequest' => URI.escape(%{<samlp:LogoutRequest ID="#{rand}" Version="2.0" IssueInstant="#{time.rfc2822}">
250:         <saml:NameID></saml:NameID>
251:         <samlp:SessionIndex>#{st.ticket}</samlp:SessionIndex>
252:         </samlp:LogoutRequest>})})
253:       if response.kind_of? Net::HTTPSuccess
254:         $LOG.info "Logout notification successfully posted to #{st.service.inspect}."
255:         return true
256:       else
257:         $LOG.error "Service #{st.service.inspect} responed to logout notification with code '#{response.code}'!"
258:         return false
259:       end
260:     rescue Exception => e
261:       $LOG.error "Failed to send logout notification to service #{st.service.inspect} due to #{e}"
262:       return false
263:     end
264:   end

[Source]

     # File lib/casserver/cas.rb, line 266
266:   def service_uri_with_ticket(service, st)
267:     raise ArgumentError, "Second argument must be a ServiceTicket!" unless st.kind_of? CASServer::Model::ServiceTicket
268: 
269:     # This will choke with a URI::InvalidURIError if service URI is not properly URI-escaped...
270:     # This exception is handled further upstream (i.e. in the controller).
271:     service_uri = URI.parse(service)
272: 
273:     if service.include? "?"
274:       if service_uri.query.empty?
275:         query_separator = ""
276:       else
277:         query_separator = "&"
278:       end
279:     else
280:       query_separator = "?"
281:     end
282: 
283:     service_with_ticket = service + query_separator + "ticket=" + st.ticket
284:     service_with_ticket
285:   end

[Source]

     # File lib/casserver/cas.rb, line 117
117:   def validate_login_ticket(ticket)
118:     $LOG.debug("Validating login ticket '#{ticket}'")
119: 
120:     success = false
121:     if ticket.nil?
122:       error = _("Your login request did not include a login ticket. There may be a problem with the authentication system.")
123:       $LOG.warn "Missing login ticket."
124:     elsif lt = LoginTicket.find_by_ticket(ticket)
125:       if lt.consumed?
126:         error = _("The login ticket you provided has already been used up. Please try logging in again.")
127:         $LOG.warn "Login ticket '#{ticket}' previously used up"
128:       elsif Time.now - lt.created_on < settings.config[:maximum_unused_login_ticket_lifetime]
129:         $LOG.info "Login ticket '#{ticket}' successfully validated"
130:       else
131:         error = _("You took too long to enter your credentials. Please try again.")
132:         $LOG.warn "Expired login ticket '#{ticket}'"
133:       end
134:     else
135:       error = _("The login ticket you provided is invalid. There may be a problem with the authentication system.")
136:       $LOG.warn "Invalid login ticket '#{ticket}'"
137:     end
138: 
139:     lt.consume! if lt
140: 
141:     error
142:   end

[Source]

     # File lib/casserver/cas.rb, line 217
217:   def validate_proxy_granting_ticket(ticket)
218:     if ticket.nil?
219:       error = Error.new(:INVALID_REQUEST, "pgt parameter was missing in the request.")
220:       $LOG.warn("#{error.code} - #{error.message}")
221:     elsif pgt = ProxyGrantingTicket.find_by_ticket(ticket)
222:       if pgt.service_ticket
223:         $LOG.info("Proxy granting ticket '#{ticket}' belonging to user '#{pgt.service_ticket.username}' successfully validated.")
224:       else
225:         error = Error.new(:INTERNAL_ERROR, "Proxy granting ticket '#{ticket}' is not associated with a service ticket.")
226:         $LOG.error("#{error.code} - #{error.message}")
227:       end
228:     else
229:       error = Error.new(:BAD_PGT, "Invalid proxy granting ticket '#{ticket}' (no matching ticket found in the database).")
230:       $LOG.warn("#{error.code} - #{error.message}")
231:     end
232: 
233:     [pgt, error]
234:   end

[Source]

     # File lib/casserver/cas.rb, line 202
202:   def validate_proxy_ticket(service, ticket)
203:     pt, error = validate_service_ticket(service, ticket, true)
204: 
205:     if pt.kind_of?(CASServer::Model::ProxyTicket) && !error
206:       if not pt.granted_by_pgt
207:         error = Error.new(:INTERNAL_ERROR, "Proxy ticket '#{pt}' belonging to user '#{pt.username}' is not associated with a proxy granting ticket.")
208:       elsif not pt.granted_by_pgt.service_ticket
209:         error = Error.new(:INTERNAL_ERROR, "Proxy granting ticket '#{pt.granted_by_pgt}'"+
210:           " (associated with proxy ticket '#{pt}' and belonging to user '#{pt.username}' is not associated with a service ticket.")
211:       end
212:     end
213: 
214:     [pt, error]
215:   end

[Source]

     # File lib/casserver/cas.rb, line 166
166:   def validate_service_ticket(service, ticket, allow_proxy_tickets = false)
167:     $LOG.debug "Validating service/proxy ticket '#{ticket}' for service '#{service}'"
168: 
169:     if service.nil? or ticket.nil?
170:       error = Error.new(:INVALID_REQUEST, "Ticket or service parameter was missing in the request.")
171:       $LOG.warn "#{error.code} - #{error.message}"
172:     elsif st = ServiceTicket.find_by_ticket(ticket)
173:       if st.consumed?
174:         error = Error.new(:INVALID_TICKET, "Ticket '#{ticket}' has already been used up.")
175:         $LOG.warn "#{error.code} - #{error.message}"
176:       elsif st.kind_of?(CASServer::Model::ProxyTicket) && !allow_proxy_tickets
177:         error = Error.new(:INVALID_TICKET, "Ticket '#{ticket}' is a proxy ticket, but only service tickets are allowed here.")
178:         $LOG.warn "#{error.code} - #{error.message}"
179:       elsif Time.now - st.created_on > settings.config[:maximum_unused_service_ticket_lifetime]
180:         error = Error.new(:INVALID_TICKET, "Ticket '#{ticket}' has expired.")
181:         $LOG.warn "Ticket '#{ticket}' has expired."
182:       elsif !st.matches_service? service
183:         error = Error.new(:INVALID_SERVICE, "The ticket '#{ticket}' belonging to user '#{st.username}' is valid,"+
184:           " but the requested service '#{service}' does not match the service '#{st.service}' associated with this ticket.")
185:         $LOG.warn "#{error.code} - #{error.message}"
186:       else
187:         $LOG.info("Ticket '#{ticket}' for service '#{service}' for user '#{st.username}' successfully validated.")
188:       end
189:     else
190:       error = Error.new(:INVALID_TICKET, "Ticket '#{ticket}' not recognized.")
191:       $LOG.warn("#{error.code} - #{error.message}")
192:     end
193: 
194:     if st
195:       st.consume!
196:     end
197: 
198: 
199:     [st, error]
200:   end

[Source]

     # File lib/casserver/cas.rb, line 144
144:   def validate_ticket_granting_ticket(ticket)
145:     $LOG.debug("Validating ticket granting ticket '#{ticket}'")
146: 
147:     if ticket.nil?
148:       error = "No ticket granting ticket given."
149:       $LOG.debug error
150:     elsif tgt = TicketGrantingTicket.find_by_ticket(ticket)
151:       if settings.config[:maximum_session_lifetime] && Time.now - tgt.created_on > settings.config[:maximum_session_lifetime]
152:         tgt.destroy
153:         error = "Your session has expired. Please log in again."
154:         $LOG.info "Ticket granting ticket '#{ticket}' for user '#{tgt.username}' expired."
155:       else
156:         $LOG.info "Ticket granting ticket '#{ticket}' for user '#{tgt.username}' successfully validated."
157:       end
158:     else
159:       error = "Invalid ticket granting ticket '#{ticket}' (no matching ticket found in the database)."
160:       $LOG.warn(error)
161:     end
162: 
163:     [tgt, error]
164:   end

[Validate]