Authentication

Authentication and authorization#

Headers use the normal Effect RPC API and apply to the complete pipeline request:

ts
import * as RpcClient from "effect/rpc/RpcClient"

const result = yield* Pipeline.all({
  me: rpc.me(),
  todos: rpc.listTodos({ filter: "all" })
}).pipe(
  RpcClient.withHeaders({ authorization: `Bearer ${token}` })
)

Protect the server RPCs#

Use native Effect RPC middleware for authentication. Auth.layerBearer extracts and redacts the bearer credential, then passes it to your verifier. The result becomes a typed principal service for handlers.

ts
import * as Context from "effect/Context"
import * as Redacted from "effect/Redacted"
import * as RpcMiddleware from "effect/rpc/RpcMiddleware"
import * as Auth from "effect-rpc-pipeline/Auth"

class CurrentUser extends Context.Service<CurrentUser, User>()("app/CurrentUser") {}

class Unauthorized extends Schema.TaggedError<Unauthorized>()("Unauthorized", {
  reason: Schema.String
}) {}

class AccessTokenVerifier extends Context.Service<AccessTokenVerifier, {
  verify: (token: Redacted.Redacted<string>) => Effect.Effect<User, Unauthorized>
}>()("app/AccessTokenVerifier") {}

class Authenticated extends RpcMiddleware.Service<Authenticated, {
  provides: CurrentUser
  requires: AccessTokenVerifier
}>()("app/Authenticated", { error: Unauthorized, requiredForClient: true }) {}

const PrivateRpcs = RpcGroup.make(
  Rpc.make("me", { success: User }),
  Rpc.make("privateTodos", { success: Schema.Array(Todo) })
).middleware(Authenticated)

const PrivateHandlers = PrivateRpcs.toLayer({
  me: () => CurrentUser,
  privateTodos: () => Effect.flatMap(CurrentUser, (user) => Todos.forUser(user.id))
})

const AuthenticatedLive = Auth.layerBearer(Authenticated, {
  principal: CurrentUser,
  authenticate: (token) => Effect.flatMap(
    AccessTokenVerifier,
    (verifier) => verifier.verify(token)
  ),
  unauthorized: () => new Unauthorized({ reason: "invalid credentials" })
})

const PrivateRoutes = PipelineServer.layerHttp({
  group: PrivateRpcs,
  path: "/rpc"
}).pipe(
  Layer.provide(PrivateHandlers),
  Layer.provide(AuthenticatedLive),
  Layer.provide(AccessTokenVerifierLive)
)

Read the current token on the client#

Provide the client middleware once. It reads the current token for every pipeline execution, so it can serve both public and protected RPCs:

ts
import * as Option from "effect/Option"

class CurrentAccessToken extends Context.Reference<
  Option.Option<Redacted.Redacted<string>>
>("app/CurrentAccessToken", { defaultValue: Option.none }) {}

const AuthenticatedClient = Auth.layerClientBearer(Authenticated, {
  token: CurrentAccessToken
})

const ClientLive = PipelineClient.layerClientHttp(AppClient, AppRpcs, {
  url: "/rpc"
}).pipe(
  Layer.provide(AuthenticatedClient),
  Layer.provide(RpcSerialization.layerJson)
)

const privateProgram = Effect.gen(function*() {
  const rpc = yield* AppClient
  return yield* rpc.me().pipe(
    Effect.provideService(
      CurrentAccessToken,
      Option.some(Redacted.make(accessToken))
    )
  )
}).pipe(Effect.provide(ClientLive))

None sends no authorization header, allowing public calls to run anonymously. A new token is observed on the next execution without rebuilding the client.

Protected server middleware still authenticates every invocation.

Supply token verification#

Auth.layerBearer does not verify JWTs. Implement AccessTokenVerifier with a JOSE/OIDC library that checks the allowed algorithm, issuer, audience, token type, expiration, and required claims.

Send credentials in the Authorization header over TLS. Do not put them in payloads or URLs. Redacted helps avoid accidental logging; it does not encrypt the token.

Check authentication coverage#

Declare which RPCs are public and which require authentication. assertCoverage can check that none were exposed accidentally:

ts
const PublicRpcs = RpcGroup.make(Health)
const PrivateRpcs = RpcGroup.make(Me, ListTodos).middleware(Authenticated)
const AppRpcs = PublicRpcs.merge(PrivateRpcs)

yield* Auth.assertCoverage(AppRpcs, {
  public: [Health],
  protectedBy: Authenticated
})

Authorize the resource#

Authentication identifies the caller. A handler must still decide whether that caller can read or change a particular resource. Use additional RPC middleware for coarse role or scope checks.

For example, constrain a mutation by the authenticated owner:

ts
updateTodo: ({ id, patch }) => Effect.gen(function*() {
  const user = yield* CurrentUser
  return yield* Todos.updateOwnedBy({ ownerId: user.id, id, patch })
})

Use the server-provided principal for ownership checks, rather than trusting a client-supplied userId. Adding a credential on the client is not an access check.

Middleware marked requiredForClient is captured when PipelineClient.make runs. Middleware shared by several graph nodes runs once around the whole batch.