search
HomePHP FrameworkLaravelThe difference between laravel's passport and jwt

The difference between laravel's passport and jwt

Introduction

Passport is a Node.js middleware that provides a variety of different request authentications that are easy to implement. Strategy. By default, it stores the user object in the session. (Recommended learning: laravel development)

JSON Web Token is an authentication standard that works by assigning and passing encrypted tokens in requests that help identify logged in users , instead of storing the user in a session on the server and creating a cookie to work. It has different integrations, including Node.js modules.

Install dependencies.

npm install --save koa-passport  passport-jwt jsonwebtoken

Process

When the user logs in, the backend creates the signed token and returns it as a response

The client is in Save the token locally (usually in localStorage) and send it back on every subsequent request that requires authentication

All requests that require authentication check the provided token through the middleware, and only The request is only allowed when the token is verified

Token when logging in

/**
 * @route POST api/users/login
 * @desc 用户登录接口
 * @access 都可访问
 */
router.post('/login', async ctx => {
    	//...获取数据 验证数据省略
        const payload = {
            name: user.name,
            email,
            avatar: user.avatar
        };
        //生成token
        const token = jwt.sign(payload, config.secretKey, {
            expiresIn: 3600 //存活时间
        });
        ctx.status = 200;
        ctx.body = {
            message: '验证成功',
            token: 'Bearer ' + token
        }
})

Note: There must be a space in the middle of 'Bearer', and the case is also distinguished...

Login parsing Token

/**
 * @route GET api/users/current
 * @desc 获取用户信息
 * @access 私密接口
 */
 //poassport.authenticate 则加入了认证权限,会调用 passport.js中
router.get('/current',passport.authenticate('jwt', { session: false }),async ctx=>{
	//获取 passport.js 中的返回值,去除密码并将结果返回到客户端
    const {password,...userInfo}=ctx.state.user._doc;
    ctx.body=userInfo;
})

//app.js
const passport = require('koa-passport');
app.use(passport.initialize())
app.use(passport.session())
//调用 passport.js 并将passport传入
require('./config/passport')(passport);

config/passport.js

const config=require('./default');
const JwtStrategy = require('passport-jwt').Strategy,
    ExtractJwt = require('passport-jwt').ExtractJwt;
const opts = {}
opts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken();
opts.secretOrKey = config.secretKey;
// const User=require('../models/User');
const mongoose=require('mongoose');
const User=mongoose.model('users');
module.exports=passport=>{
    passport.use(new JwtStrategy(opts,async (jwt_payload,done)=>{
    	//jwt_payload 返回的是登录时返回的数据 即payload
        const user=await User.findOne(jwt_payload.id);
        if(user){
            done(null,user);
        }else{
            done(null,false);
        }
    }))
}

ps. This is the complete code of the user login template

app.js

const Koa=require('koa');
const KoaRouter=require('koa-router');
const bodyParser=require('koa-bodyparser');
const mongoose=require('mongoose');
//const config=require('./config/default')
const passport = require('koa-passport');
//配置文件 这里就不单独抽离
const config={
	mogoUrl:'mongodb://localhost/koaTest',
    secretKey:'sercretKey',
}

const router=new KoaRouter();
const app=new Koa();

app.use(bodyParser());
//初始化 passport
app.use(passport.initialize())
app.use(passport.session())


//连接数据库
mongoose.connect(config.mogoUrl,{
    useNewUrlParser:true
}).then(res=>{
    console.log('mongoose connectd...');
})
.catch(error=>{
    console.log(error)
})

//引入 user.js
const user=require('./routes/api/user');

require('./config/passport')(passport);

//配置路由地址
router.use('/api/users',user);

//配置路由
app.use(router.routes()).use(router.allowedMethods());
const port=process.env.PORT||5000;
//监听端口
app.listen(port,()=>{
    console.log(`listing at ${port}`)
})

routes/api/user.js

var Router = require('koa-router');
var router = new Router();
const User = require('../../models/User')
const bcrypt = require('bcryptjs');
const tools = require('../../config/tools')

const jwt = require('jsonwebtoken'); //token 认证
const config = require('../../config/default');
const passport=require('koa-passport');

/**
 * @route POST api/users/login
 * @desc 用户登录接口
 * @access 都可访问
 */
router.post('/login', async ctx => {
    const {
        email,
        password
    } = ctx.request.body;
    const findResult = await User.find({
        email
    });
    const user = findResult[0];
    if (findResult.length === 0) {
        //表示不存在该用户
        ctx.status = 404;
        ctx.body = {
            message: '该用户不存在'
        };
        return;
    }
    //验证密码是否正确
    const verify = bcrypt.compareSync(password, user.password);
    if (verify) {
        //密码正确
        const payload = {
            name: user.name,
            email,
            avatar: user.avatar
        };
        //生成token
        const token = jwt.sign(payload, config.secretKey, {
            expiresIn: 3600
        });

        ctx.status = 200;
        ctx.body = {
            message: '验证成功',
            token: 'Bearer ' + token
        }
    } else {
        ctx.status = 500;
        ctx.body = {
            message: '密码错误'
        };
    }

})

/**
 * @route GET api/users/current
 * @desc 获取用户信息
 * @access 私密接口
 */
router.get('/current',passport.authenticate('jwt', { session: false }),async ctx=>{
    const {password,...userInfo}=ctx.state.user._doc;
    ctx.body=userInfo;
})
module.exports = router.routes();

The above is the detailed content of The difference between laravel's passport and jwt. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Laravel's Impact: Simplifying Web DevelopmentLaravel's Impact: Simplifying Web DevelopmentApr 21, 2025 am 12:18 AM

Laravel stands out by simplifying the web development process and delivering powerful features. Its advantages include: 1) concise syntax and powerful ORM system, 2) efficient routing and authentication system, 3) rich third-party library support, allowing developers to focus on writing elegant code and improve development efficiency.

Laravel: Frontend or Backend? Clarifying the Framework's RoleLaravel: Frontend or Backend? Clarifying the Framework's RoleApr 21, 2025 am 12:17 AM

Laravelispredominantlyabackendframework,designedforserver-sidelogic,databasemanagement,andAPIdevelopment,thoughitalsosupportsfrontenddevelopmentwithBladetemplates.

Laravel vs. Python: Exploring Performance and ScalabilityLaravel vs. Python: Exploring Performance and ScalabilityApr 21, 2025 am 12:16 AM

Laravel and Python have their own advantages and disadvantages in terms of performance and scalability. Laravel improves performance through asynchronous processing and queueing systems, but due to PHP limitations, there may be bottlenecks when high concurrency is present; Python performs well with the asynchronous framework and a powerful library ecosystem, but is affected by GIL in a multi-threaded environment.

Laravel vs. Python (with Frameworks): A Comparative AnalysisLaravel vs. Python (with Frameworks): A Comparative AnalysisApr 21, 2025 am 12:15 AM

Laravel is suitable for projects that teams are familiar with PHP and require rich features, while Python frameworks depend on project requirements. 1.Laravel provides elegant syntax and rich features, suitable for projects that require rapid development and flexibility. 2. Django is suitable for complex applications because of its "battery inclusion" concept. 3.Flask is suitable for fast prototypes and small projects, providing great flexibility.

Frontend with Laravel: Exploring the PossibilitiesFrontend with Laravel: Exploring the PossibilitiesApr 20, 2025 am 12:19 AM

Laravel can be used for front-end development. 1) Use the Blade template engine to generate HTML. 2) Integrate Vite to manage front-end resources. 3) Build SPA, PWA or static website. 4) Combine routing, middleware and EloquentORM to create a complete web application.

PHP and Laravel: Building Server-Side ApplicationsPHP and Laravel: Building Server-Side ApplicationsApr 20, 2025 am 12:17 AM

PHP and Laravel can be used to build efficient server-side applications. 1.PHP is an open source scripting language suitable for web development. 2.Laravel provides routing, controller, EloquentORM, Blade template engine and other functions to simplify development. 3. Improve application performance and security through caching, code optimization and security measures. 4. Test and deployment strategies to ensure stable operation of applications.

Laravel vs. Python: The Learning Curves and Ease of UseLaravel vs. Python: The Learning Curves and Ease of UseApr 20, 2025 am 12:17 AM

Laravel and Python have their own advantages and disadvantages in terms of learning curve and ease of use. Laravel is suitable for rapid development of web applications. The learning curve is relatively flat, but it takes time to master advanced functions. Python's grammar is concise and the learning curve is flat, but dynamic type systems need to be cautious.

Laravel's Strengths: Backend DevelopmentLaravel's Strengths: Backend DevelopmentApr 20, 2025 am 12:16 AM

Laravel's advantages in back-end development include: 1) elegant syntax and EloquentORM simplify the development process; 2) rich ecosystem and active community support; 3) improved development efficiency and code quality. Laravel's design allows developers to develop more efficiently and improve code quality through its powerful features and tools.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version