AWS STS: Exchange a SAML Assertion for Role Credentials
See more AWS Security Token Service Examples
Uses the AWS STS Query API version 2011-06-15 and a verified TLS connection to the commercial-partition regional endpoint sts.us-west-2.amazonaws.com. Change the endpoint and signing region together for your deployment. Assumes Chilkat is unlocked.
Keep qa_data/aws/sts.json private and outside web roots/source control. Signed examples require nonempty access_key and secret_key strings; temporary source credentials also require session_token and ISO 8601 expiration. Federation exchanges load their specific fields without AWS keys. The examples do not print credentials, bearer tokens, full responses or diagnostic dumps. Credential-producing examples build a complete in-memory session object with access_key, secret_key, session_token and expiration; integrate that object into your application before it goes out of scope.
Provide role_arn, principal_arn for the IAM SAML provider, and saml_assertion containing the complete base64-encoded SAML response supplied by your IdP. Do not base64-encode it a second time. Uses unsigned POST with no AWS keys. The IdP metadata, role claims and trust must already be configured. STS verifies the assertion. The session can end sooner than the requested hour due to SessionNotOnOrAfter. IAM Identity Center AWSReservedSSO_ roles are not supported by this operation.
AWS references: AssumeRoleWithSAML
Chilkat Dart Downloads
import 'package:chilkat/chilkat.dart';
void main() {
final stringCompare = CkStringBuilder();
// Assumes Chilkat is unlocked. See Global Unlock Sample.
// Keep this file private and outside public web content/source control.
final credentials = CkJsonObject();
credentials.strict = true;
try {
credentials.loadFile('qa_data/aws/sts.json');
} on ChilkatException {
print('Could not load private STS configuration.');
return;
}
final expires = CkDateTime();
final now = CkDateTime();
final region = 'us-west-2';
stringCompare.setString(credentials.stringOf('role_arn'));
final stringMatch1 = stringCompare.contentsEqual('', true);
if ((credentials.jsonTypeOf('role_arn') != 1) || (stringMatch1)) {
print('Missing or invalid role_arn.');
return;
}
stringCompare.setString(credentials.stringOf('principal_arn'));
final stringMatch2 = stringCompare.contentsEqual('', true);
if ((credentials.jsonTypeOf('principal_arn') != 1) || (stringMatch2)) {
print('Missing or invalid principal_arn.');
return;
}
stringCompare.setString(credentials.stringOf('saml_assertion'));
final stringMatch3 = stringCompare.contentsEqual('', true);
if ((credentials.jsonTypeOf('saml_assertion') != 1) || (stringMatch3)) {
print('Missing or invalid saml_assertion.');
return;
}
final endpoint = CkStringBuilder();
endpoint.append('sts.');
endpoint.append(region);
endpoint.append('.amazonaws.com');
final rest = CkRest();
rest.connectTimeoutMs = 20000;
rest.idleTimeoutMs = 60000;
rest.verboseLogging = false;
// Keep this verified Socket alive while Rest uses its connection.
final connection = CkSocket();
connection.requireSslCertVerify = true;
connection.maxReadIdleMs = 60000;
connection.maxSendIdleMs = 60000;
try {
connection.connect(endpoint.getAsString(), 443, true, 20000);
} on ChilkatException {
print('TLS connection failed; inspect diagnostics privately.');
return;
}
try {
rest.useConnection(connection, true);
} on ChilkatException {
print('Could not attach TLS connection.');
return;
}
final xml = CkXml();
xml.strict = true;
var value = '';
var responseXml = '';
try {
rest.clearAllQueryParams();
} on ChilkatException {
print('Could not reset request parameters.');
return;
}
try {
rest.addQueryParam('Action', 'AssumeRoleWithSAML');
} on ChilkatException {
print('Could not set Action.');
return;
}
try {
rest.addQueryParam('Version', '2011-06-15');
} on ChilkatException {
print('Could not set Version.');
return;
}
try {
rest.addQueryParam('RoleArn', credentials.stringOf('role_arn'));
} on ChilkatException {
print('Could not set RoleArn.');
return;
}
try {
rest.addQueryParam('PrincipalArn', credentials.stringOf('principal_arn'));
} on ChilkatException {
print('Could not set PrincipalArn.');
return;
}
try {
rest.addQueryParam('SAMLAssertion', credentials.stringOf('saml_assertion'));
} on ChilkatException {
print('Could not set SAMLAssertion.');
return;
}
try {
rest.addQueryParam('DurationSeconds', '3600');
} on ChilkatException {
print('Could not set DurationSeconds.');
return;
}
try {
responseXml = rest.fullRequestFormUrlEncoded('POST', '/');
} on ChilkatException {
print('STS transport failed; inspect diagnostics privately.');
return;
}
if (rest.responseStatusCode != 200) {
print('STS HTTP status: ${rest.responseStatusCode}');
try {
xml.loadXml(responseXml);
try {
value = xml.getChildContent('Error|Code');
print('AWS error code: $value');
} on ChilkatException {
// xml.getChildContent() failed; continue anyway.
}
try {
value = xml.getChildContent('RequestId');
print('AWS request ID: $value');
} on ChilkatException {
// xml.getChildContent() failed; continue anyway.
}
} on ChilkatException {
// xml.loadXml() failed; continue anyway.
}
return;
}
try {
xml.loadXml(responseXml);
} on ChilkatException {
print('Invalid STS XML response.');
return;
}
stringCompare.setString(xml.tag);
final stringMatch4 = stringCompare.contentsEqual('AssumeRoleWithSAMLResponse', true);
if (!stringMatch4) {
print('Unexpected STS response root.');
return;
}
value = xml.getChildContent('ResponseMetadata|RequestId');
stringCompare.setString(value);
final stringMatch5 = stringCompare.contentsEqual('', true);
if ((!xml.lastMethodSuccess) || (stringMatch5)) {
print('Missing or empty ResponseMetadata|RequestId.');
return;
}
if (!xml.hasChildWithTag('AssumeRoleWithSAMLResult')) {
print('Missing STS result.');
return;
}
final accessKey = xml.getChildContent('AssumeRoleWithSAMLResult|Credentials|AccessKeyId');
stringCompare.setString(accessKey);
final stringMatch6 = stringCompare.contentsEqual('', true);
if ((!xml.lastMethodSuccess) || (stringMatch6)) {
print('Missing or empty AssumeRoleWithSAMLResult|Credentials|AccessKeyId.');
return;
}
final secretKey = xml.getChildContent('AssumeRoleWithSAMLResult|Credentials|SecretAccessKey');
stringCompare.setString(secretKey);
final stringMatch7 = stringCompare.contentsEqual('', true);
if ((!xml.lastMethodSuccess) || (stringMatch7)) {
print('Missing or empty AssumeRoleWithSAMLResult|Credentials|SecretAccessKey.');
return;
}
final sessionToken = xml.getChildContent('AssumeRoleWithSAMLResult|Credentials|SessionToken');
stringCompare.setString(sessionToken);
final stringMatch8 = stringCompare.contentsEqual('', true);
if ((!xml.lastMethodSuccess) || (stringMatch8)) {
print('Missing or empty AssumeRoleWithSAMLResult|Credentials|SessionToken.');
return;
}
final expiration = xml.getChildContent('AssumeRoleWithSAMLResult|Credentials|Expiration');
stringCompare.setString(expiration);
final stringMatch9 = stringCompare.contentsEqual('', true);
if ((!xml.lastMethodSuccess) || (stringMatch9)) {
print('Missing or empty AssumeRoleWithSAMLResult|Credentials|Expiration.');
return;
}
try {
expires.setFromTimestamp(expiration);
} on ChilkatException {
print('Returned expiration is invalid.');
return;
}
try {
now.setFromCurrentSystemTime();
} on ChilkatException {
print('Could not read current time.');
return;
}
if (expires.diffSeconds(now) <= 60) {
print('Returned credentials are expired or expire within 60 seconds; obtain fresh credentials.');
return;
}
value = xml.getChildContent('AssumeRoleWithSAMLResult|AssumedRoleUser|Arn');
stringCompare.setString(value);
final stringMatch10 = stringCompare.contentsEqual('', true);
if ((!xml.lastMethodSuccess) || (stringMatch10)) {
print('Missing or empty AssumeRoleWithSAMLResult|AssumedRoleUser|Arn.');
return;
}
value = xml.getChildContent('AssumeRoleWithSAMLResult|AssumedRoleUser|AssumedRoleId');
stringCompare.setString(value);
final stringMatch11 = stringCompare.contentsEqual('', true);
if ((!xml.lastMethodSuccess) || (stringMatch11)) {
print('Missing or empty AssumeRoleWithSAMLResult|AssumedRoleUser|AssumedRoleId.');
return;
}
final session = CkJsonObject();
try {
session.updateString('access_key', accessKey);
} on ChilkatException {
print('Could not build complete session.');
return;
}
try {
session.updateString('secret_key', secretKey);
} on ChilkatException {
print('Could not build complete session.');
return;
}
try {
session.updateString('session_token', sessionToken);
} on ChilkatException {
print('Could not build complete session.');
return;
}
try {
session.updateString('expiration', expiration);
} on ChilkatException {
print('Could not build complete session.');
return;
}
// Use session in memory; do not print or log session.Emit().
print('Session validated; expiration: $expiration');
print('Example completed.');
}