Comprehensive authentication system with support for sign-up, sign-in, multi-factor authentication, social providers, and user management. Built on Amazon Cognito with full TypeScript support.
import {
signUp, signIn, signOut, getCurrentUser, fetchAuthSession
} from "aws-amplify/auth";For Cognito-specific functionality:
import {
signUp, signIn, signOut, decodeJWT
} from "aws-amplify/auth/cognito";Register new users with email, phone, or username.
/**
* Register a new user account
* @param input - Sign up configuration including username, password, and attributes
* @returns Promise with sign up result and next steps
*/
function signUp(input: SignUpInput): Promise<SignUpOutput>;
interface SignUpInput {
username: string;
password: string;
options?: {
userAttributes?: Record<UserAttributeKey, string>;
validationData?: Record<string, string>;
};
}
interface SignUpOutput {
isSignUpComplete: boolean;
nextStep: AuthNextSignUpStep;
userId?: string;
}
interface AuthNextSignUpStep {
signUpStep: 'CONFIRM_SIGN_UP' | 'DONE';
codeDeliveryDetails?: CodeDeliveryDetails;
}Usage Example:
const { isSignUpComplete, userId, nextStep } = await signUp({
username: "user@example.com",
password: "TempPassword123!",
options: {
userAttributes: {
name: "John Doe",
phone_number: "+1234567890"
}
}
});
if (!isSignUpComplete) {
// User needs to confirm with code sent to email/phone
console.log(`Code sent to: ${nextStep.codeDeliveryDetails?.destination}`);
}Confirm user registration with verification code.
/**
* Confirm user sign up with verification code
* @param input - Username and confirmation code
* @returns Promise with confirmation result
*/
function confirmSignUp(input: ConfirmSignUpInput): Promise<ConfirmSignUpOutput>;
interface ConfirmSignUpInput {
username: string;
confirmationCode: string;
}
interface ConfirmSignUpOutput {
isSignUpComplete: boolean;
nextStep: AuthNextSignUpStep;
}Resend verification code for sign up.
/**
* Resend confirmation code for sign up
* @param input - Username to resend code for
* @returns Promise with code delivery details
*/
function resendSignUpCode(input: ResendSignUpCodeInput): Promise<ResendSignUpCodeOutput>;
interface ResendSignUpCodeInput {
username: string;
}
interface ResendSignUpCodeOutput {
destination?: string;
deliveryMedium?: 'EMAIL' | 'SMS';
attributeName?: string;
}Sign in existing users with various authentication flows.
/**
* Sign in a user with username and password
* @param input - Sign in credentials and options
* @returns Promise with sign in result and next steps
*/
function signIn(input: SignInInput): Promise<SignInOutput>;
interface SignInInput {
username: string;
password?: string;
options?: {
authFlowType?: 'USER_SRP_AUTH' | 'USER_PASSWORD_AUTH' | 'CUSTOM_WITH_SRP' | 'CUSTOM_WITHOUT_SRP';
};
}
interface SignInOutput {
isSignedIn: boolean;
nextStep: AuthNextSignInStep;
}
interface AuthNextSignInStep {
signInStep: 'CONFIRM_SIGN_IN_WITH_SMS_CODE' | 'CONFIRM_SIGN_IN_WITH_TOTP_CODE' | 'CONFIRM_SIGN_IN_WITH_NEW_PASSWORD_REQUIRED' | 'CONFIRM_SIGN_IN_WITH_CUSTOM_CHALLENGE' | 'CONFIRM_SIGN_IN_WITH_PASSWORD' | 'RESET_PASSWORD' | 'DONE';
codeDeliveryDetails?: CodeDeliveryDetails;
missingAttributes?: UserAttributeKey[];
}Usage Example:
const { isSignedIn, nextStep } = await signIn({
username: "user@example.com",
password: "TempPassword123!"
});
if (isSignedIn) {
console.log("User signed in successfully");
} else {
// Handle next step (MFA, password change, etc.)
console.log(`Next step: ${nextStep.signInStep}`);
}Handle multi-step sign in flows including MFA and password changes.
/**
* Confirm sign in for multi-step authentication flows
* @param input - Confirmation details for the current step
* @returns Promise with confirmation result
*/
function confirmSignIn(input: ConfirmSignInInput): Promise<ConfirmSignInOutput>;
interface ConfirmSignInInput {
challengeResponse: string;
options?: {
userAttributes?: Record<UserAttributeKey, string>;
};
}
interface ConfirmSignInOutput {
isSignedIn: boolean;
nextStep: AuthNextSignInStep;
}Automatically sign in after successful sign up.
/**
* Automatically sign in user after sign up confirmation
* @returns Promise with sign in result
*/
function autoSignIn(): Promise<SignInOutput>;Sign in with social providers and OAuth flows.
/**
* Sign in with OAuth provider redirect
* @param input - OAuth provider configuration
* @returns Promise that resolves when redirect is initiated
*/
function signInWithRedirect(input?: SignInWithRedirectInput): Promise<void>;
interface SignInWithRedirectInput {
provider?: 'Google' | 'Facebook' | 'Amazon' | 'Apple' | string;
options?: {
preferPrivateSession?: boolean;
};
}OAuth Callback Handling:
For OAuth flows, you must import the OAuth listener to handle callback redirects:
// Side-effect import - enables OAuth callback handling
import "aws-amplify/auth/enable-oauth-listener";This import enables automatic handling of OAuth redirect callbacks in your application. It should be imported once, typically in your main application file or authentication setup module.
Sign out current user with various options.
/**
* Sign out the current user
* @param input - Sign out options
* @returns Promise that resolves when sign out is complete
*/
function signOut(input?: SignOutInput): Promise<void>;
interface SignOutInput {
global?: boolean;
}Get information about the currently authenticated user.
/**
* Get the current authenticated user
* @returns Promise with current user information
*/
function getCurrentUser(): Promise<AuthUser>;
interface AuthUser {
userId: string;
username: string;
signInDetails?: AuthSignInDetails;
}
interface AuthSignInDetails {
loginId?: string;
authFlowType?: string;
}Retrieve current authentication session and tokens.
/**
* Fetch the current authentication session
* @param options - Options for fetching the session
* @returns Promise with authentication session
*/
function fetchAuthSession(options?: FetchAuthSessionOptions): Promise<AuthSession>;
interface FetchAuthSessionOptions {
forceRefresh?: boolean;
}
interface AuthSession {
tokens?: AuthTokens;
credentials?: AWSCredentials;
identityId?: string;
userSub?: string;
}
interface AuthTokens {
accessToken: JWT;
idToken?: JWT;
refreshToken?: string;
}
interface JWT {
toString(): string;
payload: JWTPayload;
}
interface JWTPayload {
sub: string;
aud: string;
email_verified?: boolean;
iss: string;
cognito:username: string;
given_name?: string;
family_name?: string;
aud: string;
event_id: string;
token_use: 'access' | 'id';
auth_time: number;
exp: number;
iat: number;
}Manage user profile attributes.
/**
* Fetch current user's attributes
* @returns Promise with user attributes
*/
function fetchUserAttributes(): Promise<Record<UserAttributeKey, string>>;
/**
* Update multiple user attributes
* @param input - Attributes to update
* @returns Promise with update results
*/
function updateUserAttributes(input: UpdateUserAttributesInput): Promise<Record<UserAttributeKey, UpdateUserAttributeOutput>>;
/**
* Update a single user attribute
* @param input - Attribute to update
* @returns Promise with update result
*/
function updateUserAttribute(input: UpdateUserAttributeInput): Promise<UpdateUserAttributeOutput>;
interface UpdateUserAttributesInput {
userAttributes: Record<UserAttributeKey, string>;
}
interface UpdateUserAttributeInput {
attributeKey: UserAttributeKey;
value: string;
}
interface UpdateUserAttributeOutput {
isUpdated: boolean;
nextStep: AuthNextUpdateAttributeStep;
}Verify user attributes like email and phone number.
/**
* Send verification code for user attribute
* @param input - Attribute to verify
* @returns Promise with code delivery details
*/
function sendUserAttributeVerificationCode(input: SendUserAttributeVerificationCodeInput): Promise<SendUserAttributeVerificationCodeOutput>;
/**
* Confirm user attribute with verification code
* @param input - Attribute and confirmation code
* @returns Promise when confirmation is complete
*/
function confirmUserAttribute(input: ConfirmUserAttributeInput): Promise<void>;
interface SendUserAttributeVerificationCodeInput {
userAttributeKey: VerifiableUserAttributeKey;
}
interface ConfirmUserAttributeInput {
userAttributeKey: VerifiableUserAttributeKey;
confirmationCode: string;
}Reset and update user passwords.
/**
* Initiate password reset flow
* @param input - Username to reset password for
* @returns Promise with reset flow details
*/
function resetPassword(input: ResetPasswordInput): Promise<ResetPasswordOutput>;
/**
* Confirm password reset with code and new password
* @param input - Username, code, and new password
* @returns Promise when reset is complete
*/
function confirmResetPassword(input: ConfirmResetPasswordInput): Promise<void>;
/**
* Update current user's password
* @param input - Current and new passwords
* @returns Promise when update is complete
*/
function updatePassword(input: UpdatePasswordInput): Promise<void>;
interface ResetPasswordInput {
username: string;
}
interface ResetPasswordOutput {
nextStep: AuthNextResetPasswordStep;
}
interface ConfirmResetPasswordInput {
username: string;
confirmationCode: string;
newPassword: string;
}
interface UpdatePasswordInput {
oldPassword: string;
newPassword: string;
}Configure and manage MFA settings.
/**
* Update MFA preferences for current user
* @param input - MFA preferences
* @returns Promise when preferences are updated
*/
function updateMFAPreference(input: UpdateMFAPreferenceInput): Promise<void>;
/**
* Fetch current MFA preferences
* @returns Promise with MFA preferences
*/
function fetchMFAPreference(): Promise<FetchMFAPreferenceOutput>;
/**
* Set up TOTP MFA for current user
* @returns Promise with TOTP setup details
*/
function setUpTOTP(): Promise<SetUpTOTPOutput>;
/**
* Verify TOTP setup with code
* @param input - TOTP code for verification
* @returns Promise when verification is complete
*/
function verifyTOTPSetup(input: VerifyTOTPSetupInput): Promise<void>;
interface UpdateMFAPreferenceInput {
sms?: 'ENABLED' | 'DISABLED' | 'PREFERRED';
totp?: 'ENABLED' | 'DISABLED' | 'PREFERRED';
}
interface SetUpTOTPOutput {
sharedSecret: string;
getSetupUri(appName: string, accountName?: string): URL;
}
interface VerifyTOTPSetupInput {
code: string;
options?: {
friendlyDeviceName?: string;
};
}Manage remembered devices for MFA.
/**
* Remember the current device to skip MFA
* @returns Promise when device is remembered
*/
function rememberDevice(): Promise<void>;
/**
* Forget a device (remove from remembered devices)
* @param input - Device to forget (optional, defaults to current)
* @returns Promise when device is forgotten
*/
function forgetDevice(input?: ForgetDeviceInput): Promise<void>;
/**
* Fetch list of user's devices
* @returns Promise with list of devices
*/
function fetchDevices(): Promise<FetchDevicesOutput>;
interface ForgetDeviceInput {
device?: {
deviceKey: string;
};
}
interface FetchDevicesOutput {
devices: AuthDevice[];
}
interface AuthDevice {
deviceKey: string;
deviceName?: string;
deviceCreateDate?: Date;
deviceLastModifiedDate?: Date;
deviceLastAuthenticatedDate?: Date;
}Biometric and hardware key authentication.
/**
* Associate WebAuthn credential with current user
* @returns Promise when credential is associated
*/
function associateWebAuthnCredential(): Promise<void>;
/**
* List WebAuthn credentials for current user
* @returns Promise with list of credentials
*/
function listWebAuthnCredentials(): Promise<ListWebAuthnCredentialsOutput>;
/**
* Delete a WebAuthn credential
* @param input - Credential to delete
* @returns Promise when credential is deleted
*/
function deleteWebAuthnCredential(input: DeleteWebAuthnCredentialInput): Promise<void>;
interface ListWebAuthnCredentialsOutput {
credentials: WebAuthnCredential[];
}
interface WebAuthnCredential {
credentialId: string;
friendlyCredentialName: string;
relyingPartyId: string;
authenticatorAttachment?: 'platform' | 'cross-platform';
authenticatorTransports?: string[];
createdAt: Date;
}
interface DeleteWebAuthnCredentialInput {
credentialId: string;
}Delete user account and attributes.
/**
* Delete the current user account
* @returns Promise when account is deleted
*/
function deleteUser(): Promise<void>;
/**
* Delete specific user attributes
* @param input - Attributes to delete
* @returns Promise when attributes are deleted
*/
function deleteUserAttributes(input: DeleteUserAttributesInput): Promise<void>;
interface DeleteUserAttributesInput {
userAttributeKeys: UserAttributeKey[];
}Decode and work with JWT tokens.
/**
* Decode a JWT token (Cognito-specific)
* @param token - JWT token string to decode
* @returns Decoded JWT object
*/
function decodeJWT(token: string): JWT;type UserAttributeKey =
| 'address'
| 'birthdate'
| 'email'
| 'family_name'
| 'gender'
| 'given_name'
| 'locale'
| 'middle_name'
| 'name'
| 'nickname'
| 'phone_number'
| 'picture'
| 'preferred_username'
| 'profile'
| 'sub'
| 'updated_at'
| 'website'
| 'zoneinfo'
| `custom:${string}`;
type VerifiableUserAttributeKey = 'email' | 'phone_number';
interface CodeDeliveryDetails {
destination?: string;
deliveryMedium?: 'EMAIL' | 'SMS';
attributeName?: string;
}
interface AWSCredentials {
accessKeyId: string;
secretAccessKey: string;
sessionToken?: string;
expiration?: Date;
}
// Error types
class AuthError extends Error {
name: string;
message: string;
cause?: Error;
}Authentication functions can throw various errors:
try {
await signIn({ username, password });
} catch (error) {
if (error instanceof AuthError) {
switch (error.name) {
case 'UserNotConfirmedException':
// Handle unconfirmed user
break;
case 'NotAuthorizedException':
// Handle invalid credentials
break;
case 'UserNotFoundException':
// Handle user not found
break;
default:
// Handle other auth errors
break;
}
}
}