working on it ...

Filters

Explore Public Snippets

Sort by

Found 188 snippets matching: saml

    public by tciss modified Jan 23, 2018  1210  1  5  0

    Create SAML2 Assertion

    //-----------------------------------------------------------------------
    // <copyright file="SAML20Assertion.cs" company="CoverMyMeds">
    //  Copyright (c) 2012 CoverMyMeds.  All rights reserved.
    //  This code is presented as reference material only.
    // </copyright>
    //-----------------------------------------------------------------------
    
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Xml;
    using System.Xml.Serialization;
    using System.Security.Cryptography.X509Certificates;
    using System.Security.Cryptography.Xml;
    using System.IO;
    using CoverMyMeds.SAML.Library.Schema;
    
    namespace CoverMyMeds.SAML.Library {
    
        /// <summary>
        /// Encapsulate functionality for building a SAML Response using the Schema object
        ///     created by xsd.exe from the OASIS spec
        /// </summary>
        /// <remarks>Lots of guidance from this CodeProject implementation
        ///     http://www.codeproject.com/Articles/56640/Performing-a-SAML-Post-with-C#xx0xx
        /// </remarks>
        public class SAML20Assertion {
    
            /// <summary>
            /// Build a signed XML SAML Response string to be inlcuded in an HTML Form
            /// for POSTing to a SAML Service Provider
            /// </summary>
            /// <param name="Issuer">Identity Provider - Used to match the certificate for verifying 
            ///     Response signing</param>
            /// <param name="AssertionExpirationMinutes">Assertion lifetime</param>
            /// <param name="Audience"></param>
            /// <param name="Subject"></param>
            /// <param name="Recipient"></param>
            /// <param name="Attributes">Dictionary of attributes to send through for user SSO</param>
            /// <param name="SigningCert">X509 Certificate used to sign Assertion</param>
            /// <returns></returns>
            public static string CreateSAML20Response(string Issuer, int AssertionExpirationMinutes, string Audience, string Subject, string Recipient, Dictionary<string, string> Attributes, X509Certificate2 SigningCert) {
                // Create SAML Response object with a unique ID and correct version
                ResponseType response = new ResponseType() {ID = "_" + System.Guid.NewGuid().ToString(), Version = "2.0", IssueInstant = System.DateTime.UtcNow, Destination = Recipient.Trim(), Issuer = new NameIDType() {Value = Issuer.Trim()}, Status = new StatusType() {StatusCode = new StatusCodeType() {Value = "urn:oasis:names:tc:SAML:2.0:status:Success"}}};
    
                // Put SAML 2.0 Assertion in Response
                response.Items = new AssertionType[] {CreateSAML20Assertion(Issuer, AssertionExpirationMinutes, Audience, Subject, Recipient, Attributes)};
    
                XmlDocument XMLResponse = SerializeAndSignSAMLResponse(response, SigningCert);
    
                return System.Convert.ToBase64String(Encoding.UTF8.GetBytes(XMLResponse.OuterXml));
            }
    
            /// <summary>
            /// Accepts SAML Response, serializes it to XML and signs using the supplied certificate
            /// </summary>
            /// <param name="Response">SAML 2.0 Response</param>
            /// <param name="SigningCert">X509 certificate</param>
            /// <returns>XML Document with computed signature</returns>
            private static XmlDocument SerializeAndSignSAMLResponse(ResponseType Response, X509Certificate2 SigningCert) {
                // Set serializer and writers for action
                XmlSerializer responseSerializer = new XmlSerializer(Response.GetType());
                StringWriter stringWriter = new StringWriter();
                XmlWriter responseWriter = XmlTextWriter.Create(stringWriter, new XmlWriterSettings() {OmitXmlDeclaration = true, Indent = true, Encoding = Encoding.UTF8});
                responseSerializer.Serialize(responseWriter, Response);
                responseWriter.Close();
                XmlDocument xmlResponse = new XmlDocument();
                xmlResponse.LoadXml(stringWriter.ToString());
    
                // Set the namespace for prettire and more consistent XML
                XmlNamespaceManager ns = new XmlNamespaceManager(xmlResponse.NameTable);
                ns.AddNamespace("saml", "urn:oasis:names:tc:SAML:2.0:assertion");
    
                CertificateUtility.AppendSignatureToXMLDocument(ref xmlResponse, "#" + ((AssertionType) Response.Items[0]).ID, SigningCert);
    
                return xmlResponse;
            }
    
            /// <summary>
            /// Creates a SAML 2.0 Assertion Segment for a Response
            /// Simple implmenetation assuming a list of string key and value pairs
            /// </summary>
            /// <param name="Issuer"></param>
            /// <param name="AssertionExpirationMinutes"></param>
            /// <param name="Audience"></param>
            /// <param name="Subject"></param>
            /// <param name="Recipient"></param>
            /// <param name="Attributes">Dictionary of string key, string value pairs</param>
            /// <returns>Assertion to sign and include in Response</returns>
            private static AssertionType CreateSAML20Assertion(string Issuer, int AssertionExpirationMinutes, string Audience, string Subject, string Recipient, Dictionary<string, string> Attributes) {
                AssertionType NewAssertion = new AssertionType() {Version = "2.0", IssueInstant = System.DateTime.UtcNow, ID = "_" + System.Guid.NewGuid().ToString()};
    
                // Create Issuer
                NewAssertion.Issuer = new NameIDType() {Value = Issuer.Trim()};
    
                // Create Assertion Subject
                SubjectType subject = new SubjectType();
                NameIDType subjectNameIdentifier = new NameIDType() {Value = Subject.Trim(), Format = "urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified"};
                SubjectConfirmationType subjectConfirmation = new SubjectConfirmationType() {Method = "urn:oasis:names:tc:SAML:2.0:cm:bearer", SubjectConfirmationData = new SubjectConfirmationDataType() {NotOnOrAfter = DateTime.UtcNow.AddMinutes(AssertionExpirationMinutes), Recipient = Recipient}};
                subject.Items = new object[] {subjectNameIdentifier, subjectConfirmation};
                NewAssertion.Subject = subject;
    
                // Create Assertion Conditions
                ConditionsType conditions = new ConditionsType();
                conditions.NotBefore = DateTime.UtcNow;
                conditions.NotBeforeSpecified = true;
                conditions.NotOnOrAfter = DateTime.UtcNow.AddMinutes(AssertionExpirationMinutes);
                conditions.NotOnOrAfterSpecified = true;
                conditions.Items = new ConditionAbstractType[] {new AudienceRestrictionType() {Audience = new string[] {Audience.Trim()}}};
                NewAssertion.Conditions = conditions;
    
                // Add AuthnStatement and Attributes as Items
                AuthnStatementType authStatement = new AuthnStatementType() {AuthnInstant = DateTime.UtcNow, SessionIndex = NewAssertion.ID};
                AuthnContextType context = new AuthnContextType();
                context.ItemsElementName = new ItemsChoiceType5[] {ItemsChoiceType5.AuthnContextClassRef};
                context.Items = new object[] {"urn:oasis:names:tc:SAML:2.0:ac:classes:unspecified"};
                authStatement.AuthnContext = context;
    
                AttributeStatementType attributeStatement = new AttributeStatementType();
                attributeStatement.Items = new AttributeType[Attributes.Count];
                int i = 0;
                foreach (KeyValuePair<string, string> attribute in Attributes) {
                    attributeStatement.Items[i] = new AttributeType() {Name = attribute.Key, AttributeValue = new object[] {attribute.Value}, NameFormat = "urn:oasis:names:tc:SAML:2.0:attrname-format:basic"};
                    i++;
                }
    
                NewAssertion.Items = new StatementAbstractType[] {authStatement, attributeStatement};
    
                return NewAssertion;
            }
    
        }
    
    }

    public by msdn modified Jan 12, 2015  1483  2  6  0

    GetSamlAssertionSignedWithCertificate: Creates a SAML assertion signed with the given certificate.

    Creates a SAML assertion signed with the given certificate.
    using System;
    using System.Globalization;
    using System.Security.Cryptography.X509Certificates;
    using System.ServiceModel;
    using ACS.Management;
    using Microsoft.IdentityModel.Claims;
    using Microsoft.IdentityModel.Protocols.WSTrust;
    using Microsoft.IdentityModel.SecurityTokenService;
    using Microsoft.IdentityModel.Tokens.Saml2;
    
    /// <summary>
    /// Creates a SAML assertion signed with the given certificate.
    /// </summary>
    public static Saml2SecurityToken GetSamlAssertionSignedWithCertificate(String nameIdentifierClaim, byte[] certificateWithPrivateKeyRawBytes, string password)
    {
        string acsUrl = string.Format(CultureInfo.InvariantCulture, "https://{0}.{1}", SamplesConfiguration.ServiceNamespace, SamplesConfiguration.AcsHostUrl);
    
        Saml2Assertion assertion = new Saml2Assertion(new Saml2NameIdentifier(nameIdentifierClaim));
    
        Saml2Conditions conditions = new Saml2Conditions();
        conditions.NotBefore = DateTime.UtcNow;
        conditions.NotOnOrAfter = DateTime.MaxValue;
        conditions.AudienceRestrictions.Add(new Saml2AudienceRestriction(new Uri(acsUrl, UriKind.RelativeOrAbsolute)));
        assertion.Conditions = conditions;
    
        Saml2Subject subject = new Saml2Subject();
        subject.SubjectConfirmations.Add(new Saml2SubjectConfirmation(Saml2Constants.ConfirmationMethods.Bearer));
        subject.NameId = new Saml2NameIdentifier(nameIdentifierClaim);
        assertion.Subject = subject;
    
        X509SigningCredentials clientSigningCredentials = new X509SigningCredentials(
                new X509Certificate2(certificateWithPrivateKeyRawBytes, password, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable));
    
        assertion.SigningCredentials = clientSigningCredentials;
    
        return new Saml2SecurityToken(assertion);
    }

    public by msdn modified Jan 12, 2015  671  0  6  0

    EnsureApprovalWorkflowOnList: Ensures the approval workflow on list.

    Ensures the approval workflow on list. The web. The list. The events. Whether to use the SAML Approval workflow The workflow subscription id
    /// <summary>
    /// custom Workflow activities Feature Id
    /// </summary>
    private static Guid customWorkflowActivitiesFeatureId = new Guid("5d3b4ca1-21e1-4d29-9605-066b3e77e94a");
    /// <summary>
    /// custom Workflow Feature Id
    /// </summary>
    private static Guid customWorkflowFeatureId = new Guid("49faa188-cb77-490f-9225-c95ad56c6193");
    /// <summary>
    /// id of ContentType Workflow Task SharePoint 2013
    /// </summary>
    private const string ContentTypeWorkflowTaskSharePoint2013 = "0x0108003365C4474CAE8C42BCE396314E88E51F";
    /// <summary>
    /// SAML ApprovalWorkflow Definition Id
    /// </summary>
    private static Guid approvalSamlWorkflowDefinitionId = new Guid("65BE55E6-B0AF-4CB3-BBD7-535FCBB3C5E4");
    /// <summary>
    /// ApprovalWorkflow Definition Id
    /// </summary>
    private static Guid approvalWorkflowDefinitionId = new Guid("73C27777-198F-43B4-A7C0-FE6753ADA4C4");
    
    /// <summary>
    /// Ensures the approval workflow on list.
    /// </summary>
    /// <param name="web">The web.</param>
    /// <param name="list">The list.</param>
    /// <param name="events">The events.</param>
    /// <param name="useSamlWorkflow">Whether to use the SAML Approval workflow</param>
    /// <returns>
    /// The workflow subscription id
    /// </returns>
    /// <exception cref="System.ArgumentNullException"></exception>
    public static Guid EnsureApprovalWorkflowOnList(SPWeb web, SPList list, List<WorkflowStartEventType> events, bool useSamlWorkflow)
    {
        Guid subscriptionId = Guid.Empty;
    
        if (list == null)
        {
            throw new ArgumentNullException("list");
        }
    
        // Remove existing 2010 workflow associations
        SPWorkflowAssociationCollection existingWorkflows = list.WorkflowAssociations;
        if (existingWorkflows != null)
        {
            for (int i = 0; i < existingWorkflows.Count; i++)
            {
                list.WorkflowAssociations.Remove(existingWorkflows[i]);
            }
        }
    
        SPFeature customWorkflowActivitiesFeature = web.Features[customWorkflowActivitiesFeatureId];
    
        if (customWorkflowActivitiesFeature == null)
        {
            customWorkflowActivitiesFeature = web.Features.Add(customWorkflowActivitiesFeatureId);
        }
    
        SPFeature customWorkflowFeature = web.Features[customWorkflowFeatureId];
    
        if (customWorkflowFeature == null)
        {
            customWorkflowFeature = web.Features.Add(customWorkflowFeatureId);
        }
    
        if (customWorkflowFeature != null)
        {
            if (!list.EnableModeration || !list.ForceCheckout)
            {
                list.EnableModeration = true;
                list.ForceCheckout = true;
                list.EnableVersioning = true;
                list.Update();
            }
    
            Dictionary<string, string> workflowPropertyData = GetApprovalWorkflowSettings(web, list.Title);
    
            SPList taskList = EnsureWorkflowTaskList(web, "/lists/workflowtasks", string.Empty);
    
            SPList historyList = EnsureWorkflowHistoryList(web, "/workflowhistory", string.Empty);
    
            if (taskList != null && historyList != null)
            {
                bool workflowTaskContentTypeAssociated = false;
                foreach (SPContentType contentType in taskList.ContentTypes)
                {
                    if (contentType.Parent.Id.ToString().Equals(ContentTypeWorkflowTaskSharePoint2013, StringComparison.OrdinalIgnoreCase))
                    {
                        workflowTaskContentTypeAssociated = true;
                        break;
                    }
                }
    
                if (!workflowTaskContentTypeAssociated)
                {
                    SPContentType wftaskContentType = default(SPContentType);
                    SPContentTypeCollection contentTypes = web.ContentTypes.Count == 0 ? web.Site.RootWeb.ContentTypes : web.ContentTypes;
    
                    wftaskContentType = contentTypes.Cast<SPContentType>().FirstOrDefault<SPContentType>(c => c.Id.ToString().Equals(ContentTypeWorkflowTaskSharePoint2013, StringComparison.OrdinalIgnoreCase));
    
                    if (wftaskContentType != null)
                    {
                        taskList.ContentTypes.Add(wftaskContentType);
                    }
                }
    
                string displayName = ResourcesHelper.GetLocalizedString("workflow_approval_instancename");
    
                Guid workflowDefId = useSamlWorkflow ? approvalSamlWorkflowDefinitionId : approvalWorkflowDefinitionId;
    
                subscriptionId = EnsureWorkflowOnList(web, list, workflowDefId, displayName, events, taskList, historyList, workflowPropertyData, false);
    
                EnableWorkflowsRunAsAnApp(web);
    
                SubscribeToEventReceivers(list, false);
            }
        }
    
        return subscriptionId;
    }

    public by msdn modified Jan 12, 2015  444  0  6  0

    RemoveApprovalWorkflowOnList: Removes the approval workflow on list.

    Removes the approval workflow on list. The web. The list. Is Saml Workflow. The status
    /// <summary>
    /// SAML ApprovalWorkflow Definition Id
    /// </summary>
    private static Guid approvalSamlWorkflowDefinitionId = new Guid("65BE55E6-B0AF-4CB3-BBD7-535FCBB3C5E4");
    /// <summary>
    /// ApprovalWorkflow Definition Id
    /// </summary>
    private static Guid approvalWorkflowDefinitionId = new Guid("73C27777-198F-43B4-A7C0-FE6753ADA4C4");
    
    /// <summary>
    /// Removes the approval workflow on list.
    /// </summary>
    /// <param name="web">The web.</param>
    /// <param name="list">The list.</param>
    /// <param name="isSamlWorkflow">Is Saml Workflow.</param>
    /// <returns>The status</returns>
    public static bool RemoveApprovalWorkflowOnList(SPWeb web, SPList list, bool isSamlWorkflow)
    {
        Guid subscriptionId = Guid.Empty;
    
        try
        {
            Guid workflowDefId = isSamlWorkflow ? approvalSamlWorkflowDefinitionId : approvalWorkflowDefinitionId;
            subscriptionId = EnsureWorkflowOnList(web, list, workflowDefId, null, null, null, null, null, true);
            SubscribeToEventReceivers(list, true);
        }
        catch
        {
        }
    
        return subscriptionId != Guid.Empty;
    }

    external by Omindu Rathnaweera modified Jul 12, 2016  62  0  1  0

    Modified samlsso_notification.jsp to POST SAML error response to ACS URL

    Modified samlsso_notification.jsp to POST SAML error response to ACS URL: samlsso_notification.jsp
    <%--
      ~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
      ~
      ~ WSO2 Inc. licenses this file to you under the Apache License,
      ~ Version 2.0 (the "License"); you may not use this file except
      ~ in compliance with the License.
      ~ You may obtain a copy of the License at
      ~
      ~ http://www.apache.org/licenses/LICENSE-2.0
      ~
      ~ Unless required by applicable law or agreed to in writing,
      ~ software distributed under the License is distributed on an
      ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
      ~ KIND, either express or implied.  See the License for the
      ~ specific language governing permissions and limitations
      ~ under the License.
      --%>
    
    <%@ page import="org.wso2.carbon.identity.application.authentication.endpoint.util.Constants" %>
    <%@ page import="org.owasp.encoder.Encode" %>
    <%@ page import="java.net.URLDecoder"%>
    <%@ page import="org.apache.commons.codec.binary.Base64"%>
    <%@ page import="java.util.zip.Inflater"%>
    <%@ page import="java.util.zip.InflaterInputStream"%>
    <%@ page import="java.util.zip.DataFormatException" %>
    <%@ page import="java.io.ByteArrayInputStream" %>
    <%@ page import="java.io.ByteArrayOutputStream" %>
    <%@ page import="java.nio.charset.StandardCharsets" %>
    
    <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
    
    <%
    
        String stat = request.getParameter(Constants.STATUS);
        String statusMessage = request.getParameter(Constants.STATUS_MSG);
        String encodedResponse = "";
        String acsURL = "";
        String decodedString;
        boolean success = false;
    
        if (stat == null || statusMessage == null) {
            success = false;
        }
        String samlError = request.getParameter("SAMLResponse");
    
        if (samlError == null || samlError.isEmpty()) {
            success = false;
        }
    
        try {
            Base64 base64Decoder = new Base64(0);
            byte[] xmlBytes = samlError.getBytes(StandardCharsets.UTF_8);
            byte[] base64DecodedByteArray = base64Decoder.decode(xmlBytes);
    
            try {
    
                Inflater inflater = new Inflater(true);
                inflater.setInput(base64DecodedByteArray);
                byte[] xmlMessageBytes = new byte[5000];
                int resultLength = inflater.inflate(xmlMessageBytes);
                inflater.end();
                decodedString = new String(xmlMessageBytes, 0, resultLength, StandardCharsets.UTF_8);
    
                if (!inflater.finished()) {
                    success = false;
                } else {
                    success = true;
                }
    
            } catch (DataFormatException e) {
                ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(base64DecodedByteArray);
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                InflaterInputStream iis = new InflaterInputStream(byteArrayInputStream);
                byte[] buf = new byte[1024];
                int count = iis.read(buf);
                while (count != -1) {
                    byteArrayOutputStream.write(buf, 0, count);
                    count = iis.read(buf);
                }
                iis.close();
                decodedString = new String(byteArrayOutputStream.toByteArray(), StandardCharsets.UTF_8);
                success = true;
            }
    
            byte[] encodeBytes = base64Decoder.encode(decodedString.getBytes(StandardCharsets.UTF_8));
            encodedResponse = new String(encodeBytes, StandardCharsets.UTF_8);
    
            acsURL = request.getParameter("ACSUrl");
    
            if (acsURL == null || acsURL.isEmpty()) {
                success = false;
            } else {
                acsURL = URLDecoder.decode(acsURL, StandardCharsets.UTF_8.name());
                success = true;
            }
        } catch (Exception e) {
            success = false;
        }
    
        if (!success) {
            stat = "Authentication Error !";
            statusMessage = "Something went wrong during the authentication process. Please try signing in again.";
        }
    
        session.invalidate();
    %>
    
    <% if (success) {%>
    
    <html>
    <body>
    
    <form method='post' action='<%=acsURL%>'>
        <p>
            <input type='hidden' name='SAMLResponse' value='<%=Encode.forHtmlAttribute(encodedResponse)%>'>
        <noscript>
            <button type='submit'>Continue..</button>
        </noscript>
        </p>
    </form>
    <script type='text/javascript'>
        document.forms[0].submit();
    </script>
    </body>
    </html>
    
    <%} else {%>
    <style>
        .info-box {
            background-color: #EEF3F6;
            border: 1px solid #ABA7A7;
            font-size: 13px;
            font-weight: bold;
            margin-bottom: 10px;
            padding: 10px;
        }
    </style>
    
    <fmt:bundle basename="org.wso2.carbon.identity.application.authentication.endpoint.i18n.Resources">
        <div id="middle">
            <h2><fmt:message key='saml.sso'/></h2>
    
            <div id="workArea">
                <div class="info-box">
                    <%=Encode.forHtml(stat)%>
                </div>
                <table class="styledLeft">
                    <tbody>
                    <tr>
                        <td><%=Encode.forHtmlContent(statusMessage)%>
                        </td>
                    </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </fmt:bundle>
    
    <% } %>
    
    

    external by Zulfiqar Ahmed modified Jun 1, 2017  5  0  1  0

    Sample request to create Auth0 Saml connection with samlp metadata

    Sample request to create Auth0 Saml connection with samlp metadata: saml-connection-creation-with-metadata.md
    #Saml-connection creation
    
    ###Payload
    
    ```bash
    curl -H "Authorization: Bearer ..-yiSm0uYkVArSrXYojrkhwvI1dPzcZRlDQ---" -X POST  -H "Content-Type: application/json" -d '{"name":"pkr-tenant","strategy":"samlp","options":{"metadataUrl":"https://pkr.myauth0.com/samlp/metadata/vj4HB0DougzOsvUOQrLE6mLSyTl9GeIY"}}' https://zulfiqar.myauth0.com/api/v2/connections`
    ```
    
    ```
    {
      "name": "pkr-tenant",
      "strategy": "samlp",
      "options": {
        "metadataUrl": "https://pkr.myauth0.com/samlp/metadata/vj4HB0DougzOsvUOQrLE6mLSyTl9GeIY"
      }
    }
    ```
    
    

    external by Peter Braswell modified Sep 13, 2014  114  1  2  0

    Issues with SAML Integration

    Issues with SAML Integration: gistfile1.rb
    # routes.rb
    ActionController::Routing::Routes.draw do |map|
    
      map.connect 'saml', :controller => 'saml', :action => 'init'
      map.connect '/saml/:action', :controller => 'saml'
    ...
    
    # Gemfile
    gem 'ruby-saml'
    
    ...
    
    
    # /app/controllers/saml_controller.ruby
    require 'onelogin/ruby-saml'
    
    class SamlController < ApplicationController
      def init
        request = OneLogin::RubySaml::Authrequest.new
        redirect_to(request.create(saml_settings))
      end
    
      def consume
        response          = OneLogin::RubySaml::Response.new(params[:SAMLResponse])
        response.settings = saml_settings
    
        if response.is_valid? && user = current_account.users.find_by_email(response.name_id)
          authorize_success(user)
        else
          authorize_failure(user)
        end
      end
    
      private
    
      def saml_settings
        settings = OneLogin::RubySaml::Settings.new
    
        settings.assertion_consumer_service_url = "http://#{request.host}/saml/consume"
        settings.issuer                         = request.host
        settings.idp_sso_target_url             = "https://app.onelogin.com/saml/signon/#{OneLoginAppId}"
        settings.idp_cert_fingerprint           = OneLoginAppCertFingerPrint
        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"
        # Optional. Describe according to IdP specification (if supported) which attributes the SP desires to receive in SAMLResponse.
        settings.attributes_index = 30
    
        settings
      end
    end
    
    

    external by trscavo modified Sep 24, 2014  102  0  2  0

    Bash script to fetch SAML metadata via the Metadata Query Protocol

    Bash script to fetch SAML metadata via the Metadata Query Protocol: mdq_get.sh
    #!/bin/bash
    
    ###########################################################
    # Fetch SAML metadata via the Metadata Query Protocol
    #
    # usage: mdq_get.sh [-tv] IDENTIFIER
    #
    # where the -t option simply outputs the computed request URL (without 
    # querying for metadata) and the -v option causes curl to produce verbose 
    # output. The two options are mutually exclusive.
    #
    # The single command-line argument is an arbitrary IDENTIFIER as defined
    # in the Metadata Query Protocol spec but in a SAML context the IDENTIFIER 
    # is usually a SAML entityID, which is used to fetch a single entity descriptor.
    #
    # Note: set environment variable MDQ_BASE_URL before using this script
    #
    # Example:
    #
    # $ export MDQ_BASE_URL=http://mdq.example.com/public
    # $ mdq_get.sh -t https://sso.example.org/idp
    # http://mdq.example.com/public/entities/https%3A%2F%2Fsso.example.org%2Fidp
    #
    # See: https://github.com/iay/md-query
    ###########################################################
    
    script_name=${0##*/}  # equivalent to basename $0
    
    # check the required environment variable
    if [ -z "$MDQ_BASE_URL" ]; then
    	echo "ERROR: $script_name: environment variable MDQ_BASE_URL does not exist" >&2
    	exit 2
    fi
    
    # construct a request URL per the MDQ Protocol specification
    # see: https://github.com/iay/md-query
    construct_mdq_url () {
    	# construct_mdq_url <base_url> <url_encoded_id>
    
    	# make sure there are two command-line arguments
    	if [ $# -ne 2 ]; then
    		echo "ERROR: $FUNCNAME: incorrect number of arguments: $# (2 required)" >&2
    		return 2
    	fi
    	local base_url=$1
    	local url_encoded_id=$2
    	
    	# add a trailing slash to the base URL if necessary
    	local length="${#1}"
    	if [[ "${base_url:length-1:1}" == '/' ]]; then
    		echo "${base_url}entities/$url_encoded_id"
    	else
    		echo "${base_url}/entities/$url_encoded_id"
    	fi
    }
    
    # URL-encode an arbitrary string
    # see: https://gist.github.com/cdown/1163649
    urlencode () {
    	# urlencode <string>
    	
    	# make sure there is one (and only one) command-line argument
    	if [ $# -ne 1 ]; then
    		echo "ERROR: $FUNCNAME: incorrect number of arguments: $# (1 required)" >&2
    		return 2
    	fi
    
    	local length="${#1}"
    	for (( i = 0; i < length; i++ )); do
    		local c="${1:i:1}"
    		case "$c" in
    			[a-zA-Z0-9.~_-]) printf "$c" ;;
    			*) printf '%%%02X' "'$c"
    		esac
    	done
    }
    
    # process command-line option(s)
    test_mode=false; verbose_mode=false
    while getopts ":tv" opt; do
    	case $opt in
    		t)
    			test_mode=true
    			verbose_mode=false
    			;;
    		v)
    			test_mode=false
    			verbose_mode=true
    			;;
    		\?)
    			echo "ERROR: $script_name: Unrecognized option: -$OPTARG" >&2
    			exit 2
    			;;
    	esac
    done
    
    # make sure there is one (and only one) command-line argument left
    shift $(( OPTIND - 1 ))
    if [ $# -ne 1 ]; then
    	echo "ERROR: $script_name: incorrect number of arguments: $# (1 required)" >&2
    	exit 2
    fi
    id=$1
    
    # URL-encode the identifier
    encoded_id=$( urlencode "$id" )
    return_status=$?
    if [ "$return_status" -ne 0 ]; then
    	echo "ERROR: $script_name: failed to URL-encode the identifier" >&2
    	exit $return_status
    fi
    
    # construct the request URL
    request_url=$( construct_mdq_url $MDQ_BASE_URL $encoded_id )
    return_status=$?
    if [ "$return_status" -ne 0 ]; then
    	echo "ERROR: $script_name: failed to construct the request URL" >&2
    	exit $return_status
    fi
    
    # use curl to request the resource (unless in test mode)
    if $test_mode; then
    	echo $request_url
    else
    	if $verbose_mode; then
    		opt="-v"
    	else
    		opt=
    	fi
    	/usr/bin/curl $opt $request_url
    fi
    
    
    

    external by ccastan1 modified Jan 6, 2015  91  0  1  0

    saml response for 15five

    saml response for 15five: gistfile1.txt
    <samlp:Response ID="_0f206bc0-780e-0132-bb09-6c40088ad7b6" Version="2.0" IssueInstant="2015-01-06T20:11:01Z" Destination="https://bitium.15five.com/saml2/acs/" Consent="urn:oasis:names:tc:SAML:2.0:consent:unspecified" xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"><Issuer xmlns="urn:oasis:names:tc:SAML:2.0:assertion">http://bitium.dev/bitium.com</Issuer><samlp:Status><samlp:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success"/></samlp:Status><Assertion xmlns="urn:oasis:names:tc:SAML:2.0:assertion" ID="_0f206c10-780e-0132-bb09-6c40088ad7b6" IssueInstant="2015-01-06T20:11:01Z" Version="2.0"><Issuer>http://bitium.dev/bitium.com</Issuer><ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#"><ds:SignedInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#"><ds:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"></ds:CanonicalizationMethod><ds:SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"></ds:SignatureMethod><ds:Reference URI="#_0f206c10-780e-0132-bb09-6c40088ad7b6"><ds:Transforms><ds:Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"></ds:Transform><ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"></ds:Transform></ds:Transforms><ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"></ds:DigestMethod><ds:DigestValue>SkL5mMm1WRo89yEz4/qRKk+u0Io=</ds:DigestValue></ds:Reference></ds:SignedInfo><ds:SignatureValue>PdjMOPKKW/3MYJY5/qH0qwgsUcJoGjCbrwQExdfCamI7qNtzdPk+E/ptdEpbqSLmnkGZkq6P6C9rXq4W9P/lzB3jrmkBqT3yJjbzFrmeOHT2bhJB+pdqrTXk6hB+UVLvU1nkURz+jG7rqwedm3BD772UdxpIhuXwvS2+9qnipMm3M8EONPdUs/fTaVhKk3UMPVu7qKZkRk35LaInPMQHefGYMZxJ99TPRcqcThOH3ZzJWyhT11CtOQ02lj4X9huRqtPZMTLaBG+b/8FEpqNUfz7NlgFCtUMBRXDZDm7yR+9f9If5XCZ/bNLYtAnU8QjgZ1scn06GV2PgY2f/YXSzNQ==</ds:SignatureValue><KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#"><ds:X509Data><ds:X509Certificate>MIIDjDCCAnSgAwIBAgITBlhjOBu0pJB9NDHdnCiewZ0SMzANBgkqhkiG9w0BAQUFADBWMRMwEQYDVQQDDApiaXRpdW0uY29tMQ8wDQYDVQQKDAZCaXRpdW0xFDASBgNVBAcMC0xvcyBBbmdlbGVzMQswCQYDVQQIDAJDQTELMAkGA1UEBhMCVVMwHhcNMTQwOTI5MjEzNTE4WhcNMjQwOTI5MjEzNTE4WjBWMRMwEQYDVQQDDApiaXRpdW0uY29tMQ8wDQYDVQQKDAZCaXRpdW0xFDASBgNVBAcMC0xvcyBBbmdlbGVzMQswCQYDVQQIDAJDQTELMAkGA1UEBhMCVVMwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCvY443+fQYcsMCAW8XjeQUWpNJImBzQz5bMjbShUx/fX3TJnsPWn9hN2M9PBzjLtB0/8+ojiXdDNOns/S/0sZyo1mCeY+7P4qOzqU/qruLi2hgae/ETfaB5ikiiFOSQh98FSd9MM+PghPm6xUW0UFdq3MJIVUQx8xJWPB8g6CPuGdx1cC7T3do6KXEocQnHdevJ8LCsHxxSyIlEk/kgKPuEv7Mkhx5jg1v664NP4k6h+B+opvu2VPVQFaXrxdvCWdXC51JTlygax/XwA6H/wDgtysETTUxJublXyRvkAvxPX9uVu+91FwilvbNMdSDKGwIzpfIKhS3u4A6DTHPlTL7AgMBAAGjUzBRMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFChdSjDG13NRTLeSbTLHvgjxlpf7MB8GA1UdIwQYMBaAFChdSjDG13NRTLeSbTLHvgjxlpf7MA0GCSqGSIb3DQEBBQUAA4IBAQCIFgLm6Ay9oExDm4/etdCFfrmR5qKPW8FWUF2JH5Ay8X6BIVfXhNNwGzuY0km2YV1wNVrlip8mDvNhtF7nQi3JyAu34/n89sYuR+kjU9TkgPPikhS/5cEKnw+bnli5+f+W8wAAm7haXeVMIOQnQpzB1LuUWv3Dc1Ak8TJEBeHRAMtk3ok3Kk9Zah92ToQC9vqWEPWk2BFGbfLvFgtQdY+XF/1v7IqG2GaQlO3xP5RKR6t5AAS58lp8FF3pceax3o0XrOra6Y+Qj6YQwIDLDCft5A9JbKTnXskecXrQDeAgROM+hOdzujs5//YaASBA3rT4hCzajJ5TxEG20tJQ0asq</ds:X509Certificate></ds:X509Data></KeyInfo></ds:Signature><Subject><NameID Format="urn:oasis:names:tc:SAML:2.0:nameid-format:emailAddress">christian@bitium.com</NameID><SubjectConfirmation Method="urn:oasis:names:tc:SAML:2.0:cm:bearer"><SubjectConfirmationData NotOnOrAfter="2015-01-06T20:14:01Z" Recipient="https://bitium.15five.com/saml2/acs/"></SubjectConfirmationData></SubjectConfirmation></Subject><Conditions NotBefore="2015-01-06T20:10:56Z" NotOnOrAfter="2015-01-06T20:26:01Z"><AudienceRestriction><Audience>https://bitium.15five.com/saml2/metadata/</Audience></AudienceRestriction></Conditions><AttributeStatement><Attribute Name="login" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri" FriendlyName="Login"><AttributeValue>christian@bitium.com</AttributeValue></Attribute></AttributeStatement><AuthnStatement AuthnInstant="2015-01-06T20:11:01Z" SessionIndex="_0f206c10-780e-0132-bb09-6c40088ad7b6"><AuthnContext><AuthnContextClassRef>urn:oasis:names:tc:SAML:2.0:ac:classes:Password</AuthnContextClassRef></AuthnContext></AuthnStatement></Assertion></samlp:Response>
    
    

    external by Tom Scavo modified Oct 13, 2014  68  0  1  0

    Filter the entity attributes from a SAML metadata file

    Filter the entity attributes from a SAML metadata file: filter_mdattr.sh
    #!/bin/bash
    
    #####################################################################
    # Inspect a SAML metadata file, iterate over the entity descriptors
    # in the file, and pass each entity descriptor through a filter that
    # produces a list of entity attributes in metadata.
    #
    # usage: filter_mdattr.sh MD_FILE
    #
    #####################################################################
    
    script_bin=${0%/*}  # equivalent to dirname $0
    script_name=${0##*/}  # equivalent to basename $0
    
    # process command-line option(s)
    verbose_mode=false
    while getopts ":v" opt; do
    	case $opt in
    		v)
    			verbose_mode=true
    			;;
    		\?)
    			echo "ERROR: $script_name: Unrecognized option: -$OPTARG" >&2
    			exit 2
    			;;
    	esac
    done
    
    # make sure there is one (and only one) command-line argument
    shift $(( OPTIND - 1 ))
    if [ $# -ne 1 ]; then
    	echo "ERROR: $script_name: incorrect number of arguments: $# (1 required)" >&2
    	exit 2
    fi
    md_file=$1
    
    # make sure the command-line argument is a non-null file path
    if [ -z "$md_file" ]; then
    	printf "ERROR: %s: file argument is null" $script_name >&2
    	exit 2
    fi
    if [ ! -f "$md_file" ] ; then
    	printf "ERROR: The metadata file does not exist: %s\n" $md_file >&2
    	exit 2
    fi
    
    # Does the file contain an aggregate of SAML metadata?
    entitiesDescriptor=$( /bin/cat "$md_file" | grep -E '<(md:)?EntitiesDescriptor ' )
    if [ -z "$entitiesDescriptor" ]; then
    	printf "ERROR: The file is NOT a SAML metadata aggregate: %s\n" $md_file >&2
    	exit 2
    fi
    
    #####################################################################
    # An entity attribute filter that returns a list of entity attributes 
    # bound to an entity descriptor. The filter produces one line of output 
    # for each entity attribute value in the entity descriptor:
    #
    # <registrarID> <entityID> <role> <attr_name> <attr_value>
    #
    # where <role> is either "IdP" or "SP" (or "UNKNOWN" if the role can 
    # not be determined).
    #
    # A typical entity attribute looks like this:
    #
    # <mdattr:EntityAttributes xmlns:mdattr="urn:oasis:names:tc:SAML:metadata:attribute">
    #   <saml:Attribute xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion"
    #       Name="http://macedir.org/entity-category" 
    #       NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri">
    #     <saml:AttributeValue>
    #       http://refeds.org/category/research-and-scholarship
    #     </saml:AttributeValue>
    #   </saml:Attribute>
    # </mdattr:EntityAttributes>
    #
    # The above entity attribute has name "http://macedir.org/entity-category" 
    # and value "http://refeds.org/category/research-and-scholarship".
    #
    # Note that entity attributes may be multi-valued, in which case multiple 
    # lines of output are returned per entity attribute, one for each value.
    #####################################################################
    filter_entity () {
    	
    	# make sure there is one (and only one) command-line argument
    	if [ $# -ne 1 ]; then
    		echo "ERROR: $FUNCNAME: incorrect number of arguments: $# (1 required)" >&2
    		return 2
    	fi
    	
    	# get the entity attributes for this entity (if any)
    	entityAttributes=$( echo "$1" \
    		| sed -n -e '\;<\(mdattr:\)\{0,1\}EntityAttributes;,\;EntityAttributes>;p'
    	)
    	
    	# if there aren't any entity attributes, we're done
    	if [ -z "$entityAttributes" ]; then
    		return 0
    	fi
    
    	# get the Registrar ID
    	if echo "$1" | grep -Fq ' registrationAuthority='; then
    		registrarID=$( echo "$1" \
    			| grep -F -m 1 ' registrationAuthority=' \
    			| sed -e 's/^.* registrationAuthority="\([^"]*\)".*$/\1/'
    		)
    	else
    		registrarID=UNKNOWN
    	fi
    
    	# get the entityID
    	entityID=$( echo "$1" \
    		| grep -F -m 1 ' entityID=' \
    		| sed -e 's/^.* entityID="\([^"]*\)".*$/\1/'
    	)
    	
    	# get the primary role of this entity
    	if echo "$1" | grep -Eq '<(md:)?IDPSSODescriptor '; then
    		if echo "$1" | grep -Evq '<(md:)?SPSSODescriptor '; then
    			role=IdP
    		fi
    	elif echo "$1" | grep -Eq '<(md:)?SPSSODescriptor '; then
    		if echo "$1" | grep -Evq '<(md:)?IDPSSODescriptor '; then
    			role=SP
    		fi
    	else
    		role=UNKNOWN
    	fi
    	
    	# get a list of the entity attribute names
    	attr_names=$( echo "$entityAttributes" \
    		| grep -F ' Name=' \
    		| sed -e 's/^.* Name="\([^"]*\)".*$/\1/'
    	)
    	
    	# iterate over the attribute names
    	for attr_name in $attr_names; do
    	
    		# get the entity attribute with the given name
    		entityAttribute=$( echo "$entityAttributes" \
    			| sed -n -e '\;<\([[:alnum:]]\{1,\}:\)\{0,1\}Attribute.* Name="'${attr_name}'";,\;Attribute>;p'
    		)
    		
    		# get a list of the entity attribute values
    		attr_values=$( echo "$entityAttribute" \
    			| grep -E '<([^:]+:)?AttributeValue[^>]*>' \
    			| sed -e 's/^.*<\([[:alnum:]]\{1,\}:\)\{0,1\}AttributeValue[^>]*>\([^<]*\).*$/\2/'
    		)
    	
    		# iterate over the attribute values
    		for attr_value in $attr_values; do
    			echo "$registrarID $entityID $role $attr_name $attr_value"
    		done
    	done
    	
    	return 0
    }
    
    #####################################################################
    # begin processing
    #####################################################################
    
    # get a list of entityIDs from the metadata aggregate
    entityIDs=$( /bin/cat $md_file | grep -F ' entityID=' \
    	| sed -E 's/^.+ entityID="([^"]+).+$/\1/'
    )
    
    if $verbose_mode; then
    	num_entities=$( echo "$entityIDs" | /usr/bin/wc -l )
    	printf "Number of entities found: %d\n" $num_entities
    fi
    	
    for entityID in $entityIDs; do
    	
    	# get the entity descriptor for this entity
    	entityDescriptor=$( /bin/cat $md_file \
    		| sed -n -e '\;<\(md:\)\{0,1\}EntityDescriptor.* entityID="'${entityID}'";,\;EntityDescriptor>;p'
    	)
    	
    	filtered_result=$( filter_entity "$entityDescriptor" )
    	return_status=$?
    	if [ "$return_status" -ne 0 ]; then
    		echo "ERROR: $script_name: failed to execute filter: $filter_file" >&2
    	fi
    
    	if [ ! -z "$filtered_result" ];  then
    		echo "$filtered_result"
    	fi
    done
    
    
    
    • Public Snippets
    • Channels Snippets