SAML Authentication in Rails

openssl req -nodes -x509 -newkey rsa:2048 -keyout private-key.pem -out cert.pem -sha256 -days 365
certificate and private key generation using OpenSSL
SamlIdp::Fingerprint.certificate_digest(x509_cert, :sha512)
class SamlController < ApplicationController
skip_before_action :verify_authenticity_token, only: [:consume]
def init
request = OneLogin::RubySaml::Authrequest.new
redirect_to(request.create(saml_settings, email: "sivagollapalli88@gmail.com"))
end
def consume
response = OneLogin::RubySaml::Response.new(params[:SAMLResponse], settings: saml_settings)
# We validate the SAML Response and check if the user already exists in the system
if response.is_valid?
# authorize_success, log the user
session[:userid] = response.nameid
session[:attributes] = response.attributes
render plain: "Successfully authenticated...."
else
authorize_failure # This method shows an error message
# List of errors is available in response.errors array
end
end
def saml_settings
idp_metadata_parser = OneLogin::RubySaml::IdpMetadataParser.new
settings = idp_metadata_parser.parse_remote("http://localhost:3000/saml/metadata")
settings.assertion_consumer_service_url = "http://localhost:4000/saml/consume"
settings.sp_entity_id = "http://localhost:4000"
settings.private_key = File.read("#{Rails.root}/private-key.pem")
#settings.name_identifier_format = "urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress"
# Optional for most SAML IdPs
#settings.authn_context = "urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport"
settings
end
end
config.name_id.formats = {
email_address: -> (principal) { principal.email },
transient: -> (principal) { principal.id },
persistent: -> (p) { p.id },
}
@saml_response = encode_response user, encryption: {
cert: saml_request.service_provider.cert,
block_encryption: 'aes256-cbc',
key_transport: 'rsa-oaep-mgf1p'
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store