This commit is contained in:
jay brown
2025-04-16 11:30:14 -07:00
parent e76dd2391c
commit cb0207a74f
3 changed files with 67 additions and 74 deletions
+4 -9
View File
@@ -16,11 +16,9 @@ A reusable Go package for AWS Cognito authentication and authorization with Echo
To disable all of these features for all endpoints you must set
`DISABLE_AUTH=true` in your environment.
## Installation
```bash
go get github.com/yourusername/cognitoauth
```
## Package details
For a detailed explanation of all of the files in this
package see the [summary](./summary.md) file.
## Configuration
@@ -30,9 +28,6 @@ The package reads configuration from environment variables:
- `COGNITO_CLIENT_SECRET`: Your AWS Cognito App Client Secret (optional for public clients)
- `COGNITO_USER_POOL_ID`: Your AWS Cognito User Pool ID
- `COGNITO_DOMAIN`: Your AWS Cognito domain
- `AWS_REGION`: AWS region where your Cognito User Pool is located
- `AWS_REGION`: AWS region where your Cognito User Pool is located (us-east-2)
- `DEBUG`: Set to "true" for debug logging
Optional path configuration:
- `COGNITO_LOGIN_PATH`: Path for login endpoint (default: "/login")
- `COGNITO_CALLBACK_PATH`: Path for OAuth callback (default: "/
-13
View File
@@ -1,13 +0,0 @@
# Cognitoauth structure
| File | Description |
|------|-------------|
| `auth.go` | Main package file with exported functions |
| `handler.go` | HTTP handlers for login, callback, etc. |
| `middleware.go` | Echo middleware implementation |
| `jwks.go` | JWKS handling and validation |
| `token.go` | Token verification and management |
| `models.go` | Data models and types |
| `utils.go` | Helper functions |
| `config.go` | Configuration structures |
+63 -52
View File
@@ -1,70 +1,81 @@
# Summary of the Cognito Auth Package
# Cognito RBAC Design and Integration
This package handles the complete PKCE flow with AWS Cognito and integrates cleanly with the Echo web framework.
## Overview
## Key Components:
This package uses AWS Cognito for authentication and implements Role-Based Access Control (RBAC) for API endpoints. The integration is tightly coupled with the Echo web framework and the OpenAPI (swagger) generated API code.
### Config Structure: Centralizes all configuration and can be initialized from environment variables.
## Key Components
Middleware:
### 1. Cognito Auth Package (`internal/cognitoauth`)
### JWTAuthMiddleware: Extracts tokens from cookies and adds them to Authorization headers
- **auth.go**: Main exports for the package.
- **handler.go**: HTTP handlers for login, callback, logout, and home.
- **middleware.go**: Echo middleware for JWT extraction, validation, and RBAC enforcement.
- **jwks.go**: Handles JWKS key fetching and JWT signature validation.
- **token.go**: Token verification and management.
- **models.go**: Data models and types for tokens, users, etc.
- **utils.go**: Helper functions.
- **config.go**: Configuration structures for the auth system.
TokenValidationMiddleware: Handles token validation and authorization
### 2. Service Config (`internal/serviceconfig`)
### Route Handlers:
- **auth/config.go**: Loads and manages authentication-related configuration, including RBAC route permissions.
- **common.go**: Shared config logic.
Login initiation
OAuth callback processing
Logout functionality
Home page with authentication status
### 3. API Layer (`api/queryAPI`)
### Helper Functions:
- **api.gen.go**: Swagger-generated API handlers.
- **authHandlers.go**: Bridges generated code to Cognito logic; delegates to middleware for most flows.
- **homehandler.go**: Displays authentication status.
- **controllers.go**: Wires up controllers, but does not directly handle auth.
Token verification
User group extraction
Permission checking
### 4. Server Setup (`internal/server/api/listener.go`)
## How to Use It:
- Creates the Echo server.
- Sets up config and logging middleware.
- Sets up Prometheus and OpenAPI validation middleware.
- **Registers Cognito RBAC middleware and routes before registering API handlers.**
- Sets route-level permissions via a map of route to allowed groups.
Initialize the Config:
## Integration Flow
```
goconfig := cognitoauth.NewConfigFromEnv("http://localhost:8080", logger)
1. **Config Initialization**: Auth config and route permissions are loaded at startup.
2. **Echo Server Setup**: The Echo instance is created and set on the config.
3. **RBAC Middleware Registration**:
- `cognitoauth.RegisterRoutes(echoRouter, config)` is called.
- This registers login, callback, logout, and home endpoints.
- It also registers JWT extraction and validation middleware.
- Route permissions are enforced via middleware that checks the user's Cognito groups/roles against the configured permissions map.
4. **API Handler Registration**:
- OpenAPI-generated handlers are registered after the RBAC middleware.
- All API endpoints are thus protected by the RBAC middleware.
5. **Request Flow**:
- User requests a protected endpoint.
- Middleware extracts JWT from cookies, validates it, and checks group membership.
- If authorized, the request proceeds to the handler (which may be swagger-generated).
- If not, a 401/403 is returned.
Set Route Permissions:
goroutePermissions := map[string][]string{
"/users": {"exporters", "uploaders"},
"/orders": {"exporters"},
## Example
```go
// Set route permissions
routePermissions := map[string][]string{
"/users": {"exporters", "uploaders", "querybuilders"},
"/orders": {"exporters"},
// ...
}
config.SetRoutePermissions(routePermissions)
config.SetAuthRoutePermissions(routePermissions)
// Register Cognito auth routes and middleware
cognitoauth.RegisterRoutes(echoRouter, config)
// Register API handlers (swagger-generated)
RegisterHandlers(echoRouter, controllers)
```
### Register Routes and Middleware:
## Customization
`gocognitoauth.RegisterRoutes(e, config)`
### Define Your Protected Routes:
```
e.GET("/users", handleUsers)
e.GET("/orders", handleOrders)
```
### Authentication Flow:
User navigates to /login
User is redirected to Cognito login page
After successful login, Cognito redirects to /login-callback
The callback handler exchanges the authorization code for tokens
Tokens are stored in cookies for subsequent requests
Protected routes check token validity and user permissions
### Customization:
The package is designed to be customizable:
Configure paths for login, callback, logout, and home
Define your own route permissions
Use RequireGroups middleware for fine-grained control
Access user information in your handlers via GetUserInfo
- Paths for login, callback, logout, and home can be configured.
- Route permissions are fully customizable.
- Middleware can be extended or replaced for fine-grained control.
- User info is accessible in handlers via helper functions.