Sample code for 30+ languages & platforms
C# Requires Chilkat v11.6.0+

AWS STS: Exchange an OIDC Token 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, role_session_name and the complete web_identity_token from your OIDC provider. The exchange is unsigned: no AWS access key or SigV4 header is sent. Configure the IAM provider and role trust for the expected issuer, audience and subject. STS validates the token; this sample does not treat decoding a JWT as verification. Refresh expired input through your identity provider.

AWS references: AssumeRoleWithWebIdentity

Chilkat C# Downloads

C#
bool success = false;

Chilkat.StringBuilder stringCompare = new Chilkat.StringBuilder();
//  Assumes Chilkat is unlocked. See Global Unlock Sample.
//  Keep this file private and outside public web content/source control.
Chilkat.JsonObject credentials = new Chilkat.JsonObject();
credentials.Strict = true;
success = credentials.LoadFile("qa_data/aws/sts.json");
if (success != true) {
    Debug.WriteLine("Could not load private STS configuration.");
    return;
}

Chilkat.CkDateTime expires = new Chilkat.CkDateTime();
Chilkat.CkDateTime now = new Chilkat.CkDateTime();
string region = "us-west-2";
stringCompare.SetString(credentials.StringOf("role_arn"));
bool stringMatch1 = stringCompare.ContentsEqual("",true);
if ((credentials.JsonTypeOf("role_arn") != 1) || (stringMatch1 == true)) {
    Debug.WriteLine("Missing or invalid role_arn.");
    return;
}

stringCompare.SetString(credentials.StringOf("role_session_name"));
bool stringMatch2 = stringCompare.ContentsEqual("",true);
if ((credentials.JsonTypeOf("role_session_name") != 1) || (stringMatch2 == true)) {
    Debug.WriteLine("Missing or invalid role_session_name.");
    return;
}

Chilkat.StringBuilder identifier = new Chilkat.StringBuilder();
identifier.Append(credentials.StringOf("role_session_name"));
if ((identifier.Length < 2) || (identifier.Length > 64)) {
    Debug.WriteLine("role_session_name must have 2-64 characters.");
    return;
}

Chilkat.StringBuilder allowed = new Chilkat.StringBuilder();
allowed.Append("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_+=,.@-");
int charIndex = 0;
while ((charIndex < identifier.Length)) {
    if (allowed.Contains(identifier.GetRange(charIndex,1,false),true) != true) {
        Debug.WriteLine("Invalid character in role_session_name.");
        return;
    }

    charIndex = charIndex + 1;
}

stringCompare.SetString(credentials.StringOf("web_identity_token"));
bool stringMatch3 = stringCompare.ContentsEqual("",true);
if ((credentials.JsonTypeOf("web_identity_token") != 1) || (stringMatch3 == true)) {
    Debug.WriteLine("Missing or invalid web_identity_token.");
    return;
}

Chilkat.StringBuilder endpoint = new Chilkat.StringBuilder();
endpoint.Append("sts.");
endpoint.Append(region);
endpoint.Append(".amazonaws.com");
Chilkat.Rest rest = new Chilkat.Rest();
rest.ConnectTimeoutMs = 20000;
rest.IdleTimeoutMs = 60000;
rest.VerboseLogging = false;
//  Keep this verified Socket alive while Rest uses its connection.
Chilkat.Socket connection = new Chilkat.Socket();
connection.RequireSslCertVerify = true;
connection.MaxReadIdleMs = 60000;
connection.MaxSendIdleMs = 60000;
success = connection.Connect(endpoint.GetAsString(),443,true,20000);
if (success != true) {
    Debug.WriteLine("TLS connection failed; inspect diagnostics privately.");
    return;
}

success = rest.UseConnection(connection,true);
if (success != true) {
    Debug.WriteLine("Could not attach TLS connection.");
    return;
}

Chilkat.Xml xml = new Chilkat.Xml();
xml.Strict = true;
string value;
string accessKey;
string secretKey;
string sessionToken;
string expiration;
string responseXml = "";
success = rest.ClearAllQueryParams();
if (success != true) {
    Debug.WriteLine("Could not reset request parameters.");
    return;
}

success = rest.AddQueryParam("Action","AssumeRoleWithWebIdentity");
if (success != true) {
    Debug.WriteLine("Could not set Action.");
    return;
}

success = rest.AddQueryParam("Version","2011-06-15");
if (success != true) {
    Debug.WriteLine("Could not set Version.");
    return;
}

success = rest.AddQueryParam("RoleArn",credentials.StringOf("role_arn"));
if (success != true) {
    Debug.WriteLine("Could not set RoleArn.");
    return;
}

success = rest.AddQueryParam("RoleSessionName",credentials.StringOf("role_session_name"));
if (success != true) {
    Debug.WriteLine("Could not set RoleSessionName.");
    return;
}

success = rest.AddQueryParam("DurationSeconds","3600");
if (success != true) {
    Debug.WriteLine("Could not set DurationSeconds.");
    return;
}

success = rest.AddQueryParam("WebIdentityToken",credentials.StringOf("web_identity_token"));
if (success != true) {
    Debug.WriteLine("Could not set WebIdentityToken.");
    return;
}

responseXml = rest.FullRequestFormUrlEncoded("POST","/");
if (rest.LastMethodSuccess != true) {
    Debug.WriteLine("STS transport failed; inspect diagnostics privately.");
    return;
}

if (rest.ResponseStatusCode != 200) {
    Debug.WriteLine("STS HTTP status: " + Convert.ToString(rest.ResponseStatusCode));
    success = xml.LoadXml(responseXml);
    if (success == true) {
        value = xml.GetChildContent("Error|Code");
        if (xml.LastMethodSuccess == true) {
            Debug.WriteLine("AWS error code: " + value);
        }

        value = xml.GetChildContent("RequestId");
        if (xml.LastMethodSuccess == true) {
            Debug.WriteLine("AWS request ID: " + value);
        }

    }

    return;
}

success = xml.LoadXml(responseXml);
if (success != true) {
    Debug.WriteLine("Invalid STS XML response.");
    return;
}

stringCompare.SetString(xml.Tag);
bool stringMatch4 = stringCompare.ContentsEqual("AssumeRoleWithWebIdentityResponse",true);
if (stringMatch4 != true) {
    Debug.WriteLine("Unexpected STS response root.");
    return;
}

value = xml.GetChildContent("ResponseMetadata|RequestId");
stringCompare.SetString(value);
bool stringMatch5 = stringCompare.ContentsEqual("",true);
if ((xml.LastMethodSuccess != true) || (stringMatch5 == true)) {
    Debug.WriteLine("Missing or empty ResponseMetadata|RequestId.");
    return;
}

if (xml.HasChildWithTag("AssumeRoleWithWebIdentityResult") != true) {
    Debug.WriteLine("Missing STS result.");
    return;
}

accessKey = xml.GetChildContent("AssumeRoleWithWebIdentityResult|Credentials|AccessKeyId");
stringCompare.SetString(accessKey);
bool stringMatch6 = stringCompare.ContentsEqual("",true);
if ((xml.LastMethodSuccess != true) || (stringMatch6 == true)) {
    Debug.WriteLine("Missing or empty AssumeRoleWithWebIdentityResult|Credentials|AccessKeyId.");
    return;
}

secretKey = xml.GetChildContent("AssumeRoleWithWebIdentityResult|Credentials|SecretAccessKey");
stringCompare.SetString(secretKey);
bool stringMatch7 = stringCompare.ContentsEqual("",true);
if ((xml.LastMethodSuccess != true) || (stringMatch7 == true)) {
    Debug.WriteLine("Missing or empty AssumeRoleWithWebIdentityResult|Credentials|SecretAccessKey.");
    return;
}

sessionToken = xml.GetChildContent("AssumeRoleWithWebIdentityResult|Credentials|SessionToken");
stringCompare.SetString(sessionToken);
bool stringMatch8 = stringCompare.ContentsEqual("",true);
if ((xml.LastMethodSuccess != true) || (stringMatch8 == true)) {
    Debug.WriteLine("Missing or empty AssumeRoleWithWebIdentityResult|Credentials|SessionToken.");
    return;
}

expiration = xml.GetChildContent("AssumeRoleWithWebIdentityResult|Credentials|Expiration");
stringCompare.SetString(expiration);
bool stringMatch9 = stringCompare.ContentsEqual("",true);
if ((xml.LastMethodSuccess != true) || (stringMatch9 == true)) {
    Debug.WriteLine("Missing or empty AssumeRoleWithWebIdentityResult|Credentials|Expiration.");
    return;
}

success = expires.SetFromTimestamp(expiration);
if (success != true) {
    Debug.WriteLine("Returned expiration is invalid.");
    return;
}

success = now.SetFromCurrentSystemTime();
if (success != true) {
    Debug.WriteLine("Could not read current time.");
    return;
}

if (expires.DiffSeconds(now) <= 60) {
    Debug.WriteLine("Returned credentials are expired or expire within 60 seconds; obtain fresh credentials.");
    return;
}

value = xml.GetChildContent("AssumeRoleWithWebIdentityResult|AssumedRoleUser|Arn");
stringCompare.SetString(value);
bool stringMatch10 = stringCompare.ContentsEqual("",true);
if ((xml.LastMethodSuccess != true) || (stringMatch10 == true)) {
    Debug.WriteLine("Missing or empty AssumeRoleWithWebIdentityResult|AssumedRoleUser|Arn.");
    return;
}

value = xml.GetChildContent("AssumeRoleWithWebIdentityResult|AssumedRoleUser|AssumedRoleId");
stringCompare.SetString(value);
bool stringMatch11 = stringCompare.ContentsEqual("",true);
if ((xml.LastMethodSuccess != true) || (stringMatch11 == true)) {
    Debug.WriteLine("Missing or empty AssumeRoleWithWebIdentityResult|AssumedRoleUser|AssumedRoleId.");
    return;
}

Chilkat.JsonObject session = new Chilkat.JsonObject();
success = session.UpdateString("access_key",accessKey);
if (success != true) {
    Debug.WriteLine("Could not build complete session.");
    return;
}

success = session.UpdateString("secret_key",secretKey);
if (success != true) {
    Debug.WriteLine("Could not build complete session.");
    return;
}

success = session.UpdateString("session_token",sessionToken);
if (success != true) {
    Debug.WriteLine("Could not build complete session.");
    return;
}

success = session.UpdateString("expiration",expiration);
if (success != true) {
    Debug.WriteLine("Could not build complete session.");
    return;
}

//  Use session in memory; do not print or log session.Emit().
Debug.WriteLine("Session validated; expiration: " + expiration);
Debug.WriteLine("Example completed.");