SENDLINE open source
open source / oauth4s / the authorization code flow

The authorization code flow

A client is a configuration: who you are, how you authenticate and where the server is.

scala
val endpoints = Endpoints.of(Endpoint("https://auth.example.com/authorize"), Endpoint("https://auth.example.com/token"))
val config    = OAuthClientConfig(ClientId("client-1"), ClientAuthentication.SecretBasic(ClientSecret("s3cret")), endpoints)
val client    = OAuthClient[IO](config.withScope(Scope.of("read", "write")))

// or from the server's own description: RFC 8414 first, the OpenID configuration second
val discovered: IO[OAuthClient[IO]] =
  OAuthClient.discover[IO](Issuer("https://auth.example.com"), ClientId("client-1"), ClientAuthentication.Public)

The flow is two calls, because it is two HTTP requests of yours with a browser round trip between them:

scala
// the first request: remember the flow, send the browser to its url
def signIn(remember: AuthorizationFlow => IO[Unit]): IO[String] =
  for
    flow <- client.authorize(redirect, AuthorizationOptions.scoped("read").withPrompt("consent"))
    _    <- remember(flow)
  yield flow.url

// the second request: the provider sent the browser back to the redirect URI
def callback(flow: AuthorizationFlow, requestUrl: String): IO[TokenResponse] =
  client.complete(flow, AuthorizationCallback.fromUrl(requestUrl))

complete returns a TokenResponse: accessToken, tokenType, expiresIn and the expiresAt computed from it, refreshToken, scope, idToken, and raw, the whole document, for whatever else the server put there.

What a flow carries

AuthorizationFlow is a plain case class, and it is the whole state of the flow:

Field What it is for
url where to send the browser
state 32 random bytes; the callback must bring it back
redirectUri sent again with the code, as the specification requires
verifier the PKCE code verifier; its SHA-256 went out in url
nonce present when the flow asked for one; an ID token must repeat it

Where it lives between the two requests — a server-side session, an encrypted cookie, a row keyed by state — is the application's decision. A recipe keeps it in memory keyed by state.

What complete checks

  1. The callback has no error. If it has, the flow fails with that error as a Rejected and nothing is sent.
  2. The callback's state is the flow's. Otherwise StateMismatch: this is the CSRF check.
  3. If the configuration knows its issuer and the callback has an iss, they are equal. Otherwise IssuerMismatch: this is the mix-up defence of RFC 9207.
  4. There is a code.

Only then is the code exchanged, together with the verifier and the redirect URI.

Client authentication

scala
val authentication: List[ClientAuthentication] =
  List(
    ClientAuthentication.Public,                              // a browser, a mobile or a desktop application
    ClientAuthentication.SecretBasic(ClientSecret("s3cret")), // Authorization: Basic, what RFC 6749 prefers
    ClientAuthentication.SecretPost(ClientSecret("s3cret")),  // client_id and client_secret in the form
    ClientAuthentication.SecretMinted(minted),                // a secret made for each request, from the time it is made at
  )

There is no way to say "Basic, but I forgot the secret". SecretMinted takes an Instant => ClientSecret, for a secret that is a function of time: Apple's is a JWT that expires, so it is signed again for every request.

Configuration

scala
val tuned: OAuthClientConfig =
  config
    .withIssuer(Issuer("https://auth.example.com"))                    // compared with the `iss` of the callback, RFC 9207
    .withScope(Scope.of("read"))                                       // what a flow asks for when it names no scope
    .withScopeSeparator(",")                                           // for the providers that do not use a space
    .withAuthorizationParameter("audience", "https://api.example.com") // on every authorization request
    .withTokenParameter("audience", "https://api.example.com")         // on every token request
    .forwardingCallbackParameter("device_id")                          // from the callback into the code exchange
    .withUserAgent("billing/1.4")

Endpoints is built the same way: Endpoints.of(authorization, token) and withDeviceAuthorization, withRevocation, withIntrospection, withUserInfo, withJwks, withEndSession. A method that needs an endpoint the client does not have fails with OAuthError.MissingEndpoint.

An Endpoint is absolute, has no fragment, and is https, or http on localhost and 127.0.0.1. Endpoint("http://auth.example.com/token") throws where it is written; Endpoint.parse returns an Either, and that is what reads a discovery document, so a server that advertises a plain http token endpoint is refused before a secret is sent to it.

Options of one flow

scala
val options: AuthorizationOptions =
  AuthorizationOptions.default
    .withScope(Scope.of("read", "write"))
    .withNonce                 // a nonce in the request and in the flow
    .withPrompt("consent")
    .withLoginHint("ann@example.com")
    .withParameter("ui_locales", "ru")
    .withPkce(PkceMethod.S256) // the default; withoutPkce for a provider that refuses the parameters

Callbacks

scala
def posted(flow: AuthorizationFlow, requestBody: String): IO[TokenResponse] =
  client.complete(flow, AuthorizationCallback.fromForm(requestBody)) // response_mode=form_post

def denied(requestUrl: String): Option[OAuthError] =
  AuthorizationCallback.fromUrl(requestUrl).error // Some(Rejected(AccessDenied, …)) when the user said no

AuthorizationCallback.fromParameters takes the parameters when a web framework has already parsed them. The fragment of a URL is ignored, so Instagram's #_ is not part of the code.

built from README.md at v0.1.1 edit this page on GitHub