Use BasicAuth with an Amplify backend
This guide secures your Blocks API with the AWS Blocks AuthBasic Block — simple username and password authentication with JWT sessions.
This guide assumes you have already added AWS Blocks to your Amplify project.
Install the AuthBasic Block
Add the Block to your aws-blocks workspace:
npm install @aws-blocks/bb-auth-basicDefine authentication
In aws-blocks/index.ts, create an AuthBasic instance, protect your API methods with requireAuth, and export the authentication API the frontend uses to sign users in and out:
import { ApiNamespace, Scope } from '@aws-blocks/blocks';import { AuthBasic } from '@aws-blocks/bb-auth-basic';
const scope = new Scope('my-app');
const auth = new AuthBasic(scope, 'auth', { sessionDuration: 86400, // 24 hours passwordPolicy: { minLength: 8, requireDigits: true }});
export const api = new ApiNamespace(scope, 'api', (context) => ({ async getProfile() { const user = await auth.requireAuth(context); return { username: user.username, createdAt: user.createdAt }; }}));
// Export the auth API for the frontend sign-in / sign-up flowsexport const authApi = auth.createApi();requireAuth(context) returns the signed-in user or throws a 401 (SessionExpiredException). AuthBasic manages the session with an HTTP cookie, so there is no token to attach manually.
Deploy
Deploy with the rest of your backend:
npm run sandboxSign users in from your frontend
Generate the native client for your platform from your backend's blocks.spec.json (see Connect your frontend). Call the setAuthState action with { action: 'signUp', ... } and { action: 'signIn', ... } to register and authenticate users. AuthBasic sets a session cookie, so subsequent authenticated calls do not need a token attached.
Optional: confirm sign-up with a code
To require email confirmation, provide a codeDelivery callback. This puts new users in an unconfirmed state until they verify a 6-digit code, and enables password reset:
const auth = new AuthBasic(scope, 'auth', { passwordPolicy: { minLength: 8, requireDigits: true }, codeDelivery: async (username, code) => { await sendEmail(username, `Your verification code: ${code}`); }});You could deliver the code with the AWS Blocks EmailClient Block. Users then complete sign-up with { action: 'confirmSignUp', username, code, password }.
Next steps
- Add an AI agent to your Amplify app.
- See the AWS Blocks Developer Guide for the full
AuthBasicAPI, including password reset and cross-domain sessions.