Class: Ciam::Saml::Authrequest

Inherits:
Object
  • Object
show all
Defined in:
lib/ciam/ruby-saml/authrequest.rb

Constant Summary collapse

HTTP_POST =

a few symbols for SAML class names

"urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST"
HTTP_GET =
"urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(settings) ⇒ Authrequest

Returns a new instance of Authrequest.



19
20
21
22
# File 'lib/ciam/ruby-saml/authrequest.rb', line 19

def initialize( settings )
  @settings = settings
  @request_params = Hash.new
end

Instance Attribute Details

#issue_instantObject

Returns the value of attribute issue_instant.



17
18
19
# File 'lib/ciam/ruby-saml/authrequest.rb', line 17

def issue_instant
  @issue_instant
end

#requestObject

Returns the value of attribute request.



17
18
19
# File 'lib/ciam/ruby-saml/authrequest.rb', line 17

def request
  @request
end

#uuidObject

Returns the value of attribute uuid.



17
18
19
# File 'lib/ciam/ruby-saml/authrequest.rb', line 17

def uuid
  @uuid
end

Instance Method Details

#binding_selectObject

get the IdP metadata, and select the appropriate SSO binding that we can support. Currently this is HTTP-Redirect and HTTP-POST but more could be added in the future



132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
# File 'lib/ciam/ruby-saml/authrequest.rb', line 132

def binding_select
  # first check if we're still using the old hard coded method for 
  # backwards compatability
  if @settings. == nil && @settings.idp_sso_target_url != nil
    @URL = @settings.idp_sso_target_url
    return "GET", content_get
  end
  # grab the metadata
   = Metadata::new
  meta_doc = .(@settings)
  
  # first try POST
  sso_element = REXML::XPath.first(meta_doc,
    "/EntityDescriptor/IDPSSODescriptor/SingleSignOnService[@Binding='#{HTTP_POST}']")
  if sso_element 
    @URL = sso_element.attributes["Location"]
    #Logging.debug "binding_select: POST to #{@URL}"
    return "POST", content_post
  end
  
  # next try GET
  sso_element = REXML::XPath.first(meta_doc,
    "/EntityDescriptor/IDPSSODescriptor/SingleSignOnService[@Binding='#{HTTP_GET}']")
  if sso_element 
    @URL = sso_element.attributes["Location"]
    Logging.debug "binding_select: GET from #{@URL}"
    return "GET", content_get
  end
  # other types we might want to add in the future:  SOAP, Artifact
end

#content_getObject

construct the the parameter list on the URL and return



164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
# File 'lib/ciam/ruby-saml/authrequest.rb', line 164

def content_get
  # compress GET requests to try and stay under that 8KB request limit
  deflated_request  = Zlib::Deflate.deflate(@request, 9)[2..-5]
  # strict_encode64() isn't available?  sub out the newlines
  @request_params["SAMLRequest"] = Base64.encode64(deflated_request).gsub(/\n/, "")
  
  Logging.debug "SAMLRequest=#{@request_params["SAMLRequest"]}"
  uri = Addressable::URI.parse(@URL)
  if uri.query_values == nil
    uri.query_values = @request_params
  else
    # solution to stevenwilkin's parameter merge
    uri.query_values = @request_params.merge(uri.query_values)
  end
  url = uri.to_s
  #Logging.debug "Sending to URL #{url}"
  return url
end

#content_postObject

construct an HTML form (POST) and return the content



183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
# File 'lib/ciam/ruby-saml/authrequest.rb', line 183

def content_post
  # POST requests seem to bomb out when they're deflated
  # and they probably don't need to be compressed anyway
  @request_params["SAMLRequest"] = Base64.encode64(@request).gsub(/\n/, "")
  
  #Logging.debug "SAMLRequest=#{@request_params["SAMLRequest"]}"
  # kind of a cheesy method of building an HTML, form since we can't rely on Rails too much,
  # and REXML doesn't work well with quote characters
  str = "<html><body onLoad=\"document.getElementById('form').submit();\">\n"
  str += "<form id='form' name='form' method='POST' action=\"#{@URL}\">\n"
  # we could change this in the future to associate a temp auth session ID
  str += "<input name='RelayState' value='ruby-saml' type='hidden' />\n"
  @request_params.each_pair do |key, value|
    str += "<input name=\"#{key}\" value=\"#{value}\" type='hidden' />\n"
    #str += "<input name=\"#{key}\" value=\"#{CGI.escape(value)}\" type='hidden' />\n"
  end
  str += "</form></body></html>\n"
  
  #Logging.debug "Created form:\n#{str}"
  return str
end

#create(params = {}) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
# File 'lib/ciam/ruby-saml/authrequest.rb', line 24

def create(params = {})
  uuid = "_" + UUID.new.generate
  self.uuid = uuid
  time = Time.now.utc.strftime("%Y-%m-%dT%H:%M:%SZ")
  self.issue_instant = time
  # Create AuthnRequest root element using REXML 
  request_doc = Ciam::XMLSecurityNew::Document.new
  request_doc.context[:attribute_quote] = :quote
  root = request_doc.add_element "samlp:AuthnRequest", { "xmlns:samlp" => "urn:oasis:names:tc:SAML:2.0:protocol", 
                                                          "xmlns:saml" => "urn:oasis:names:tc:SAML:2.0:assertion"
                                                         }
  root.attributes['ID'] = uuid
  root.attributes['IssueInstant'] = time
  root.attributes['Version'] = "2.0"
  #root.attributes['ProtocolBinding'] = "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST"
  root.attributes['AttributeConsumingServiceIndex'] = @settings.assertion_consumer_service_index
  #root.attributes['IsPassive'] = "false"
  #usato AssertionConsumerServiceURL e ProtocolBinding in alternativa, pag 8 regole tecniche
  root.attributes['AssertionConsumerServiceIndex'] = @settings.attribute_consuming_service_index

  #Tolto, utilizzo AssertionConsumerServiceIndex
  # # Conditionally defined elements based on settings
  # if @settings.assertion_consumer_service_url != nil
  #   root.attributes["AssertionConsumerServiceURL"] = @settings.assertion_consumer_service_url
  # end

  if @settings.destination_service_url != nil
    root.attributes["Destination"] = @settings.destination_service_url
  end

  unless @settings.issuer.blank?
    issuer = root.add_element "saml:Issuer"
    issuer.attributes['NameQualifier'] =  @settings.issuer #non metto @settings.sp_name_qualifier, questo valore deve essere uguale al 
    #entityID dei metadata che usa @settings.issuer
    issuer.attributes['Format'] =  "urn:oasis:names:tc:SAML:2.0:nameid-format:entity"
    issuer.text = @settings.issuer
  end

  #opzionale
  unless @settings.sp_name_qualifier.blank?
    subject = root.add_element "saml:Subject"
    name_id = subject.add_element "saml:NameID"
    name_id.attributes['Format'] = "urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified"
    name_id.attributes['NameQualifier'] = @settings.sp_name_qualifier
    name_id.text = @settings.sp_name_identifier
  end



  if @settings.name_identifier_format != nil
    root.add_element "samlp:NameIDPolicy", { 
        # Might want to make AllowCreate a setting?
        #{}"AllowCreate"     => "true",
        "Format"          => @settings.name_identifier_format[0]
    }
  end

  # BUG fix here -- if an authn_context is defined, add the tags with an "exact"
  # match required for authentication to succeed.  If this is not defined, 
  # the IdP will choose default rules for authentication.  (Shibboleth IdP)
  if @settings.authn_context != nil
    requested_context = root.add_element "samlp:RequestedAuthnContext", { 
      "Comparison" => "exact"
    }
    context_class = []
    @settings.authn_context.each_with_index{ |context, index|
      context_class[index] = requested_context.add_element "saml:AuthnContextClassRef"
      context_class[index].text = context
    }
    
  end

  if @settings.requester_identificator != nil
    requester_identificator = root.add_element "samlp:Scoping", { 
      "ProxyCount" => "0"
    }
    identificators = []
    @settings.requester_identificator.each_with_index{ |requester, index|
      identificators[index] = requester_identificator.add_element "samlp:RequesterID"
      identificators[index].text = requester
    }
    
  end

  request_doc << REXML::XMLDecl.new("1.0", "UTF-8")
  
  #LA FIRMA VA MESSA SOLO NEL CASO CON HTTP POST
  cert = @settings.get_cert(@settings.sp_cert)
  # embed signature
  if @settings. && @settings.sp_private_key && @settings.sp_cert
    private_key = @settings.get_sp_key
    request_doc.sign_document(private_key, cert)
  end

  # stampo come stringa semplice i metadata per non avere problemi con validazione firma
  #ret = request_doc.to_s

  @request = request_doc.to_s

  #Logging.debug "Created AuthnRequest: #{@request}"

  return self

end