Api response
In order to make sense of some of my code, each of my API responses is laid out as such:
Assumptions for the server api
We are making the assumption that the API server:
Authenticated api requests
For this portion, we’ll make use of Axios’ built-in interceptors feature, which allows us to modify requests and responses, as well as capture all errors. Thankfully, @nuxtjs/axios provides first-class support for this feature.
We’ll use a request interceptor to attach the access token to every API request.
Cauation if «main» was like this «main»:»index.js» on package.json file, change it to «main»: «app.js»
now its time we create some files:
nodemon.js root direcotry that you just made
on package.json will be on root directory add these lines of codes on scripts like as I did in below
app.js on root direcotry that you just made
constexpress=require("express");constbodyParser=require("body-parser");constmongoose=require("mongoose");// routesconstauthRouter=require("./routes/authRouter");constapp=express();app.use(bodyParser.json());app.use((req,res,next)=>{res.setHeader("Access-Control-Allow-Origin","*");res.setHeader("Access-Control-Allow-Methods","OPTIONS, GET, POST, PUT, PATCH, DELETE");res.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization");next();});app.use("/api/auth/",authRouter);app.use((error,req,res,next)=>{console.log(error);conststatus=error.statusCode||500;constmessage=error.message;constdata=error.data;res.status(status).json({message:message,data:data});});// connect to dbconstMONGOOSE_URI=`mongodb srv://${process.env.MONGO_USER}:${process.env.MONGO_PASS}@cluster0.4r3gv.mongodb.net/${process.env.MONGO_DB}`;mongoose.connect(MONGOOSE_URI).then((result)=>{app.listen(process.env.PORT||8080);}).catch((err)=>console.log(err));and
/controllers/authController.js
constbcrypt=require("bcryptjs");constuserModel=require("../models/userModel");constjwt=require("jsonwebtoken");exports.postSignin=async(req,res,next)=>{const{fullname,email,password}=req.body;try{constexsitUser=awaituserModel.findOne({email:email});if(exsitUser){consterror=newError("Eamil already exist, please pick another email!");res.status(409).json({error:"Eamil already exist, please pick another email! ",});error.statusCode=409;throwerror;}consthashedPassword=awaitbcrypt.hash(password,12);constuser=newuserModel({fullname:fullname,email:email,password:hashedPassword,});constresult=awaituser.save();res.status(200).json({message:"User created",user:{id:result._id,email:result.email},});}catch(err){if(!err.statusCode){err.statusCode=500;}next(err);}};letloadedUser;exports.postLogin=async(req,res,next)=>{const{email,password}=req.body;try{constuser=awaituserModel.findOne({email:email});if(!user){consterror=newError("user with this email not found!");error.statusCode=401;throwerror;}loadedUser=user;constcomparePassword=bcrypt.compare(password,user.password);if(!comparePassword){consterror=newError("password is not match!");error.statusCode=401;throwerror;}consttoken=jwt.sign({email:loadedUser.email},"expressnuxtsecret",{expiresIn:"20m",// it will expire token after 20 minutes and if the user then refresh the page will log out});res.status(200).json({token:token});}catch(err){if(!err.statusCode){err.statusCode=500;}next(err);}};exports.getUser=(req,res,next)=>{// this function will send user data to the front-end as I said above authFetch on the user object in nuxt.config.js will send a request and it will executeres.status(200).json({user:{id:loadedUser._id,fullname:loadedUser.fullname,email:loadedUser.email,},});};and
/middleware/isAuth.js
and
Congratulations!
We did it!As you can see, nuxt auth module is nice, but unfortunately requires some workarounds. I hope you found this article useful and won’t spend weeks like I did trying to fix those strange bugs (:
I did those things while improving my opensource project: BitcartCC.If you want to contribute to it or just see how I did it, check it out:
Creating a login page
Create a file called login.vue under the pages directory in your Nuxt.js project with the following content. Before loading it sends a request to /sanctum/csrf-cookie path, so that server could initialize CSRF protection for the application.
Express.js
That’s was our nuxt codes and now its time to make our API:
first of all make a directory and enter this command on Terminal/Cmd and npm init -ythen npm install express body-parser bcryptjs jsonwebtoken mongooseand thennpm install —save-dev nodemon it will add nodemon as a dev dependency
Express.js & mongodb (if you want also implement api)
so let’s start it
License
MIT License
Copyright (c) Nuxt Community
Login
Set the global settings for store login action.
- endpoint — Set the URL of the login endpoint. It can be a relative or absolute path.
Logout
Sets the global settings for store logout action.
- endpoint — Set the URL of the logout endpoint. It can be a relative or absolute path.
- method — Set the request to POST or GET.
Middleware
As my app will be 100% behind a login (except the login/register pages) I have set every page to require authorisation to be access. This can then be disabled on a page by page basis.
This is done by adding the following to our nuxt.config.js:
router:{
middleware:['auth']
}On each page you wish to disable this, you can put auth: false if you wish for anyone to see the page or auth: ‘guest’ if you only want non-authorised people to see (e.g. you don’t want people who are logged in to ever be faced with a login page themselves).
Note that this was a test project and typically you have to add some validation for client-side app inputs, and also server-side app
finally it’s done, hope you’ve enjoyed it, and there is my Github link that you can find the source code
Some suggestions that might be useful for you:
Nuxt application setup
Let’s begin by setting up the Nuxt.js app first, and then Laravel based API backend using Sanctum. Before that let me give you a little information on how to set up your domains in order to work with the Sanctum’s SPA authentication.
Create a new Nuxt.js project by entering the following command in your terminal.
npx create-nuxt-app your-project-nameNext, setup will ask you a series of questions, answers them as your preferences.
? Project name: sanctum-nuxt
? Project description: My fantastic Nuxt.js project
? Author name: Swapnil Bhavsar
? Choose the package manager: Npm
? Choose UI framework: Tailwind CSS
? Choose custom server framework: None (Recommended)
...Nuxt config
We should do some configuration in nuxt.config.js:
Nuxt.js
1- make a new app with npx create-nuxt-app front2- choose the Axios module when making new app (if you didn’t don’t worry we will install it later)3- install nuxt module and the Axios if you didn’t yarn add —exact @nuxtjs/auth-nextyarn add @nuxtjs/axiosor with npm npm install —save-exact @nuxtjs/auth-nextnpm install @nuxtjs/axios
then add it on nuxt.config.js like below:
now it’s time to add options on auth module :
auth:{strategies:{local:{// scheme: "refresh",token:{property:"token",//property name that the Back-end sends for you as a access token for saving on localStorage and cookie of user browserglobal:true,required:true,type:"Bearer"},user:{property:"user",autoFetch:true},// refreshToken: { // it sends request automatically when the access token expires, and its expire time has set on the Back-end and does not need to we set it here, because is useless// property: "refresh_token", // property name that the Back-end sends for you as a refresh token for saving on localStorage and cookie of user browser// data: "refresh_token", // data can be used to set the name of the property you want to send in the request.// },endpoints:{login:{url:"/api/auth/login",method:"post"},// refresh: { url: "/api/auth/refresh-token", method: "post" },logout:false,// we don't have an endpoint for our logout in our API and we just remove the token from localstorageuser:{url:"/api/auth/user",method:"get"}}}}},and here is the config for the Axios that I recommend to use it:
Tip: if your back-end project has implemented Refresh token you should uncomment the refresh endpoint and change it to the right endpoint which your back-end gave you and also you should uncomment these refreshToken object and also scheme: refresh
now we make some components:
/components/Auth/Login/index.vue
/components/Auth/Register/index.vue
and
/components/Home/index.vue
and
Prerequisites
- Familiarity with django-rest-framework
- Knowledge of nuxt-auth: this video will be enough
Refresh tokens
However, what happens when the access token expires? For security reasons, access tokens shouldn’t be long-lived and should be easily revocable if necessary.
Setting up laravel sanctum
Enough of theory! Let’s begin by setting up Laravel sanctum for your Laravel application. Just follow these steps carefully to configure your app.
In your Laravel 7 app, install the sanctum package using composer:
composer require laravel/sanctumNext, publish sanctum configuration & database migration files.
php artisan vendor:publish --provider="LaravelSanctumSanctumServiceProvider"Setup
- Add
@nuxtjs/authdependency using yarn or npm to your project - Add
@nuxtjs/authand@nuxtjs/axiostomodulessection ofnuxt.config.js
{modules: ['@nuxtjs/auth',// ...Axios module should be included AFTER @nuxtjs/auth'@nuxtjs/axios'],// Default Valuesauth: {user: {endpoint: 'auth/user',propertyName: 'user',resetOnFail: true,enabled: true,method: 'GET',},login: {endpoint: 'auth/login',},logout: {endpoint: 'auth/logout',method: 'GET',},redirect: {notLoggedIn: '/login',loggedIn: '/'},token: {enabled: true,type: 'Bearer',localStorage: true,name: 'token',cookie: true,cookieName: 'token'}}Token
- enabled (Boolean) — Get and use tokens for authentication.
- type — Sets the token type of the authorization header.
- localStorage(Boolean) — Keeps token in local storage, if enabled.
- name — Set the token name in the local storage.
- cookie (Boolean) — Keeps token in cookies, if enabled.
- cookieName — Set the token name in Cookies.
Frontend setup
Nuxt.js docs recommend using @nuxtjs/authpackage.It supports different auth schemes and stuff, but it doesn’t support refresh token out of the box.As we have quite a simple API, I picked up local auth scheme.
Backend situation
Let’s assume the following situation:We have a backend, serving a few endpoints:
Setting up the backend
Install the following packages in your virtual environment:
Conclusion
https://www.youtube.com/watch?v=eRHcbizg29g
This is a bare minimum example for you to get started with authentication in Nuxt.js using Laravel Sanctum. I am pretty amazed by the simplicity provided by the Sanctum package over Laravel Passport when implementing API authentication for your applications.
Вход в личный кабинет