当前位置:网站首页>Login to verify the simple use of KOA passport Middleware
Login to verify the simple use of KOA passport Middleware
2022-07-06 17:03:00 【Society, you Lei brother, life is hard, don't bend down】
sketch
koa-passport
yes koa
One of the middleware , It's actually just right passport
An encapsulation of . utilize koa-passport
It can easily realize the login and registration function , Not only local authentication , There are also many modules that provide third-party login . This blog only talks about some simple contents of login verification
To configure
Installation dependency
npm install -S koa-passport
npm install -S passport-local
Leading package
import passport from 'koa-passport'
import LocalStrategy from 'passport-local'
import UserModel from '../../dbs/models/users'
Configure authentication policy
koa-passport By default username
and password
Do validation
passport.use(new LocalStrategy(async function(username, password, done) {
let where = {
username
};
// Look for the entered user information in the database
let result = await UserModel.findOne(where)
if (result != null) {
if (result.password === password) {
return done(null, result)
} else {
return done(null, false, ' Wrong password ')
}
} else {
return done(null, false, ' The user doesn't exist ')
}
}))
serialize
After the user's login verification is successful, the user's data will be stored in session
in , Calling ctx.login()
Serialization operation will be triggered , Save the user object to session
in .
passport.serializeUser(function(user, done) {
done(null, user)
})
Deserialization
Each request will be from session
Read user objects in ,session
If there is "passport":{"user":"xxx"}
Will trigger the de serialization operation defined
passport.deserializeUser(function(user, done) {
return done(null, user)
})
Don't forget export default passport
Export the configured module
Use
import Koa from 'koa'
import session from 'koa-generic-session'
import Redis from 'koa-redis'
import passport from './interface/utils/passport'
const app = new Koa()
// session Encryption processing of
app.keys = ['mt', 'keyskeys']
app.use(session({
key: 'mt',
prefix: 'mt:uid',
store: new Redis()
}))
//initialzie() The function is used to add passport Field , Will be in ctx Mount the following methods
//ctx.state.user Authenticated user
//ctx.login(user) The logged in user
//ctx.logout() User log out
//ctx.isAuthenticated() Determine whether to authenticate
app.use(passport.initialize())
// Turn on koa-passport Yes session Support for ,passport.session() Is to make passport Can from session To extract user information
app.use(passport.session())
Login component
router.post('/signin', async(ctx, next) => {
return Passport.authenticate('local', function(err, user, info, status) {
if (err) {
ctx.body = {
code: -1,
msg: err
}
} else {
if (user) {
//user It's the data we found in the database
ctx.body = {
code: 0,
msg: ' Login successful ',
user
}
// It can store users' session
return ctx.login(user)
} else {
ctx.body = {
code: 1,
//info It is the information judged in the verification , The password is incorrect or the user does not exist
msg: info
}
}
}
})(ctx, next)
})
Components after successful login
router.get('/getUser', async(ctx) => {
if (ctx.isAuthenticated()) {
// The strategy passes done take user It's stored in session in , And will sessionID Written to the client cookie On ,
// Attach user information to the request object req.session.passport.user On
const {
username, email } = ctx.session.passport.user
ctx.body = {
user: username,
email
}
} else {
ctx.body = {
user: '',
email: ''
}
}
})
Exit the logged in component
router.get('/exit', async(ctx, next) => {
//logout Method can delete a user's session, With no arguments
await ctx.logout()
if (!ctx.isAuthenticated()) {
ctx.body = {
code: 0
}
} else {
ctx.body = {
code: -1
}
}
})
边栏推荐
- ~69 other ways to use icon fonts
- MySQL字符串函数
- The "advertising maniacs" in this group of programmers turned Tiktok advertisements into ar games
- 原型链继承
- Activiti directory (III) deployment process and initiation process
- Conception du système de thermomètre numérique DS18B20
- How to configure hosts when setting up Eureka
- The daemon thread starts redis and modifies the configuration file
- 唯有学C不负众望 TOP3 Demo练习
- Shell_ 02_ Text three swordsman
猜你喜欢
Activiti目录(四)查询代办/已办、审核
J'ai traversé le chemin le plus fou, le circuit cérébral d'un programmeur de saut d'octets
Activiti目录(五)驳回、重新发起、取消流程
字节跳动春招攻略:学长学姐笔经面经,还有出题人「锦囊」
TCP的三次握手和四次挥手
Install docker under windows10 (through Oracle VM VirtualBox)
~73 other text styles
~86m rabbit practice
[unsolved]7-14 calculation diagram
一个数10年工作经验的微服务架构老师的简历
随机推荐
7-10 punch in strategy
Shell_ 05_ operator
Thank you for your invitation. I'm in the work area. I just handed in the code. I'm an intern in the next ByteDance
Erlang installation
Yao BanZhi and his team came together, and the competition experts gathered together. What fairy programming competition is this?
Activit零零碎碎要人命的坑
Resume of a microservice architecture teacher with 10 years of work experience
我走过最迷的路,是字节跳动程序员的脑回路
Fdog series (4): use the QT framework to imitate QQ to realize the login interface, interface chapter.
The most lost road I have ever walked through is the brain circuit of ByteDance programmers
was unable to send heartbeat
Eureka single machine construction
字节跳动2022校招研发提前批宣讲会,同学们最关心的10个问题
8086 memory
MySQL日期函数
汇编语言寻址方式
How to generate six digit verification code
8086 CPU 内部结构
在 vi 编辑器中的命令模式下,删除当前光标处的字符使用 __ 命 令。
程序员定位解决问题方法论