Putnami
DocsGitHub

Licensed under FSL-1.1-MIT

Getting Started
Concepts
How To
Build A Web App
Build An Api Service
Share Code Between Projects
Configure Your App
Add Persistence
Add Authentication
Add Background Jobs
Principles
Tooling & Workspace
Workspace Overview
Cli
Jobs & Commands
SDK
Error Handling
Extensions
Typescript
Go
Python
Docker
Ci
Frameworks
Typescript
OverviewWebReact RoutingForms And ActionsStatic FilesApiErrors And ResponsesConfigurationLoggingHttp And MiddlewareDependency InjectionPlugins And LifecycleSessionsAuthPersistenceEventsStorageCachingWebsocketsTestingHealth ChecksTelemetryProto GrpcSmart Client
Go
OverviewHttpDependency InjectionPlugins And LifecycleConfigurationSecurityPersistenceErrorsEventsStorageCachingLoggingTelemetryGrpcService ClientsValidationOpenapiTesting
Platform
  1. DocsSeparator
  2. How ToSeparator
  3. Add Authentication

Add authentication

You will add OAuth2 login and protect one route using @putnami/application.

Companion sample: samples/ts/07-authentication — a runnable project with OAuth2 flow, sessions, and protected routes. Run bunx putnami serve @sample/ts-authentication from the workspace root.

Steps

1) Enable OAuth2

Update your app entry, for example apps/web/src/main.ts:

import { application, http, oAuth2 } from '@putnami/application';

export const app = () =>
  application()
    .use(http({ port: 3000 }))
    .use(oAuth2());

2) Configure the provider

Create .env.local.yaml:

oauth:
  clientId: 'your-client-id'
  clientSecret: 'your-client-secret'
  authorizeUri: 'https://auth.example.com/authorize'
  tokenUri: 'https://auth.example.com/token'
  keysUri: 'https://auth.example.com/.well-known/jwks.json'
  scopes:
    - 'openid'
    - 'profile'
    - 'email'

3) Protect one route

Create apps/web/src/app/me/get.ts:

import { endpoint, useUser, HttpResponse } from '@putnami/application';

export default endpoint(async () => {
  const user = await useUser();
  if (!user) {
    return HttpResponse.redirect('/login');
  }
  return { user };
});

Visit /login to sign in, then load /me.

Result

You now have a protected route behind authentication.

On this page

  • Add authentication
  • Steps
  • 1) Enable OAuth2
  • 2) Configure the provider
  • 3) Protect one route
  • Result