How to use assume_role_with_saml method in localstack

Best Python code snippet using localstack_python

server.py

Source:server.py Github

copy

Full Screen

...7from pprint import pprint8import boto39sts = boto3.client('sts')10accounts_by_number = {}11def assume_role_with_saml(saml_response: str, role_arn: str, principal_name: str) -> Path:12 account_number = re.search(r'(\d+)', role_arn).group(0)13 response = sts.assume_role_with_saml(14 RoleArn=role_arn,15 PrincipalArn='arn:aws:iam::{account}:saml-provider/{PrincipalName}'.format(16 account=account_number, PrincipalName=principal_name17 ),18 SAMLAssertion=saml_response,19 DurationSeconds=3600 * 1220 )21 pprint(response)22 credentials = response['Credentials']23 credentials_ini = (pathlib.Path.home() / '.aws' / 'credentials')24 cp = ConfigParser()25 cp.read(credentials_ini)26 account_name = accounts_by_number.get(account_number, account_number)27 for section in {'default', account_name}:28 cp.remove_section(section)29 cp.add_section(section)30 cp.set(section, 'aws_access_key_id', credentials['AccessKeyId'])31 cp.set(section, 'aws_secret_access_key', credentials['SecretAccessKey'])32 cp.set(section, 'aws_session_token', credentials['SessionToken'])33 with open(credentials_ini, mode='w') as fo:34 cp.write(fo)35 return credentials_ini36class MyHttpRequestHandler(SimpleHTTPRequestHandler):37 principal_name: str38 def do_POST(self):39 content_length = int(self.headers['Content-Length'])40 request_body = self.rfile.read(content_length).decode('utf-8')41 print(request_body)42 request_dict = json.loads(request_body)43 pprint(request_dict)44 if self.path == '/saml':45 status = 20046 try:47 credentials_ini = assume_role_with_saml(48 request_dict['SAMLResponse'], request_dict['roleARN'], self.principal_name49 )50 body = {'credentials_ini': str(credentials_ini)}51 except Exception as e:52 status = 40053 body = {'error': str(e)}54 self.send_response(status)55 self.send_header('Access-Control-Allow-Origin', '*')56 self.send_header('Content-type', 'application/json')57 self.end_headers()58 self.wfile.write(bytes(json.dumps(body), encoding='utf8'))59 else:60 self.send_error(404, self.path)61def run(identity_provider_name: str):...

Full Screen

Full Screen

conftest.py

Source:conftest.py Github

copy

Full Screen

1from datetime import datetime, timedelta2import copy3import logging4import mock5import pytest6from dateutil.tz import tzlocal7from tests import create_assertion8@pytest.fixture9def mock_botocore_client():10 return mock.Mock()11@pytest.fixture12def client_creator(mock_botocore_client):13 # Create a mock sts client that returns a specific response14 # for assume_role_with_saml.15 expiration = datetime.now(tzlocal()) + timedelta(days=1)16 mock_botocore_client.assume_role_with_saml.return_value = {17 'Credentials': {18 'AccessKeyId': 'foo',19 'SecretAccessKey': 'bar',20 'SessionToken': 'baz',21 'Expiration': expiration22 },23 }24 return mock.Mock(return_value=mock_botocore_client)25@pytest.fixture26def prompter():27 return mock.Mock(return_value='mypassword')28@pytest.fixture29def login_form():30 return (31 '<html>'32 '<form action="login">'33 '<input name="username"/>'34 '<input name="password"/>'35 '</form>'36 '</html>'37 )38@pytest.fixture(params=[39 {'reversed': False},40 {'reversed': True}41])42def assertion(request):43 provider_arn = 'arn:aws:iam::123456789012:saml-provider/Example'44 role_arn = 'arn:aws:iam::123456789012:role/monty'45 is_reversed = request.param.get('reversed', False)46 if not is_reversed:47 config_string = '%s,%s' % (provider_arn, role_arn)48 else:49 config_string = '%s,%s' % (role_arn, provider_arn)50 return create_assertion([config_string])51@pytest.fixture(autouse=True)52def reset_logger():53 """Makes sure that mutations to the logger don't persist between tests."""54 logger = logging.getLogger('awsprocesscreds')55 original_level = logger.level56 original_handlers = copy.copy(logger.handlers)57 original_filters = copy.copy(logger.filters)58 # Everything after the yield will be called during test cleanup.59 yield60 logger.setLevel(original_level)61 for handler in logger.handlers:62 if handler not in original_handlers:63 logger.removeHandler(handler)64 for log_filter in logger.filters:65 if log_filter not in original_filters:66 logger.removeFilter(log_filter)67@pytest.fixture68def cache_dir(tmpdir):69 cache_directory = tmpdir.mkdir('awscreds-saml-cache')...

Full Screen

Full Screen

__main__.py

Source:__main__.py Github

copy

Full Screen

1#2# Copyright 2019 - binx.io B.V.3#4# Licensed under the Apache License, Version 2.0 (the "License");5# you may not use this file except in compliance with the License.6# You may obtain a copy of the License at7#8# http://www.apache.org/licenses/LICENSE-2.09#10# Unless required by applicable law or agreed to in writing, software11# distributed under the License is distributed on an "AS IS" BASIS,12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13# See the License for the specific language governing permissions and14# limitations under the License.15#16import logging17import click18from auth0_login import fatal19from auth0_login.aws import assume_role_with_saml20from auth0_login.config import setting21from auth0_login.saml import get_saml_token22@click.group(name='saml-login', help="A command line utility to obtain SAML tokens and AWS credentials.")23@click.option('--verbose', is_flag=True, default=False, help=' for tracing purposes')24@click.option('--configuration', '-c', default="DEFAULT", help='configured in .saml-login to use')25def cli(verbose, configuration):26 logging.basicConfig(format='%(levelname)s:%(message)s', level=(logging.DEBUG if verbose else logging.INFO))27 setting.filename = '.saml-login'28 setting.SECTION = configuration29 if not setting.exists:30 fatal('no configuration %s found in %s', configuration, setting.filename)31cli.add_command(get_saml_token)32cli.add_command(assume_role_with_saml)33if __name__ == '__main__':...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run localstack automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful