{"id":20270287,"url":"https://github.com/4sllan/nuxt-simple-auth","last_synced_at":"2025-04-11T04:02:30.021Z","repository":{"id":212346335,"uuid":"731275147","full_name":"4sllan/nuxt-simple-auth","owner":"4sllan","description":"AuthX","archived":false,"fork":false,"pushed_at":"2025-04-01T23:30:11.000Z","size":402,"stargazers_count":1,"open_issues_count":0,"forks_count":1,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-04-11T04:02:27.377Z","etag":null,"topics":["auth","fecth","laravel","laravel-passport","module","nuxt","nuxt-module","nuxt3","security","ssr","token"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/4sllan.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":".github/FUNDING.yml","license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null},"funding":{"github":"4sllan","ko_fi":null,"tidelift":null,"community_bridge":null,"liberapay":null,"issuehunt":null,"otechie":null,"custom":null}},"created_at":"2023-12-13T18:03:09.000Z","updated_at":"2025-04-01T14:04:57.000Z","dependencies_parsed_at":"2023-12-13T20:40:12.641Z","dependency_job_id":"a0660c56-ae78-40d5-8045-eb1da7ef1b12","html_url":"https://github.com/4sllan/nuxt-simple-auth","commit_stats":null,"previous_names":["4slan-g/nuxt-simple-auth","4slank/nuxt-simple-auth","4sllan/nuxt-simple-auth"],"tags_count":21,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/4sllan%2Fnuxt-simple-auth","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/4sllan%2Fnuxt-simple-auth/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/4sllan%2Fnuxt-simple-auth/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/4sllan%2Fnuxt-simple-auth/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/4sllan","download_url":"https://codeload.github.com/4sllan/nuxt-simple-auth/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248339285,"owners_count":21087215,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["auth","fecth","laravel","laravel-passport","module","nuxt","nuxt-module","nuxt3","security","ssr","token"],"created_at":"2024-11-14T12:29:36.120Z","updated_at":"2025-04-11T04:02:30.008Z","avatar_url":"https://github.com/4sllan.png","language":"TypeScript","funding_links":["https://github.com/sponsors/4sllan"],"categories":[],"sub_categories":[],"readme":"\u003cdiv align=\"center\"\u003e\n\u003cimg src=\".github/nuxt-simple-auth.svg\" width=\"200\"\u003e\n\u003c/div\u003e\n\u003ch1 align=\"center\"\u003e Auth Module Simple\u003c/h1\u003e\n    \u003cp align=\"center\"\u003eAuthentication support for Nuxt 3\u003c/p\u003e\n\u003cbr\u003e\n\n## nuxt-simple-auth\n\n\u003cbr\u003e\n\n[![npm version](https://img.shields.io/npm/v/nuxt-simple-auth/latest.svg?style=flat-square\u0026colorA=18181B\u0026colorB=28CF8D)](https://www.npmjs.com/package/nuxt-simple-auth)\n![GitHub License][license]\n[![npm downloads](https://img.shields.io/npm/dt/nuxt-simple-auth.svg?style=flat-square\u0026colorA=18181B\u0026colorB=28CF8D)](https://www.npmjs.com/package/nuxt-simple-auth)\n[![Nuxt][nuxt-src]][nuxt-href]\n[![Static Badge](https://img.shields.io/badge/-%E2%99%A5%20Sponsors-ec5cc6?style=flat-square)](https://github.com/sponsors/4sllan)\n\n\n\n\u003e **nuxt-simple-auth** is an authentication module for **Nuxt 3**, designed as an **open-source**, **robust**, and *\n*feature-rich** package. It enables **cookie** validation and **CSRF** protection, seamlessly integrating with **Laravel\nPassport**.\\\n\u003e Additionally, it supports various cookie parameters for both **login** and **two-factor authentication (2FA)**.\\\n\u003e It also includes **SSR authentication** support, ensuring that the user remains authenticated on both the **client**\n\u003e and the **server**.\n\n\u003e While the package is stable in terms of options and behavior, there are still improvements to be made, and some bugs\n\u003e may exist.\n\n\n- [Release Notes](/CHANGELOG.md)\n\n## Start\n\n```sh\nnpx nuxi@latest module add nuxt-simple-auth\n```\n\n## Setup\n\n### Installation\n\n\u003e **Add `nuxt-simple-auth` to the `modules` section in `nuxt.config.js`.**\n\n### Configuration\n\nThe configuration must be done in the `nuxt.config.js` file by adding the library to the **modules** section.\n\nIn the `auth` property, defining **strategies** is **mandatory**, while **cookies** and **CSRF** settings are **optional\n**.\n\nFor authentication, the `endpoints.login` property requires the use of **Laravel Passport**, which must expose\nthe `/oauth/token` route.  \n[Laravel Passport Documentation - Client Credentials Grant Tokens](https://laravel.com/docs/12.x/passport#client-credentials-grant-tokens)\n\nThis route must return a JSON response containing the following attributes:\n\n- `access_token`\n- `refresh_token`\n- `expires_in`\n\nIf you choose to use **2FA** authentication, the package requires the configuration of `endpoints.2fa`, which mandates\nthat **Laravel** exposes a specific route.  \nThis route should return a JSON response with the following attributes:\n\n- `access_token`\n- `expires_in`\n\n`expires_in`: Must be the number of seconds until the **2FA** access token expires.\n\n[//]: # (Example implementation in Laravel for the `TwoFactorAuthController` route controller:)\n\n[//]: # ()\n\n[//]: # (```php)\n\n[//]: # (return response\u0026#40;\u0026#41;-\u003ejson\u0026#40;[)\n\n[//]: # (    'access_token' =\u003e $twoFactorAuth-\u003etoken,)\n\n[//]: # (    'expires_in' =\u003e $twoFactorAuth-\u003eexpire_at-\u003etimestamp - now\u0026#40;\u0026#41;-\u003etimestamp, // Number of seconds until expiration.)\n\n[//]: # (]\u0026#41;;)\n\n[//]: # (```)\n\nAfter **2FA** validation, the token will be automatically added to the **headers** of requests as a **Bearer Token**,\nwith the name `\"2fa\"`.  \nThis allows **Laravel APIs** to validate authentication on protected routes.\n\n#### Example\n\n```js\nexport default defineNuxtConfig({\n    modules: [\n        'nuxt-simple-auth'\n    ],\n\n    auth: {\n        csrf: '/csrf-token',\n        cookie: {\n            options: {\n                httpOnly: true,\n                secure: true,\n                sameSite: 'Lax',\n                priority: 'high',\n            },\n            prefix: '__Secure-auth.'\n        },\n        strategies: {\n            local: {\n                redirect: {\n                    logout: \"/auth\",\n                    login: \"/auth\"\n                },\n                user: {\n                    property: \"profile\",\n                },\n                endpoints: {\n                    login: {url: \"/oauth/token\", method: \"post\", alias: \"auth token\"},\n                    user: {url: \"/api/profile\", method: \"get\"},\n                    \"2fa\": {url: \"/api/send-token-2fa\", method: \"post\"},\n                },\n            }\n        }\n    },\n});\n```\n\n### Runtime Config\n\nThe **runtimeConfig** of Nuxt 3 must also be configured to include a `secret` object.  \nThis object should contain the names of your **strategies**, and within each strategy, the following keys are **required\n**:\n\n- [`client_id`](https://laravel.com/docs/12.x/passport#main-content)\n- [`client_secret`](https://laravel.com/docs/12.x/passport#main-content)\n- [`grant_type`](https://laravel.com/docs/12.x/passport#main-content)\n\n#### Example Configuration:\n\n```js\nexport default defineNuxtConfig({\n    runtimeConfig: {\n        secret: {\n            local: {\n                client_id: 'YOUR_CLIENT_ID',\n                client_secret: 'YOUR_CLIENT_SECRET',\n                grant_type: 'password',\n            },\n            client: {\n                client_id: 'YOUR_CLIENT_ID',\n                client_secret: 'YOUR_CLIENT_SECRET',\n                grant_type: 'authorization_code',\n            }\n        }\n    }\n});\n```\n\n### Strategies\n\nThe **strategies** configuration follows the structure below, starting with a name of your choice to set up the\npackage.  \nThe available options are listed, indicating which are **required** and which are **optional**.\n\n#### Configuration\n\n- **`redirect`**: Defines the pages for redirection. _(Required)_\n    - `login`: _(Optional)_\n    - `logout`: _(Required)_\n    - `callback`: _(Optional)_\n    - `home`: _(Optional)_\n\n- **`endpoints`**: Defines the API routes configured in Laravel. _(Required)_\n    - `login`: _(Required)_\n        - `url`: _(Required)_\n        - `method`: _(Required)_\n        - `alias`: _(Optional)_\n    - `user`: Contains user data. _(Required)_\n        - `url`: _(Required)_\n        - `method`: _(Required)_\n    - `\"2fa\"`: _(Optional)_\n        - `url`: _(Required)_\n        - `method`: _(Required)_\n        - `alias`: _(Optional)_\n    - `logout`: _(Optional)_\n        - `alias`: _(Optional)_\n\n- **`user`**: Name of the object containing user data. _(Optional)_\n\n---\n\n``` js\n strategies: {\n            local: {\n                redirect: {\n                    logout: \"/auth\",\n                    login: \"/auth\"\n                },\n                user: {\n                    property: \"profile\",\n                },\n                endpoints: {\n                    login: {url: \"/oauth/token\", method: \"post\", alias: \"auth token\"},\n                    user: {url: \"/api/profile\", method: \"get\"},\n                    \"2fa\": {url: \"/api/send-token-2fa\", method: \"post\"},\n                },\n            },\n            client:{\n                redirect: {\n                    logout: \"/auth\",\n                    login: \"/auth\"\n                },\n                endpoints: {\n                    login: {url: \"/oauth/token\", method: \"post\"},\n                    user: {url: \"/api/profile\", method: \"get\"},\n                    \"2fa\": {url: \"/api/send-token-2fa\", method: \"post\"},\n                    logout: {alias: 'logout client'}\n                },\n            }\n        }\n```\n\n**2FA** is optional, but if included in one of the \"strategies,\" it must have a URL and method to enable the \"_2fa\"\nmiddleware. This middleware is not global and can be selectively used on Nuxt pages.\n\n``` js\n definePageMeta({\n      middleware: ['auth', '_2fa']\n    });\n```\n\n### Cookie\n\n| Option      | Description                                                                                                             |\n|-------------|-------------------------------------------------------------------------------------------------------------------------|\n| **prefix**  | Default token prefix used in constructing a key for token storage.                                                      |\n| **options** | Additional cookie options, passed to [cookie](https://github.com/jshttp/cookie?tab=readme-ov-file).                     |\n| **path**    | Path where the cookie is visible. Default is `/`.                                                                       |\n| **expires** | Specifies the lifetime of the cookie in number of days or a specific date. Default is session-only.                     |\n| **maxAge**  | Specifies the number (in seconds) that will be the Max-Age value (preferably expired).                                  |\n| **domain**  | Domain (and by extension subdomains) where the cookie is visible. Default is the domain and all subdomains.             |\n| **secure**  | Defines whether the cookie requires a secure protocol (HTTPS). Default is `false`, should be set to `true` if possible. |\n\n### Notes:\n\n- By default, the prefix on `localhost` is set to `\"auth.\"`\n- **`__Secure-` prefix:** Cookies with names starting with `__Secure-` (dash is part of the prefix) must be set with the\n  secure flag from a secure page (HTTPS).\n- **`__Host-` prefix:** Cookies with names starting with `__Host-` must be set with the secure flag, must originate from\n  a secure page (HTTPS), must not have a domain specified (and therefore are not sent to subdomains), and the path must\n  be `/`.\n\n``` js\ncookie: {\n        options: {\n            httpOnly: true,\n                secure: true,\n                sameSite: 'Lax',\n                priority: 'high',\n            //maxAge: 24 * 60 * 60 * 1000,\n        },\n        prefix: '__Secure-auth.',\n    }\n```\n\n### Middlewares\n\nThe **nuxt-simple-auth** package provides two middlewares: **\"auth\"** and **\"_2fa\"**.  \nThey are **not global** and can be applied selectively to Nuxt pages.\n\n- **auth**: Restricts access to protected pages, ensuring the user is authenticated via **Laravel Passport**, both on\n  the client and server (**SSR**).\n- **_2fa**: Enhances authentication by verifying values stored in **cookies** and **sessionStorage** to validate *\n  *two-factor authentication (2FA)**, also working on both the client and server (**SSR**).\n\n``` js\n definePageMeta({\n      middleware: ['auth', '_2fa']\n    });\n```\n\n### Methods\n\n| Método / Method                    | Description                                                                             |\n|------------------------------------|-----------------------------------------------------------------------------------------|\n| `loginWith(strategyName, ...args)` | Sets the current strategy and attempts to log in. Returns a `Promise`.                  |\n| `logout(strategyName)`             | Logs out, ensuring the destruction of cookies and state.                                |\n| `_2fa(strategyName, ...args)`      | Attempts to validate the two-factor authentication (**2FA**) code. Returns a `Promise`. |\n| `refreshToken(strategyName)`       |                                                                                         |\n| `$auth.headers.set(name, value)`   | Sets an HTTP header manually.                                                           |\n| `$auth.headers.get(name)`          | Retrieves the value of an HTTP header.                                                  |\n\n---\n\n### Usage Examples\n\n#### `loginWith`\n\n```js\nconst {$auth} = useNuxtApp()\n\n$auth.loginWith('local', data)\n    .then(response =\u003e {\n        // Logic after login\n    })\n\n```\n\n#### `logout`\n\n```js\nconst {$auth} = useNuxtApp()\n\n$auth.logout('local')\n\n```\n\n#### `_2fa`\n\n```js\n$auth._2fa('local', data).then(response =\u003e {\n    // Logic after 2FA validation\n})\n\n```\n\n#### `Headers and Requests`\n\n```js\n$auth.headers.set('name', 'value') // Sets a header  \n$auth.headers.get('name') // Retrieves a header  \n\nconst {data, pending, error, refresh} = useFetch(url, {\n    headers: $auth.headers,\n})\n\n```\n\n## ⚖️ License\n\nReleased under [MIT](/LICENSE) by [@4slan](https://github.com/4sllan).\n\n\n[license]: https://img.shields.io/github/license/4sllan/nuxt-simple-auth?style=flat-square\u0026colorA=18181B\u0026colorB=28CF8D\n\n[nuxt-src]: https://img.shields.io/badge/Nuxt-18181B?logo=nuxt.js\n\n[nuxt-href]: https://nuxt.com","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2F4sllan%2Fnuxt-simple-auth","html_url":"https://awesome.ecosyste.ms/projects/github.com%2F4sllan%2Fnuxt-simple-auth","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2F4sllan%2Fnuxt-simple-auth/lists"}