Skip to content

Lightweight AWS Cognito Identity Provider client for Kotlin Multiplatform and Typescript projects.

License

Notifications You must be signed in to change notification settings

Liftric/cognito-idp

Repository files navigation

CI maven-central OSS Sonatype (Releases) npm (scoped) platforms

Cognito-idp

Lightweight AWS Cognito Identity Provider client for Kotlin Multiplatform and Typescript projects.

Not all requests, errors, and auth flows are implemented.
Feel free to contribute if there is something missing for you.

Version 2 introduced breaking changes, please refer to the migration document for help.

Import

Kotlin

Gradle

sourceSets {
    val commonMain by getting {
        dependencies {
            implementation("com.liftric:cognito-idp:<version>")
        }
    }
}

Typescript

Yarn

yarn add @liftric/cognito-idp@<version>

npm

npm i @liftric/cognito-idp@<version>

How-to

Init

Kotlin

val provider = IdentityProviderClient("<region>", "<clientId>") 

Typescript

import {IdentityProviderClientJS} from '@liftric/cognito-idp';

const provider = new IdentityProviderClientJS('<region>', '<clientId>');

Usage

Kotlin

All methods are suspending and return a Result<T>, which wraps the desired object T on success or a Throwable on failure.

provider.signUp("user", "password").fold(
    onSuccess = {
        // Do something
    },
    onFailure = {
        // Handle exceptions
    }
)

Typescript

All methods return a Promise object.

Errors

Request related exceptions are defined as a sealed class of type IdentityProviderException. They contain the http status code and the message. Common AWS exceptions are implemented as subclasses. In case that we don't have implemented the exception type it will default to IdentityProviderException.Unknown, which will contain the AWS exception type.

Network related exceptions (e.g. no internet) are of type IOException.

Requests

Sign Up

Signs up the user.

Attributes are optional.

val attribute = UserAttribute("email", "[email protected]")
signUp("<username>", "<password>", listOf(attribute)): Result<SignUpResponse>

Confirm Sign Up

Confirms the sign up (also the delivery medium).

confirmSignUp("<username>", "<confirmationCode>"): Result<Unit>

Resend Confirmation Code

Resends the confirmation code.

resendConfirmationCode("<username>"): Result<CodeDeliveryDetails>

Sign In

Signs in the users.

signIn("<username>", "<password>"): Result<SignInResponse>

Respond To Auth Challenge

Responds to the auth challenge of the sign in response.

val challengeResponses = mapOf<String, String>()
respondToAuthChallenge("<challengeName>", challengeResponses, "<session>"): Result<SignInResponse>

Refresh access token

Refreshes access token based on refresh token that's retrieved from an earlier sign in.

val signInResponse: SignInResponse = ... // from earlier login or refresh
val refreshToken = signInResponse.AuthenticationResult.RefreshToken
refresh(refreshToken): Result<SignInResponse>

Get Claims

You can retrieve the claims of both the IdTokens' and AccessTokens' payload by converting them to either a CognitoIdToken or CognitoAccessToken

val idToken = CognitoIdToken(idTokenString)
val phoneNumber = idToken.claims.phoneNumber
val sub = idToken.claims.sub

Custom attributes of the IdToken get mapped into customAttributes.

You have to drop the custom: prefix.

val twitter = idToken.claims.customAttributes["twitter"]

Get User

Returns the users attributes and metadata on success.

More info about this in the official documentation.

getUser("<accessToken>"): Result<GetUserResponse>

Update User Attributes

Updates the users attributes (e.g. email, phone number, ...).

val attributes: List<UserAttribute> = ...
updateUserAttributes("<accessToken>", attributes): Result<UpdateUserAttributesResponse>

Change Password

Updates the users password

changePassword("<accessToken>", "<currentPassword>", "<newPassword>"): Result<Unit>

Forgot Password

Invokes password forgot and sends a confirmation code the the users' delivery medium.

More info about the ForgotPasswordResponse in the official documentation.

forgotPassword("<username>"): Result<ForgotPasswordResponse>

Confirm Forgot Password

Confirms forgot password.

confirmForgotPassword("<confirmationCode>", "<username>", "<newPassword>"): Result<Unit>

Get user Attribute Verification Code

Gets the user attribute verification code for the specified attribute name

getUserAttributeVerificationCode("<accessToken>", "<attributeName>", "<clientMetadata>"): Result<GetAttributeVerificationCodeResponse>

Verify User Attribute

Verifies the specified user attribute.

verifyUserAttribute("<accessToken>", "<attributeName>", "<confirmationCode>"): Result<Unit>

Sign Out

Signs out the user globally.

signOut("<accessToken>"): Result<SignOutResponse>

Revoke Token

Revokes all access tokens generated by the refresh token.

revokeToken("<refreshToken>"): Result<Unit>

Associate Software Token

Associate software token. Either with access token or session (not both).

associateSoftwareToken("<accessToken>", "<session"): Result<AssociateSoftwareTokenResponse>

Verify Software Token

Verifies software token. Either with access token or session (not both).

verifySoftwareToken("<accessToken>", "<friendlyDeviceName>", "<session", "<userCode>"): Result<VerifySoftwareTokenResponse>

Set User MFA Preference

Set MFA preferences.

val smsMfaSettings = null
val softwareTokenMfaSettings = MfaSettings(true, true)
setUserMFAPreference("<accessToken>", smsMfaSettings, softwareTokenMfaSettings): Result<Unit>

Delete User

Deletes the user from the user pool.

deleteUser("<accessToken>"): Result<Unit>

License

Cognito-idp is available under the MIT license. See the LICENSE file for more info.