SENDLINE open source
open source / oauth4s / other grants

Other grants

scala
val machine: IO[TokenResponse]   = client.clientCredentials(Scope.of("read")) // RFC 6749 §4.4
val renewed: IO[TokenResponse]   = client.refresh(refreshToken)               // RFC 6749 §6
val revoked: IO[Unit]            = client.revokeRefreshToken(refreshToken)    // RFC 7009
val inspected: IO[Introspection] = client.introspect(accessToken)             // RFC 7662

val exchanged: IO[TokenResponse] = // RFC 8693, or any grant the client has no method for
  client.requestToken(
    GrantType.TokenExchange,
    Seq("subject_token" -> accessToken.value, "subject_token_type" -> "urn:ietf:params:oauth:token-type:access_token"),
  )

val onDevice: IO[TokenResponse] =
  for
    device <- client.deviceAuthorization(Scope.of("read")) // RFC 8628
    _      <- IO.println(s"enter ${device.userCode.value} at ${device.verificationUri}")
    token  <- client.awaitDevice(device)                   // polls at the server's interval, backs off on slow_down
  yield token

awaitDevice returns when the user has approved the device, fails with the server's error when they have refused, and fails with expired_token when the device code has run out — it never waits past expiresIn.

Revocation succeeds on any 2xx, including for a token the server no longer knows, as RFC 7009 asks. revokeAccessToken is the other half. Introspection reads active, scope, client_id, username, sub, aud, iss, exp, iat, nbf, jti, and keeps the document in raw.

A token that stays fresh

A service that calls another service does not want a grant, it wants a token that is always valid:

scala
val service: TokenSource[IO] = TokenSource.clientCredentials(client, Scope.of("read"))
val user: TokenSource[IO]    = TokenSource.refreshing(client, stored)

def call[A](request: AccessToken => IO[A]): IO[A] =
  service.accessToken.flatMap(request) // asks once, then serves from memory until a minute before the expiry

val refused: IO[Unit] = service.invalidate // the resource server answered 401: the next call asks again

def active(token: AccessToken): IO[Boolean] =
  client.introspect(token).map(answer => answer.active && answer.scope.exists(_.contains("read")))

TokenSource.refreshing starts from a token you already have — a user's, loaded from your database — and uses its refresh token. When the server answers without a new refresh token, the old one is kept; when it rotates, the new one replaces it. The leeway is a minute and is the last parameter of both constructors.

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