Pysaml2 implimenation for IDP flow getting error in certificate signature

can any one integrated okta set up for IDP flow for pysaml2 ,i need complete working source code?

I am facing issue while parsing auth response in IDP ,here my SP flow is success. after debugging i cam to know that it’s able to deocde the SAML response succesfully but it’s failed in verify signature of certificate and failing with below reason

any help will be more appreciated if possible any one have complete working flow for IDP.
Here,not sure why i am getting certificate signature is failed.

func=xmlSecOpenSSLX509StoreVerify:file=x509vfy.c:line=341:obj=x509-store:subj=unknown:error=71:certificate verification failed:X509_verify_cert: subject=/C=US/ST=California/L=San Francisco/O=Okta/OU=SSOProvider/CN=dev-220782/emailAddress=info@okta.com; issuer=/C=US/ST=California/L=San Francisco/O=Okta/OU=SSOProvider/CN=dev-220782/emailAddress=info@okta.com; err=18; msg=self signed certificate
func=xmlSecOpenSSLX509StoreVerify:file=x509vfy.c:line=380:obj=x509-store:subj=unknown:error=71:certificate verification failed:subject=/C=US/ST=California/L=San Francisco/O=Okta/OU=SSOProvider/CN=dev-220782/emailAddress=info@okta.com; issuer=/C=US/ST=California/L=San Francisco/O=Okta/OU=SSOProvider/CN=dev-220782/emailAddress=info@okta.com; err=18; msg=self signed certificate
OK
SignedInfo References (ok/all): 1/1
Manifests References (ok/all): 0/0

my code : # -- coding: utf-8 --

Copyright 2015 Okta, Inc.

Licensed 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.

import logging
import os
import uuid

from flask import (
Flask,
redirect,
render_template,
request,
session,
url_for,
)
#from flask.ext.login import LoginManager, UserMixin,current_user,login_required,login_user,logout_user

from flask_bootstrap import Bootstrap
from saml2 import BINDING_HTTP_POST,BINDING_HTTP_REDIRECT,entity
from saml2.client import Saml2Client
from saml2.config import Config as Saml2Config
import requests
from cryptography.hazmat.backends import default_backend
from cryptography import x509

metadata_url_for contains PER APPLICATION configuration settings.

Each SAML service that you support will have different values here.

NOTE:

This is implemented as a dictionary for DEMONSTRATION PURPOSES ONLY.

On a production system, this information should be stored as approprate

for your concept of “customer company”, “group”, “organization”, or “team”

metdatastr = “”"<md:EntityDescriptor xmlns:md=“urn:oasis:names:tc:SAML:2.0:metadata” entityID=“http://www.okta.com/exkih6doyyeNql8wo0h7”>
<md:IDPSSODescriptor WantAuthnRequestsSigned=“false” protocolSupportEnumeration=“urn:oasis:names:tc:SAML:2.0:protocol”>
<md:KeyDescriptor use=“signing”>
<ds:KeyInfo xmlns:ds=“http://www.w3.org/2000/09/xmldsig#”>
ds:X509Data
ds:X509Certificate
MIIDpDCCAoygAwIBAgIGAV2TI2WnMA0GCSqGSIb3DQEBCwUAMIGSMQswCQYDVQQGEwJVUzETMBEG A1UECAwKQ2FsaWZvcm5pYTEWMBQGA1UEBwwNU2FuIEZyYW5jaXNjbzENMAsGA1UECgwET2t0YTEU MBIGA1UECwwLU1NPUHJvdmlkZXIxEzARBgNVBAMMCmRldi0yMjA3ODIxHDAaBgkqhkiG9w0BCQEW DWluZm9Ab2t0YS5jb20wHhcNMTcwNzMwMTA1NDU2WhcNMjcwNzMwMTA1NTU2WjCBkjELMAkGA1UE BhMCVVMxEzARBgNVBAgMCkNhbGlmb3JuaWExFjAUBgNVBAcMDVNhbiBGcmFuY2lzY28xDTALBgNV BAoMBE9rdGExFDASBgNVBAsMC1NTT1Byb3ZpZGVyMRMwEQYDVQQDDApkZXYtMjIwNzgyMRwwGgYJ KoZIhvcNAQkBFg1pbmZvQG9rdGEuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA h5bwrcemiEFthB6CrJYHBgcGaNstKPkxcnY3VTC0Ph0B5YHb+2RZYnj//OsQU6mOTH6/y5J1kV/r gSBF5FYkeMF2RzWXiLNYschalSgUWbIk/2DUQ4mMEGBeC21PCCtnYFs4vpDiR7rYTdYs5EDoXF1G +oa0K/fEBwcZNV+HDc3EK1hWn30E+YWjnK+t/8WTPObggW6ziRgdmKsPR+7KMluY+rj9LDrYTxai WkmCGRpJHexlmecfCM/M7Yu6mO+Op2jvSUjZy2MKyPWwD5T6SAg5atu/EYSpBvMCIFRaGZTpfOoS 8YF1b8ittv34ChbStOCRMXd/NlNECgVb36C1MQIDAQABMA0GCSqGSIb3DQEBCwUAA4IBAQAhDQKA aFrSYEdHhV/EsZxiBYCXzb4w9bN2DfpRhHFpIGqlehXtGELOaU/mmuyOSoyesDMgjROAe+LSqrMJ X2YXFI360UzuNEGi3+h1nwf0CRMXl1yB+isiZdnzhpDhw69LTZLA9k1IE3ZwLNG7WUU4FvIUr2e+ WEpgJUlQSb9zH5JZ6l0/olZcM4UK3VANBAI0YPh8ztGIB0Is0ypinjUYVB5Qr0avMMrDNdB0kcdY tIMbVfhuAP6CqhZarfZDXt1ByxxzIGbpnAWSbABiMPfqSwWX90WnuK3lhxcJNF0acnlPqft9woeJ AXfzzGerkaUTViH1KNs+qQeTjgKA09FR
</ds:X509Certificate>
</ds:X509Data>
</ds:KeyInfo>
</md:KeyDescriptor>
md:NameIDFormat
urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified
</md:NameIDFormat>
md:NameIDFormat
urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress
</md:NameIDFormat>
<md:SingleSignOnService Binding=“urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST” Location=“https://dev-220782.oktapreview.com/app/rokolabsdev220782_demoqa_1/exkih6doyyeNql8wo0h7/sso/saml”/>
<md:SingleSignOnService Binding=“urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect” Location=“https://dev-220782.oktapreview.com/app/rokolabsdev220782_demoqa_1/exkih6doyyeNql8wo0h7/sso/saml”/>
</md:IDPSSODescriptor>
</md:EntityDescriptor>"""
metadata_url_for = {
# For testing with http://saml.oktadev.com use the following:
# ‘test’: ‘http://idp.oktadev.com/metadata’,
# WARNING WARNING WARNING
# You MUST remove the testing IdP from a production system,
# as the testing IdP will allow ANYBODY to log in as ANY USER!
# WARNING WARNING WARNING
‘example1-okta-com’: ‘http://idp.oktadev.com/metadata’,
‘example-okta-com’: metdatastr
}

app = Flask(name)
Bootstrap(app)
app.secret_key = str(uuid.uuid4()) # Replace with your secret key
#login_manager = LoginManager()
#login_manager.setup_app(app)
logging.basicConfig(level=logging.DEBUG)

NOTE:

This is implemented as a dictionary for DEMONSTRATION PURPOSES ONLY.

On a production system, this information must come

from your system’s user store.

user_store = {}

def saml_client_for(idp_name=None):
‘’’
Given the name of an IdP, return a configuation.
The configuration is a hash for use by saml2.config.Config
‘’’

if idp_name not in metadata_url_for:
    raise Exception("Settings for IDP '{}' not found".format(idp_name))
acs_url = url_for(
    "idp_initiated",
    idp_name=idp_name,
    _external=True)
https_acs_url = url_for(
    "idp_initiated",
    idp_name=idp_name,
    _external=True,
    _scheme='http')

#   SAML metadata changes very rarely. On a production system,
#   this data should be cached as approprate for your production system.
#rv = requests.get(metadata_url_for[idp_name])
rv = metadata_url_for[idp_name]
f = open('mycert.pem', "rb")
pem_data = f.read()
f.close()

key = x509.load_pem_x509_certificate(pem_data, backend=default_backend())
public_key = key.public_key()

settings = {
    'metadata': {
        #'inline': [rv.text],
        'inline': [rv],
        },
    'entityid':"http://www.okta.com/exkih6doyyeNql8wo0h7",
   # "cert_file": key,
  #  "key_file": public_key,
    'xmlsec_binary': '/usr/bin/xmlsec1',
     'encryption_keypairs': [{
         'key_file': public_key,
         'cert_file': key,
     }],

“x509cert”: “”">MIIDpDCCAoygAwIBAgIGAV2TI2WnMA0GCSqGSIb3DQEBCwUAMIGSMQswCQYDVQQGEwJVUzETMBEG

A1UECAwKQ2FsaWZvcm5pYTEWMBQGA1UEBwwNU2FuIEZyYW5jaXNjbzENMAsGA1UECgwET2t0YTEU

MBIGA1UECwwLU1NPUHJvdmlkZXIxEzARBgNVBAMMCmRldi0yMjA3ODIxHDAaBgkqhkiG9w0BCQEW

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XivS6Uc5W3xYrlhJB/2BHJMT2yNzsP3BjTnozvN+C5rU6DSdkhksQ43aoN/wOqnzTXhBTy/mT7NYzQbd2JtKXCJstVrVCgNfWILDBLrdMvQClckczSKctd/hqSqtok4WfgswQVaaGjl9ZtDVCVwbmJn1zSV5PmCF7tY6YkGD1OVL9Kg1pvBldLbPCNuNwHFPq9S+UCDsMhPuxijglBbYjAmV91O3kS1Utz0kVjqJ41VtKpRprAsxmWKlttCP94TgfmOcVL8dc5zHfVTOdFzN0BllSfj+4GZwwZOzG3IUYHtwx46TKzvN5UalpCRFt+fA==”"",

    'service': {
        'sp': {
            'endpoints': {
                'assertion_consumer_service': [
                    (acs_url, BINDING_HTTP_REDIRECT),
                    (acs_url, BINDING_HTTP_POST),
                    (https_acs_url, BINDING_HTTP_REDIRECT),
                    (https_acs_url, BINDING_HTTP_POST)
                ],
            },
            # Don't verify that the incoming requests originate from us via
            # the built-in cache for authn request ids in pysaml2
            'allow_unsolicited': True,
            # Don't sign authn requests, since signed requests only make
            # sense in a situation where you control both the SP and IdP
            'authn_requests_signed': False,
            'logout_requests_signed': True,
            'want_assertions_signed': False,
            'want_response_signed': False,
            'authn_assertions_signed': False,
            #'only_use_keys_in_metadata': True,
            'id_attr_name': 'id'
        },
    },
}

# if 'ENTITY_ID' in settings.SAML2_AUTH:
#     settings['entityid'] = settings.SAML2_AUTH['ENTITY_ID']
# # print('entity id ' , settings.SAML2_AUTH['ENTITY_ID'])
# if 'NAME_ID_FORMAT' in settings.SAML2_AUTH:
#     settings['service']['sp']['name_id_format'] = settings.SAML2_AUTH['NAME_ID_FORMAT']
# NOTE-'NAME_ID_FORMAT is set to None above

#settings['entityid'] = "http://www.okta.com/exkih6doyyeNql8wo0h7"
spConfig = Saml2Config()
spConfig.load(settings)
spConfig.allow_unknown_attributes = True
saml_client = Saml2Client(config=spConfig)
return saml_client

def saml_client_for_idp(idp_name=None):
‘’’
Given the name of an IdP, return a configuation.
The configuration is a hash for use by saml2.config.Config
‘’’

if idp_name not in metadata_url_for:
    raise Exception("Settings for IDP '{}' not found".format(idp_name))
acs_url = url_for(
    "idp_initiated",
    idp_name=idp_name,
    _external=True)
https_acs_url = url_for(
    "idp_initiated",
    idp_name=idp_name,
    _external=True,
    _scheme='http')

#   SAML metadata changes very rarely. On a production system,
#   this data should be cached as approprate for your production system.
#rv = requests.get(metadata_url_for[idp_name])
rv = metadata_url_for[idp_name]
f = open('mycert.pem', "rb")
pem_data = f.read()
f.close()

key = x509.load_pem_x509_certificate(pem_data, backend=default_backend())
public_key = key.public_key()

settings = {
    'metadata': {
        #'inline': [rv.text],
        'inline': [rv],
        },
    'entityid':"http://www.okta.com/exkih6doyyeNql8wo0h7",
   # "cert_file": key,
  #  "key_file": public_key,
    'xmlsec_binary': '/usr/bin/xmlsec1',
     'encryption_keypairs': [{
         'key_file': public_key,
         'cert_file': key,
     }],

“x509cert”: “”">MIIDpDCCAoygAwIBAgIGAV2TI2WnMA0GCSqGSIb3DQEBCwUAMIGSMQswCQYDVQQGEwJVUzETMBEG

A1UECAwKQ2FsaWZvcm5pYTEWMBQGA1UEBwwNU2FuIEZyYW5jaXNjbzENMAsGA1UECgwET2t0YTEU

MBIGA1UECwwLU1NPUHJvdmlkZXIxEzARBgNVBAMMCmRldi0yMjA3ODIxHDAaBgkqhkiG9w0BCQEW

DWluZm9Ab2t0YS5jb20wHhcNMTcwNzMwMTA1NDU2WhcNMjcwNzMwMTA1NTU2WjCBkjELMAkGA1UE

BhMCVVMxEzARBgNVBAgMCkNhbGlmb3JuaWExFjAUBgNVBAcMDVNhbiBGcmFuY2lzY28xDTALBgNV

BAoMBE9rdGExFDASBgNVBAsMC1NTT1Byb3ZpZGVyMRMwEQYDVQQDDApkZXYtMjIwNzgyMRwwGgYJ

KoZIhvcNAQkBFg1pbmZvQG9rdGEuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA

h5bwrcemiEFthB6CrJYHBgcGaNstKPkxcnY3VTC0Ph0B5YHb+2RZYnj//OsQU6mOTH6/y5J1kV/r

gSBF5FYkeMF2RzWXiLNYschalSgUWbIk/2DUQ4mMEGBeC21PCCtnYFs4vpDiR7rYTdYs5EDoXF1G

+oa0K/fEBwcZNV+HDc3EK1hWn30E+YWjnK+t/8WTPObggW6ziRgdmKsPR+7KMluY+rj9LDrYTxai

WkmCGRpJHexlmecfCM/M7Yu6mO+Op2jvSUjZy2MKyPWwD5T6SAg5atu/EYSpBvMCIFRaGZTpfOoS

8YF1b8ittv34ChbStOCRMXd/NlNECgVb36C1MQIDAQABMA0GCSqGSIb3DQEBCwUAA4IBAQAhDQKA

aFrSYEdHhV/EsZxiBYCXzb4w9bN2DfpRhHFpIGqlehXtGELOaU/mmuyOSoyesDMgjROAe+LSqrMJ

X2YXFI360UzuNEGi3+h1nwf0CRMXl1yB+isiZdnzhpDhw69LTZLA9k1IE3ZwLNG7WUU4FvIUr2e+

WEpgJUlQSb9zH5JZ6l0/olZcM4UK3VANBAI0YPh8ztGIB0Is0ypinjUYVB5Qr0avMMrDNdB0kcdY

tIMbVfhuAP6CqhZarfZDXt1ByxxzIGbpnAWSbABiMPfqSwWX90WnuK3lhxcJNF0acnlPqft9woeJ

AXfzzGerkaUTViH1KNs+qQeTjgKA09FR""",

“privateKey”: “”“VwOIzBv0DPRo5b5YszkPhWXivS6Uc5W3xYrlhJB/2BHJMT2yNzsP3BjTnozvN+C5rU6DSdkhksQ43aoN/wOqnzTXhBTy/mT7NYzQbd2JtKXCJstVrVCgNfWILDBLrdMvQClckczSKctd/hqSqtok4WfgswQVaaGjl9ZtDVCVwbmJn1zSV5PmCF7tY6YkGD1OVL9Kg1pvBldLbPCNuNwHFPq9S+UCDsMhPuxijglBbYjAmV91O3kS1Utz0kVjqJ41VtKpRprAsxmWKlttCP94TgfmOcVL8dc5zHfVTOdFzN0BllSfj+4GZwwZOzG3IUYHtwx46TKzvN5UalpCRFt+fA==”"",

    'service': {
        'sp': {
            'endpoints': {
                'assertion_consumer_service': [
                    (acs_url, BINDING_HTTP_REDIRECT),
                    (acs_url, BINDING_HTTP_POST),
                    (https_acs_url, BINDING_HTTP_REDIRECT),
                    (https_acs_url, BINDING_HTTP_POST)
                ],
            },
            # Don't verify that the incoming requests originate from us via
            # the built-in cache for authn request ids in pysaml2
            'allow_unsolicited': True,
            # Don't sign authn requests, since signed requests only make
            # sense in a situation where you control both the SP and IdP
            'authn_requests_signed': False,
            'logout_requests_signed': True,
            'want_assertions_signed': False,
            'want_response_signed': True,
            'authn_assertions_signed': False,
            #'only_use_keys_in_metadata': True,
            'id_attr_name': 'id'
        },
    },
}

# if 'ENTITY_ID' in settings.SAML2_AUTH:
#     settings['entityid'] = settings.SAML2_AUTH['ENTITY_ID']
# # print('entity id ' , settings.SAML2_AUTH['ENTITY_ID'])
# if 'NAME_ID_FORMAT' in settings.SAML2_AUTH:
#     settings['service']['sp']['name_id_format'] = settings.SAML2_AUTH['NAME_ID_FORMAT']
# NOTE-'NAME_ID_FORMAT is set to None above

#settings['entityid'] = "http://www.okta.com/exkih6doyyeNql8wo0h7"
spConfig = Saml2Config()
spConfig.load(settings)
spConfig.allow_unknown_attributes = True
saml_client = Saml2Client(config=spConfig)
return saml_client

class User(UserMixin):

def init(self, user_id):

user = {}

self.id = None

self.first_name = None

self.last_name = None

try:

user = user_store[user_id]

self.id = unicode(user_id)

self.first_name = user[‘first_name’]

self.last_name = user[‘last_name’]

except:

pass

@login_manager.user_loader

def load_user(user_id):

return User(user_id)

#@app.route("/")
#def main_page():

return render_template(‘main_page.html’, idp_dict=metadata_url_for)

@app.route("/saml/sso/<idp_name>", methods=[‘POST’])
def idp_initiated(idp_name):
saml_client = saml_client_for(idp_name)
#certificate = “MIIDpDCCAoygAwIBAgIGAV2TI2WnMA0GCSqGSIb3DQEBCwUAMIGSMQswCQYDVQQGEwJVUzETMBEGA1UECAwKQ2FsaWZvcm5pYTEWMBQGA1UEBwwNU2FuIEZyYW5jaXNjbzENMAsGA1UECgwET2t0YTEUMBI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aUTViH1KNs+qQeTjgKA09FR”
#certificate = “mycert.pem”

authn_response = saml_client.parse_authn_request_response(
                    request.form['SAMLResponse'],
                    entity.BINDING_HTTP_POST)
authn_response.get_identity()
user_info = authn_response.get_subject()
username = user_info.text

# This is what as known as "Just In Time (JIT) provisioning".
# What that means is that, if a user in a SAML assertion
# isn't in the user store, we create that user first, then log them in
if username not in user_store:
    user_store[username] = {
        'first_name': authn_response.ava['FirstName'][0],
        'last_name': authn_response.ava['LastName'][0],
        }
# user = User(username)
# session['saml_attributes'] = authn_response.ava
# login_user(user)
url = url_for('user')
# NOTE:
#   On a production system, the RelayState MUST be checked
#   to make sure it doesn't contain dangerous URLs!
if 'RelayState' in request.form:
    url = request.form['RelayState']
return redirect(url)

@app.route("/saml/login/<idp_name>")
def sp_initiated(idp_name):
print(“in sp flow”)
saml_client = saml_client_for(idp_name)
reqid, info = saml_client.prepare_for_authenticate()

redirect_url = None
# Select the IdP URL to send the AuthN request to
for key, value in info['headers']:
    if key is 'Location':
        redirect_url = value
response = redirect(redirect_url, code=302)
# NOTE:
#   I realize I _technically_ don't need to set Cache-Control or Pragma:
#     http://stackoverflow.com/a/5494469
#   However, Section 3.2.3.2 of the SAML spec suggests they are set:
#     http://docs.oasis-open.org/security/saml/v2.0/saml-bindings-2.0-os.pdf
#   We set those headers here as a "belt and suspenders" approach,
#   since enterprise environments don't always conform to RFCs
response.headers['Cache-Control'] = 'no-cache, no-store'
response.headers['Pragma'] = 'no-cache'
return response

@app.route("/user")

@login_required

def user():

return render_template(‘user.html’, session=session)

@app.errorhandler(401)
def error_unauthorized(error):
return render_template(‘unauthorized.html’)

@app.route("/logout")

@login_required

def logout():

logout_user()

return redirect(url_for(“main_page”))

if name == “main”:
port = int(os.environ.get(‘PORT’, 5000))
if port == 5009:
app.debug = True
app.run(host=‘localhost’, port=port)