Nuxt auth utils examples

Does there exist an nuxt auth utils example with a basic jwt token? I'm setting up a authentication flow with my own custom backend using asp net core identity
2 Replies
kapa.ai
kapa.ai2w ago
Hi @LordGhandi. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave: ---------------------- Yes, there are examples of using nuxt-auth-utils for authentication flows in Nuxt, but the official documentation and recipes focus on session-based authentication using sealed cookies, not directly on JWT tokens. The provided examples show how to set up login, session management, and route protection, which you can adapt to work with your own backend (such as ASP.NET Core Identity). Key points from the official recipe: - nuxt-auth-utils manages session data using encrypted cookies, not JWTs by default. - The login flow involves an API route (e.g., /api/login) that validates credentials and sets the user session using a helper like setUserSession. - On the client, you use the useUserSession composable to check authentication state and manage sessions. - Route protection is handled via middleware that checks if the user is logged in and redirects to the login page if not. Example login API route:
// server/api/login.post.ts
import { z } from 'zod'

const bodySchema = z.object({
email: z.string().email(),
password: z.string().min(8)
})

export default defineEventHandler(async (event) => {
const { email, password } = await readValidatedBody(event, bodySchema.parse)

// Replace this with your own backend authentication logic
if (email === '[email protected]' && password === 'iamtheadmin') {
await setUserSession(event, {
user: {
name: 'John Doe'
}
})
return {}
}
throw createError({
statusCode: 401,
message: 'Bad credentials'
})
})
// server/api/login.post.ts
import { z } from 'zod'

const bodySchema = z.object({
email: z.string().email(),
password: z.string().min(8)
})

export default defineEventHandler(async (event) => {
const { email, password } = await readValidatedBody(event, bodySchema.parse)

// Replace this with your own backend authentication logic
if (email === '[email protected]' && password === 'iamtheadmin') {
await setUserSession(event, {
user: {
name: 'John Doe'
}
})
return {}
}
throw createError({
statusCode: 401,
message: 'Bad credentials'
})
})
Example login page:
<script setup lang="ts">
const { loggedIn, user, fetch: refreshSession } = useUserSession()
const credentials = reactive({
email: '',
password: '',
})
async function login() {
$fetch('/api/login', {
method: 'POST',
body: credentials
})
.then(async () => {
await refreshSession()
await navigateTo('/')
})
.catch(() => alert('Bad credentials'))
}
</script>

<template>
<form @submit.prevent="login">
<input v-model="credentials.email" type="email" placeholder="Email" />
<input v-model="credentials.password" type="password" placeholder="Password" />
<button type="submit">Login</button>
</form>
</template>
<script setup lang="ts">
const { loggedIn, user, fetch: refreshSession } = useUserSession()
const credentials = reactive({
email: '',
password: '',
})
async function login() {
$fetch('/api/login', {
method: 'POST',
body: credentials
})
.then(async () => {
await refreshSession()
await navigateTo('/')
})
.catch(() => alert('Bad credentials'))
}
</script>

<template>
<form @submit.prevent="login">
<input v-model="credentials.email" type="email" placeholder="Email" />
<input v-model="credentials.password" type="password" placeholder="Password" />
<button type="submit">Login</button>
</form>
</template>
Adapting for JWT: - If your backend returns a JWT, you can store it in a cookie using the useCookie composable or in the session object managed by nuxt-auth-utils. - There is a pending documentation update to show how to handle authentication tokens with cookies, which would be relevant for JWTs. Summary:
While there isn't an official example specifically for JWT with nuxt-auth-utils, the session-based approach can be adapted for JWT by storing the token in a cookie or session and using it in your API requests. You can refer to the Sessions and Authentication recipe for a full walkthrough and adapt the backend logic to issue and validate JWTs as needed for your ASP.NET Core Identity backend. Sessions and Authentication Recipe
Handling authentication with cookies (pending doc update) ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai2w ago
<@358749735323959308> Kapa.ai is still learning and improving, please let me know how I did by reacting below.

Did you find this page helpful?