npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

nuxt-simple-auth

v1.7.3

Published

Authentication module simple for Nuxt.js

Readme

nuxt-simple-auth

npm version GitHub License npm downloads Nuxt Static Badge

nuxt-simple-auth é um módulo de autenticação para Nuxt 3, Ele é um pacote de código aberto, robusto e repleto de recursos, permitindo a validação de cookies e CSRF utilizando Laravel Passport.
Além disso, oferece suporte a diversos parâmetros para cookies, tanto no login quanto na autenticação em duplo fator (2FA).
Conta ainda com suporte à autenticação SSR, garantindo que o usuário permaneça autenticado tanto no cliente quanto no servidor.

Embora o pacote seja estável em termos de opções e comportamento, ainda há melhorias a serem implementadas e a possibilidade de alguns bugs.

Start

npx nuxi@latest module add nuxt-simple-auth

Setup

Installation

Adicione nuxt-simple-auth à seção de módulos do nuxt.config.js.

Configuration

A configuração deve ser realizada no arquivo nuxt.config.js, adicionando a biblioteca à seção de módulos.

Na propriedade auth, a definição das strategies é obrigatória, enquanto as configurações de cookies e * CSRF* são opcionais.

Para autenticação, a propriedade endpoints.login exige o uso do Laravel Passport, que deve expor a rota /oauth/token.
Documentação do Laravel Passport - Client Credentials Grant Tokens

Essa rota deve retornar uma resposta JSON contendo os seguintes atributos:

  • access_token
  • refresh_token
  • expires_in

Se optar por utilizar a autenticação 2FA, o pacote requer a configuração de endpoints.2fa, que exige que o * Laravel* exponha uma rota específica.
Essa rota deve retornar uma resposta JSON com os seguintes atributos:

  • access_token
  • expires_in

expires_in: Deve ser o número de segundos até que o token de acesso do 2FA expire.

Exemplo de implementação no Laravel para o controller da rota TwoFactorAuthController:


return response()->json([

    'access_token' => $twoFactorAuth->token,

    'expires_in' => $twoFactorAuth->expire_at->timestamp - now()->timestamp, // Número de segundos até a expiração.

]);

Após a validação do 2FA, o token será automaticamente adicionado aos headers das requisições como um Bearer Token, com o nome "2fa".
Isso permite que as APIs do Laravel validem a autenticação nas rotas protegidas.

Example

export default defineNuxtConfig({
    modules: [
        'nuxt-simple-auth'
    ],

    auth: {
        csrf: '/csrf-token',
        cookie: {
            options: {
                httpOnly: true,
                secure: true,
                sameSite: 'Lax',
                priority: 'high',
            },
            prefix: '__Secure-auth.'
        },
        strategies: {
            local: {
                redirect: {
                    logout: "/auth",
                    login: "/auth"
                },
                user: {
                    property: "profile",
                },
                endpoints: {
                    login: {url: "/oauth/token", method: "post", alias: "auth token"},
                    user: {url: "/api/profile", method: "get"},
                    "2fa": {url: "/api/send-token-2fa", method: "post"},
                },
            }
        }
    },
});

A configuração da propriedade auth.csrf também é opcional. Nela, você pode definir o endpoint da rota /csrf-token do Laravel, que é responsável por fornecer o CSRF Token. Isso melhora a segurança ao validar as rotas protegidas que utilizam CSRF Token.

Exemplo de Implementação no Laravel

Definição da rota no web.php

Route::get('/csrf-token', function () {
    return response()->json(['csrf_token' => csrf_token()])
        ->header('Access-Control-Allow-Origin', '*')
        ->header('Access-Control-Allow-Methods', 'GET, POST')
        ->header('Access-Control-Allow-Headers', 'Content-Type, X-CSRF-TOKEN');
});

Configuração do CORS (config/cors.php)

Adicione /csrf-cookie e /csrf-token às permissões de caminhos no CORS:

'paths' => ['api/*', 'csrf-cookie', 'csrf-token', 'oauth/*']

Exceções de CSRF (app/Http/Middleware/VerifyCsrfToken.php)

Para garantir que o token seja validado corretamente nas rotas de API, adicione as exceções:

protected $except = [
    '/api/*'
];

Runtime Config

A configuração do runtimeConfig do Nuxt 3 também precisa ser ajustada para incluir um objeto secret.
Este objeto deve conter os nomes das suas strategies, e dentro de cada uma delas, as seguintes chaves são * obrigatórias*:

Exemplo de Configuração:

export default defineNuxtConfig({
    runtimeConfig: {
        secret: {
            local: {
                client_id: 'YOUR_CLIENT_ID',
                client_secret: 'YOUR_CLIENT_SECRET',
                grant_type: 'password',
            },
            client: {
                client_id: 'YOUR_CLIENT_ID',
                client_secret: 'YOUR_CLIENT_SECRET',
                grant_type: 'authorization_code',
            }
        }
    }
});

Strategies

As configurações das strategies seguem a estrutura abaixo, iniciando com um nome de sua escolha para configurar o pacote.
As opções disponíveis estão listadas, indicando quais são obrigatórias e quais são opcionais.

Configuration

  • redirect: Defines the pages for redirection. (Required)

    • login: (Optional)
    • logout: (Required)
    • callback: (Optional)
    • home: (Optional)
  • endpoints: Defines the API routes configured in Laravel. (Required)

    • login: (Required)
      • url: (Required)
      • method: (Required)
      • alias: (Optional)
    • user: Contains user data. (Required)
      • url: (Required)
      • method: (Required)
    • "2fa": (Optional)
      • url: (Required)
      • method: (Required)
      • alias: (Optional)
    • logout: (Optional)
      • alias: (Optional)
  • ~~token: Name of the object returned from Laravel authentication. It is usually "access_token". (Required)~~

  • user: Name of the object containing user data. (Optional)


 strategies: {
            local: {
                redirect: {
                    logout: "/auth",
                    login: "/auth"
                },
                user: {
                    property: "profile",
                },
                endpoints: {
                    login: {url: "/oauth/token", method: "post", alias: "auth token"},
                    user: {url: "/api/profile", method: "get"},
                    "2fa": {url: "/api/send-token-2fa", method: "post"},
                },
            },
            client:{
                redirect: {
                    logout: "/auth",
                    login: "/auth"
                },
                endpoints: {
                    login: {url: "/oauth/token", method: "post"},
                    user: {url: "/api/profile", method: "get"},
                    "2fa": {url: "/api/send-token-2fa", method: "post"},
                    logout: {alias: 'logout client'}
                },
            }
        }

O 2FA é opcional, mas, se incluído em uma das "strategies", deve conter a URL e o método necessários para ativar o middleware "_2fa". Esse middleware não é global e pode ser utilizado seletivamente nas páginas do Nuxt.

 definePageMeta({
      middleware: ['auth', '_2fa']
    });

Cookie

| Option | Description | |-------------|-------------------------------------------------------------------------------------------------------------------------| | prefix | Default token prefix used in constructing a key for token storage. | | options | Additional cookie options, passed to cookie. | | path | Path where the cookie is visible. Default is /. | | expires | Specifies the lifetime of the cookie in number of days or a specific date. Default is session-only. | | maxAge | Specifies the number (in seconds) that will be the Max-Age value (preferably expired). | | domain | Domain (and by extension subdomains) where the cookie is visible. Default is the domain and all subdomains. | | secure | Defines whether the cookie requires a secure protocol (HTTPS). Default is false, should be set to true if possible. |

Notes:

  • By default, the prefix on localhost is set to "auth."
  • __Secure- prefix: Cookies with names starting with __Secure- (dash is part of the prefix) must be set with the secure flag from a secure page (HTTPS).
  • __Host- prefix: Cookies with names starting with __Host- must be set with the secure flag, must originate from a secure page (HTTPS), must not have a domain specified (and therefore are not sent to subdomains), and the path must be /.
cookie: {
        options: {
            httpOnly: true,
                secure: true,
                sameSite: 'Lax',
                priority: 'high',
            //maxAge: 24 * 60 * 60 * 1000,
        },
        prefix: '__Secure-auth.',
    }

Middlewares

O pacote nuxt-simple-auth disponibiliza dois middlewares: "auth" e "_2fa".
Eles não são globais e podem ser aplicados seletivamente às páginas do Nuxt.

  • auth: Restringe o acesso a páginas protegidas, garantindo que o usuário esteja autenticado via **Laravel Passport **, tanto no cliente quanto no servidor (SSR).
  • _2fa: Complementa a autenticação verificando os valores armazenados nos cookies e no sessionStorage para validar a autenticação de dois fatores (2FA), também funcionando no cliente e no servidor (SSR).
 definePageMeta({
      middleware: ['auth', '_2fa']
    });

Methods

| Método / Method | Descrição (PT) | Description (EN) | |------------------------------------|------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------| | loginWith(strategyName, ...args) | Define a estratégia atual e tenta realizar o login. Retorna uma Promise. | Sets the current strategy and attempts to log in. Returns a Promise. | | logout(strategyName) | Realiza o logout, garantindo a destruição dos cookies e do estado. | Logs out, ensuring the destruction of cookies and state. | | _2fa(strategyName, ...args) | Tenta validar o código de autenticação em dois fatores (2FA). Retorna uma Promise. | Attempts to validate the two-factor authentication (2FA) code. Returns a Promise. | | refreshToken(strategyName) | | | | $auth.headers.set(name, value) | Define um cabeçalho HTTP manualmente. | Sets an HTTP header manually. | | $auth.headers.get(name) | Obtém o valor de um cabeçalho HTTP. | Retrieves the value of an HTTP header. |


Usage Examples

loginWith

const {$auth} = useNuxtApp()

$auth.loginWith('local', data)
    .then(response => {
        // Logic after login
    })

logout

const {$auth} = useNuxtApp()

$auth.logout('local')

_2fa

$auth._2fa('local', data).then(response => {
    // Logic after 2FA validation
})

Headers and Requests

$auth.headers.set('name', 'value') // Sets a header  
$auth.headers.get('name') // Retrieves a header  

const {data, pending, error, refresh} = useFetch(url, {
    headers: $auth.headers,
})

⚖️ License

Released under MIT by @4slan.