Composable

Use the useOidcAuth composable to interact with authentication state

Introduction

Nuxt OIDC Auth automatically adds API routes to interact with the current user session and auto imports the useOidcAuth composable, which provides the following properties and methods to access the user session from your Vue components or middlewares:

login

Call login to initiate the login process. It can be used in a route middleware as well as in components and should always be used instead of manually forwarding to /auth/PROVIDER/login or /auth/login.

Example usage:

<script setup lang="ts">
const { loggedIn, user, login, logout } = useOidcAuth()
</script>

<template>
  <div v-if="loggedIn">
    <h1>Welcome {{ user.userName }}!</h1>
    <p>Logged in since {{ user.loggedInAt }}</p>
    <button @click="logout()">
      Logout
    </button>
  </div>
  <div v-else>
    <h1>Not logged in</h1>
    <a href="/auth/github/login">Login with GitHub</a>
    <button @click="login()">
      Login with default provider
    </button>
  </div>
</template>

Parameters

login takes the following parameters

NameDescriptionTypeRequired
providerThe authentication provider to use. If not specified, uses the default provider.string (needs to be a configured provider)No
paramsAdditional parameters to include in the login request. Each parameters has to be listed in allowedClientAuthParameters in the provider configuration.Record<string, string>No

Returns

Promise (does not have to be awaited)

logout

Handles the logout process. Always provide the optional provider parameter if you haven't set a default provider. You can get the current provider from the currentProvider property.

Example usage:

<script setup lang="ts">
const { logout } = useOidcAuth()
</script>

<template>
  <button @click="logout()">
    Logout
  </button>
</template>

Example usage with no default provider configured or middleware => customLoginPage set to true:

<script setup lang="ts">
const { logout, currentProvider } = useOidcAuth()
</script>

<template>
  <button @click="logout(currentProvider)">
    Logout
  </button>
</template>

Parameters

logout takes the following parameters

NameDescriptionTypeRequired
providerThe authentication provider to use. If not specified, uses the default provider.string (needs to be a configured provider)No
logoutRedirectUriThe URI to redirect to after logout if logoutRedirectParameterName is set. If not provided, the user will be redirected to the root site.Record<string, string>No

Returns

Promise (can be awaited)

loggedIn

Use loggedIn to check if the user is currently logged in.

Example usage:

const { loggedIn } = useOidcAuth()

if (loggedIn.value) {
  console.log('User is logged in')
}
else {
  console.log('User is not logged in')
}

Parameters

login takes the following parameters

NameDescriptionRequired
providerThe authentication provider to use. If not specified, uses the default provider.No
paramsAdditional parameters to include in the login request. Each parameters has to be listed in allowedClientAuthParameters in the provider configuration.No

Returns

Promise (does not have to be awaited)

user

The current user object ref. See User object

currentProvider

The name of the currently logged in provider.

Example usage:

<script setup lang="ts">
const { logout, currentProvider } = useOidcAuth()
</script>

<template>
  <button @click="logout(currentProvider)">
    Logout
  </button>
</template>

fetch

Fetches/updates the current user session from the server. Only refreshed the session if the session is expired. Mainly used in middleware or plugins to make ensure there is a session.

Parameters

fetch takes no additional parameters.

Returns

Promise (can be awaited)

refresh

Refreshes the current user session against the used provider to get a new access token. Only available if the current provider issued a refresh token (indicated by canRefresh property in the user object).

Example usage:

<script setup lang="ts">
const { loggedIn, user, refresh } = useOidcAuth()
const refreshing = ref(false)
async function handleRefresh() {
  refreshing.value = true
  await refresh()
  refreshing.value = false
}
</script>

<template>
  <button
    class="btn-base btn-login"
    :disabled="!loggedIn || !user?.canRefresh || refreshing"
    @click="handleRefresh()"
  >
    <span class="i-majesticons-refresh" />
    <span class="pl-2">Refresh</span>
  </button>
</template>

Parameters

refresh takes no additional parameters.

Returns

Promise (should be awaited)

User object

The user object provided by useOidcAuth contains the following properties:

NameTypeDescription
providerstringName of the provider used to log in the current session
canRefreshbooleanWhether the current session exposed a refresh token
loggedInAtnumberLogin timestamp in second precision
updatedAtnumberRefresh timestamp in second precision
expireAtnumberSession expiration timestamp in second precision. Either loggedInAt plus session max age or expiration of access token if available.
userInfoRecord<string, unknown>Additional information coming from the provider's userinfo endpoint
userNamestringComing either from the provider or from the configured mapped claim
claimsRecord<string, unknown>Additional optional claims from the id token, if optionalClaims setting is configured.
accessTokenstringExposed access token, only existent when exposeAccessToken is configured.
idTokenstringExposed access token, only existent when exposeIdToken is configured.

You can extend the type for your provider info by creating a type declaration file (for example, auth.d.ts) in your project:

declare module '#oidc-auth' {
  interface UserSession {
    // define custom claim object
    claims: {
      customProviderToken: string
    }
  }
}

Copyright © 2024