-
Notifications
You must be signed in to change notification settings - Fork 1
Docs: Awcog
- Introduction
- Installation
- Overview
-
Key Concepts
- AWS Cognito Authentication Integration
- NGRX Effects for Authentication Handling
- Cookies Management
-
Core Components
AwcogModule
-
Key Tokens
COGNITO_SETTINGS
-
Models
CognitoSettings
-
Effects
CognitoAuthEffects
-
Usage
- Configuring Cognito
- Authentication Workflow
- Cookie Management
- API Reference
- Examples
- Testing
The Awcog Angular library integrates AWS Cognito authentication workflows into Angular applications. Designed to work seamlessly with @ngrx/effects and the Redux pattern, this library simplifies the authentication setup by handling tokens, cookies, and user session management.
Install the necessary dependencies:
npm install awcog @ngrx/effects @rollthecloudinc/auth js-cookieAwcog provides integration with AWS Cognito and includes logic for managing authentication workflows using NGRX Effects. Key features include:
- Cognito authentication settings configuration.
- Loading and managing user sessions through cookies.
- Dispatching and handling actions using
@ngrx/effects.
- Automatic cookie management for session persistence.
- Highly extensible authentication effects.
- Type-safe injection of settings using Angular's
InjectionToken.
The library uses the COGNITO_SETTINGS token to inject AWS Cognito credentials, such as identity pool ID, user pool ID, and region. These settings configure user authentication with AWS Cognito services.
The library utilizes @ngrx/effects to implement side effects for authentication workflows, such as:
- Triggering
SetUserandQUERY_ALLactions. - Persisting user cookies for session state management.
- Observing authentication actions dispatched through NGRX.
The CognitoAuthEffects class handles storing authentication cookies dynamically with expiration times using the lightweight js-cookie library.
The AwcogModule defines the necessary application setup for integrating AWS Cognito. It includes NGRX effects and handles authentication workflows.
Key Features:
- Adds Cognito-related effects via
EffectsModule.forFeature. - Provides infrastructure for handling authentication cookies.
Example:
import { AwcogModule } from 'awcog';
@NgModule({
imports: [AwcogModule],
declarations: [],
exports: [],
})
export class AppModule {}This injection token provides AWS Cognito settings, such as the identity pool ID, region, and user pool ID. CognitoSettings is used to configure the authentication service.
Example:
import { COGNITO_SETTINGS } from 'awcog';
import { CognitoSettings } from 'awcog/models';
const cognitoConfig: CognitoSettings = {
identityPoolId: 'us-east-1:xxxxxx',
region: 'us-east-1',
userPoolId: 'us-east-1_xxxxxx',
};
@NgModule({
providers: [{ provide: COGNITO_SETTINGS, useValue: cognitoConfig }],
})
export class AppModule {}This data model defines required fields to configure AWS Cognito authentication.
Properties:
-
identityPoolId: AWS Identity Pool ID. -
region: AWS region for the Cognito service. -
userPoolId: AWS User Pool ID.
Example:
const settings = new CognitoSettings({
identityPoolId: 'us-east-1:xxxxxx',
region: 'us-east-1',
userPoolId: 'us-east-1_xxxxxx',
});
console.log(settings);The authentication effects manage key workflows for AWS Cognito. Notable effects include:
- SetUser: Triggered whenever user data is set, this effect dispatches a query action for cookies (QUERY_ALL).
-
LoadCookies: Observes successful cookie retrieval actions (
QUERY_ALL_SUCCESS) and sets user cookies using thejs-cookielibrary.
Example:
@Injectable()
export class CognitoAuthEffects {
constructor(private actions$: Actions, private entityActionFactory: EntityActionFactory) {}
setUser = createEffect(() =>
this.actions$.pipe(
ofType(AuthActions.AuthActionTypes.SetUser),
map(() =>
this.entityActionFactory.create<Cookie>('Cookie', EntityOp.QUERY_ALL)
)
)
);
loadCookies$ = createEffect(
() =>
this.actions$.pipe(
ofEntityType('Cookie'),
ofEntityOp([EntityOp.QUERY_ALL_SUCCESS]),
tap((action) => {
action.payload.data.forEach((cookie) =>
Cookies.set(cookie.name, cookie.value, {
expires: new Date(new Date().getTime() + 3600 * 1000),
})
);
})
),
{ dispatch: false }
);
}Define the Cognito settings in your Angular application using COGNITO_SETTINGS.
import { COGNITO_SETTINGS } from 'awcog';
import { CognitoSettings } from 'awcog/models';
@NgModule({
providers: [
{
provide: COGNITO_SETTINGS,
useValue: {
identityPoolId: 'us-east-1:xxxxxx',
region: 'us-east-1',
userPoolId: 'us-east-1_xxxxxx',
},
},
],
})
export class AppModule {}Use NGRX actions and effects to trigger authentication workflows.
Example:
import { Store } from '@ngrx/store';
import { AuthActions } from '@rollthecloudinc/auth';
constructor(private store: Store) {}
login() {
this.store.dispatch({
type: AuthActions.AuthActionTypes.SetUser,
payload: { username: 'testUser', token: 'tokenValue' },
});
}Cookies are automatically managed by CognitoAuthEffects. Expired cookies are handled and refreshed dynamically.
Example:
import * as Cookies from 'js-cookie';
Cookies.get('sessionCookie'); // Retrieve the stored cookie
Cookies.remove('sessionCookie'); // Remove the cookie-
Properties
-
identityPoolId: Specifies the AWS Cognito Identity Pool ID. -
region: AWS region where Cognito is hosted. -
userPoolId: AWS Cognito User Pool ID.
-
-
Constructor
-
Params:
data?: CognitoSettings- Optional settings for initialization.
-
Params:
const cognitoSettings = {
identityPoolId: 'us-east-1:xxxxxx',
region: 'us-east-1',
userPoolId: 'us-east-1_xxxxxx',
};
@NgModule({
providers: [{ provide: COGNITO_SETTINGS, useValue: cognitoSettings }],
})
export class AppModule {}Use NGRX Actions to trigger authentication effects:
import { Store } from '@ngrx/store';
import { AuthActions } from '@rollthecloudinc/auth';
constructor(private store: Store) {}
authenticateUser() {
this.store.dispatch({
type: AuthActions.AuthActionTypes.SetUser,
payload: { username: 'testUser', token: 'abc123' },
});
}Retrieve, set, and manipulate cookies with js-cookie:
import * as Cookies from 'js-cookie';
Cookies.set('sessionCookie', 'sessionValue', { expires: 1 });
console.log(Cookies.get('sessionCookie'));
Cookies.remove('sessionCookie');Example test for verifying the setUser effect:
import { CognitoAuthEffects } from './effects/cognito-auth.effects';
import { ActionsSubject } from '@ngrx/store';
describe('CognitoAuthEffects', () => {
let effects: CognitoAuthEffects;
let actions$: ActionsSubject;
beforeEach(() => {
actions$ = new ActionsSubject();
effects = new CognitoAuthEffects(actions$, {
create: jest.fn(() => ({ type: 'QUERY_ALL' })),
} as any);
});
it('should dispatch QUERY_ALL when SetUser is triggered', () => {
actions$.next({
type: AuthActions.AuthActionTypes.SetUser,
});
effects.setUser.subscribe((action) => {
expect(action.type).toEqual('QUERY_ALL');
});
});
});The Awcog library offers seamless integration with AWS Cognito authentication, session management via cookies, and NGRX Effects for efficient workflows. Its modular architecture is ideal for building scalable and secure applications.
For any issues, feature requests, or contributions, feel free to reach out or open a pull request!