2: Security

    Identity Federation with SAML, OpenID Connect, and Amazon Cognito

    Identity federation moves the burden of authenticating a user away from the application and onto an external identity provider, then converts that external assertion into AWS credentials or an application session. Two reasons dominate the developer's choice. First, the workforce already has identities in Active Directory, Okta, Microsoft Entra ID, Google Workspace, or another corporate IdP, and reissuing them inside IAM would create a parallel user database that drifts on every hire and leaver. Second, the application is consumer-facing and expects users to sign in with Google, Apple, Facebook, or a custom OIDC provider, which makes embedded password handling a liability rather than a feature.

    The DVA-C02 angle is the integration point: which AWS service exchanges the IdP assertion for credentials, which credential type the application receives, and how the workload protects the data once the session begins. AWS exposes three integration paths. SAML 2.0 federation routes the SAML assertion to AWS STS through AssumeRoleWithSAML, returning short-lived IAM credentials for a role. OpenID Connect federation routes an OIDC ID token to STS through AssumeRoleWithWebIdentity for direct role assumption, or to Cognito identity pools for credential vending. Cognito itself can act as the federation broker, where a Cognito user pool hosts users locally or federates them out to SAML and OIDC providers, then issues its own JWTs that downstream services validate.

    The role of the OIDC discovery document and the SAML metadata XML deserves real attention. Both files publish the issuer URL, the signing keys, the supported algorithms, and (for OIDC) the endpoints for the authorization, token, and userinfo flows. When you configure an OIDC identity provider in IAM with aws iam create-open-id-connect-provider, AWS pulls the discovery document, validates the certificate thumbprint of the JWKS host, and stores the issuer URL. Any subsequent token whose iss claim does not match exactly fails the trust policy. The thumbprint requirement catches developers off guard when an IdP rotates its TLS certificate; the IAM OIDC provider must be updated with the new thumbprint or the token exchange begins to fail. SAML behaves differently: you upload a static XML metadata file, and renewing the IdP signing certificate inside that metadata is a manual upload step.

    A federation flow with STS looks like this. The browser is sent to the IdP, the user authenticates, and the IdP responds with a SAML assertion (POST binding to an AWS sign-in endpoint) or with an OIDC authorization code that the application redeems for an ID token. The application calls sts:AssumeRoleWithSAML (passing the SAML assertion and a role ARN) or sts:AssumeRoleWithWebIdentity (passing the OIDC token and a role ARN). STS validates the assertion or token against the registered IdP, evaluates the role's trust policy, and returns temporary credentials with a maximum session duration set by MaxSessionDuration on the role, between 15 minutes and 12 hours. The application then signs subsequent AWS API calls with those credentials.

    import boto3, requests
    
    # OIDC token comes from the IdP authorization-code flow handled earlier.
    oidc_token = "eyJraWQiOiJrZXkx..."
    
    sts = boto3.client("sts")
    resp = sts.assume_role_with_web_identity(
     RoleArn="arn:aws:iam::111122223333:role/AppFederatedRole",
     RoleSessionName="user-1234",
     WebIdentityToken=oidc_token,
     DurationSeconds=3600,
    )
    creds = resp["Credentials"]
    # AccessKeyId, SecretAccessKey, SessionToken, Expiration
    

    The matching trust policy on AppFederatedRole pins both the OIDC provider and a token claim so that the role cannot be assumed by any valid token from that IdP.

    {
     "Version": "2012-10-17",
     "Statement": [{
     "Effect": "Allow",
     "Principal": { "Federated": "arn:aws:iam::111122223333:oidc-provider/auth.example.com" },
     "Action": "sts:AssumeRoleWithWebIdentity",
     "Condition": {
     "StringEquals": {
     "auth.example.com:aud": "app-client-id-9876",
     "auth.example.com:sub": "user-1234"
     }
     }
     }]
    }
    

    Encryption at Rest and in Transit

    Federation only solves who the user is. The data they read and write still has to be encrypted at rest and in transit. Encryption at rest in AWS is keyed by KMS in nearly every managed data store: S3 with SSE-S3, SSE-KMS, or SSE-C; DynamoDB with the AWS-managed key or a customer-managed key; RDS and Aurora with KMS-encrypted volumes; EBS volumes with KMS keys; and Secrets Manager and Parameter Store SecureString parameters with KMS as well. The developer-facing decision is which key the SDK call references. Passing ServerSideEncryption="aws:kms" and SSEKMSKeyId="arn:aws:kms:us-east-1:111122223333:key/abcd-1234" on s3:PutObject writes the object under a customer-managed key, which lets you control rotation, regional access, and grants without involving the bucket policy alone.

    Encryption in transit defaults to TLS for AWS API calls. The SDKs hard-code HTTPS, the endpoints are signed certificates issued by Amazon Trust Services, and the developer rarely needs to touch the TLS layer for service-to-service traffic inside AWS. Internet-facing applications behind Application Load Balancer, CloudFront, or API Gateway present certificates that you typically provision through AWS Certificate Manager. Application traffic between two internal services (a Lambda function calling a private API hosted on ALB inside a VPC, for example) can either use the AWS Trust Services chain through *.amazonaws.com endpoints or use a private certificate issued by AWS Private CA.

    💡 Exam Trap: AssumeRoleWithSAML and AssumeRoleWithWebIdentity do not require pre-existing IAM users; the role's trust policy IS the only authorization gate. Setting the trust policy with a wildcard principal and no Condition block lets any valid token from the IdP assume the role, which the exam frames as a least-privilege violation.

    💡 Exam Trap: Encrypting an S3 object with a customer-managed KMS key requires the caller to hold both s3:PutObject on the bucket and kms:GenerateDataKey on the key. Granting only the S3 permission produces an AccessDenied from KMS, not S3, and learners often misread the error as a bucket policy problem.

    Secure Credential Handling for Application Use

    Once federation hands an application short-lived credentials, the application has to use them safely. Three principles cover almost every exam scenario. First, keep credentials in memory or in the SDK credential provider chain, not in disk files committed to source control. The SDKs read AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, and AWS_SESSION_TOKEN from the environment, then ~/.aws/credentials, then the EC2 instance metadata service, then the ECS container credentials endpoint. On Lambda, App Runner, and ECS Fargate, the runtime injects credentials by setting these variables for the function's execution role automatically. Second, refresh credentials before expiry. The SDK does this for instance-metadata-sourced credentials transparently, but manually-managed credentials require the application to detect expiry from Expiration and call STS again. Third, never log credentials. The SDK middlewares mask them, but custom debug logging that prints the full request body can leak the Authorization header.

    # Wrong: leaks the access key in the log line, which propagates to CloudWatch.
    print(f"calling with creds {creds['AccessKeyId']} / {creds['SecretAccessKey']}")
    
    # Right: log only the identity, never the secret.
    identity = boto3.client("sts").get_caller_identity()
    print(f"calling under {identity['Arn']}")
    

    ⚠️ Anti-Pattern: Storing the SAML assertion or OIDC ID token in browser local storage so that it can be replayed across tabs. The token grants role-assumption rights for its lifetime; treating it as a persistent session cookie expands the blast radius of an XSS payload to the entire IAM trust chain. Keep the token in memory and refresh through the IdP.

    🎯 Scenario: An internal application authenticates corporate users through Okta SAML. The backend currently stores an IAM user access key on each EC2 instance and signs API calls with it. The team wants to drop the long-lived keys. The fix is to register Okta as a SAML IdP in IAM, create a role with a trust policy keyed on the Okta IdP ARN and a SAML attribute (saml:aud), have the application call AssumeRoleWithSAML with the assertion the user already produced, and sign subsequent AWS calls with the temporary credentials STS returns.

    📊 Limit: STS AssumeRoleWithWebIdentity session duration is bounded by the role's MaxSessionDuration, which itself ranges from 900 seconds to 43,200 seconds (15 minutes to 12 hours). Role chaining (one assumed role assuming another) caps at 3,600 seconds regardless of MaxSessionDuration.

    Decision Anchor: Choose direct STS federation when the application speaks AWS APIs from a backend the user does not see (a Lambda function, a worker pulling from SQS) and the IdP can be modeled as a SAML or OIDC provider. Choose Cognito federation when the application is end-user-facing, needs sign-up flows, hosted UI, MFA, or social logins, and the AWS credential vending is incidental to a richer authentication experience.


    Continue with the interactive course

    Track your progress, jump into practice questions and use the Shark AI tutor inside the AWS - Developer Associate learning hub.