本篇文章主要介紹了node.js+captchapng+jsonwebtoken實現登入驗證範例,具有一定的參考價值,有興趣的可以了解一下
提到登入驗證,大家一定能想到的就是12306的驗證碼了吧。 12306為了防止刷票,可以說是煞費苦心,驗證碼也越來越難識別,最終即使是人也可能識別不了了。
今天,小編就跟大家說一下node如何實作圖片驗證碼,以及使用token驗證登入。學習本文你將學到:
1.使用captchapng產生圖片驗證碼
2.使用jsonwebtoken實現登入驗證
一、圖片驗證碼產生(最後有全部程式碼)。一下流程,第一步伺服器要隨機產生一組四位數。
第二步,將這四位數以canvas繪圖產生圖片。
第三步,我們要將這四位數存起來,以便使用者回傳資料時做比較。
那麼存到哪裡呢?很明顯為了區分用戶,存到session最穩。
第一步,先要有一個登入頁面。這裡我們還是用react,
login.tsx
import * as React from 'react' import * as ReactDom from 'react-dom' import {Link, browserHistory} from 'react-router'; import * as axios from 'axios'; export default class Login extends React.Component<any,any>{ constructor(props){ super(props) this.state = { userName : '', password : '', yzNoId : '', hash : Math.random() } } handleUserName(e) : any { this.setState({ userName : e.target.value }) } handlePassword(e) : any { this.setState({ password : e.target.value }) } handleYzId(e) : any { this.setState({ yzNoId : e.target.value }) } render(){ const { userName, password, yzNoId } = this.state; return( <p> <p className="nav-wrap"> <ul className="nav"> <li><Link to="/home">首页</Link></li> <li><Link to="/imgLoad">上传</Link></li> <li><Link to="/login">登陆</Link></li> </ul> </p> <p className="content"> <p className="login-warp"> <p> <input type="text" className="username" value={userName} onChange={this.handleUserName.bind(this)} placeholder="用户名"/> </p> <p> <input type="text" className="password" value={password} onChange={this.handlePassword.bind(this)} placeholder="密码"/> </p> <p> <input type="text" className="yz" value={yzNoId} onChange={this.handleYzId.bind(this)} placeholder="验证码"/> <img src={"http://localhost:3000/captcha"} className="yz-img" /> </p> <p> <input type="button" className="submit" value="登陆" onClick={this.sbumit.bind(this,{userName:userName,password:password,captcha:yzNoId})} /> </p> </p> </p> </p> ) } }
頁面是這樣的
我們需要透過伺服器給一張驗證圖片。
router/index.js 加入以下程式碼
var Login = require('./controller/login'); var login = new Login; router.get('/captcha', login.captcha); router.post('/login',login.loginer); login是定义在控制器的一个类的实例,captcha,loginer是它的方法。分别是返回验证图片、登录验证。 controller/login.js var rf = require('fs'); var captchapng = require('captchapng'); class Login { constructor(){} captcha(req, res, next) { var str = parseInt(Math.random()*9000+1000); //随机生成数字 req.session.captcha = str; // 存入session var p = new captchapng(80, 30, str); //生成图片 p.color(0, 0, 0, 0); p.color(80, 80, 80, 255); var img = p.getBase64(); var imgbase64 = new Buffer(img, 'base64'); res.writeHead(200, { 'Content-Type': 'image/png' }); res.end(imgbase64); } loginer(req, res, next) { let captcha = req.body.captcha; let userName = req.body.userName; let password = req.body.password; if (captcha != req.session.captcha) { res.status(400).send({ message: '验证码错误' }); }else if(userName == "chenxuehui" && password == "123321"){ res.json({"code":100,"verson":true,"msg":"登陆成功","token":token}); }else{ res.json({"code":0,"verson":false,"msg":"密码错误"}); } } } module.exports = Login
captcha方法是產生一張含四位數字的圖片,然後將圖片儲存到session中。
將此方法在 router/index.js 中引用
router.get('/captcha', login.captcha);
也就是說我們訪問localhost:3000/captcha就會回傳一張圖片。
有了這個連接後我們就可以透過圖片的src屬性拿到該圖片,但是當點擊圖片的時候要重新刷新,所以我們需要給圖片添加一個點擊刷新事件。將下面程式碼插入login.tsx中
setHash() { this.setState({ hash : Math.random() }) }
img標籤也變成了
複製代碼
這樣只要點選img,就會隨機產生一個hash,然後就會呼叫新的圖片出來。
Json Web Token就是專門解決這個問題的,原理就不做詳解了,其實就是按照一定的方式得到一個字符串,然後在通過某種方式解開。
我們要做的第一步就是用戶每次要求資料的時候要在header裡把token帶上。
第一步:還是controller/login.js
import * as React from 'react' import * as ReactDom from 'react-dom' import {Link, browserHistory} from 'react-router'; import * as axios from 'axios'; export default class Login extends React.Component<any,any>{ constructor(props){ super(props) this.state = { userName : '', password : '', yzNoId : '', hash : Math.random() } } public async sbumit(params : any) : Promise<any>{ let res = await axios.post('http://localhost:3000/login',params); } handleUserName(e) : any { this.setState({ userName : e.target.value }) } handlePassword(e) : any { this.setState({ password : e.target.value }) } handleYzId(e) : any { this.setState({ yzNoId : e.target.value }) } setHash() { this.setState({ hash : Math.random() }) } render(){ const { userName, password, yzNoId } = this.state; return( <p> <p className="nav-wrap"> <ul className="nav"> <li><Link to="/home">首页</Link></li> <li><Link to="/imgLoad">上传</Link></li> <li><Link to="/login">登陆</Link></li> </ul> </p> <p className="content"> <p className="login-warp"> <p> <input type="text" className="username" value={userName} onChange={this.handleUserName.bind(this)} placeholder="用户名"/> </p> <p> <input type="text" className="password" value={password} onChange={this.handlePassword.bind(this)} placeholder="密码"/> </p> <p> <input type="text" className="yz" value={yzNoId} onChange={this.handleYzId.bind(this)} placeholder="验证码"/> <img src={"http://localhost:3000/captcha?aaa="+this.state.hash} className="yz-img" onClick={this.setHash.bind(this)} /> </p> <p> <input type="button" className="submit" value="登陆" onClick={this.sbumit.bind(this,{userName:userName,password:password,captcha:yzNoId})} /> </p> </p> </p> </p> ) } }
var rf = require('fs'); var jwt = require('jsonwebtoken'); var captchapng = require('captchapng'); var Tokens = require('../middleware/token') var t = new Tokens; class Login { constructor(){} captcha(req, res, next) { var str = parseInt(Math.random()*9000+1000); //随机生成数字 req.session.captcha = str; // 存入session var p = new captchapng(80, 30, str); //生成图片 p.color(0, 0, 0, 0); p.color(80, 80, 80, 255); var img = p.getBase64(); var imgbase64 = new Buffer(img, 'base64'); res.writeHead(200, { 'Content-Type': 'image/png' }); res.end(imgbase64); } loginer(req, res, next) { let captcha = req.body.captcha; let userName = req.body.userName; let password = req.body.password; if (captcha != req.session.captcha) { res.status(400).send({ message: '验证码错误' }); }else if(userName == "chenxuehui" && password == "123321"){ // 设置token var datas = {userName:"chenxuehui"} //调用../middleware/token 下方法设置 var token = t.setToken('cxh',300,datas) res.json({"code":100,"verson":true,"msg":"登陆成功","token":token}); }else{ res.json({"code":0,"verson":false,"msg":"密码错误"}); } } } module.exports = Login
import * as React from 'react' import * as ReactDom from 'react-dom' import {Link, browserHistory} from 'react-router'; import * as axios from 'axios'; export default class Login extends React.Component<any,any>{ constructor(props){ super(props) this.state = { userName : '', password : '', yzNoId : '', hash : Math.random() } } public async sbumit(params : any) : Promise<any>{ let res = await axios.post('http://localhost:3000/login',params); if(res.data.verson){ sessionStorage.setItem('token',res.data.token); browserHistory.push("/home") } } handleUserName(e) : any { this.setState({ userName : e.target.value }) } handlePassword(e) : any { this.setState({ password : e.target.value }) } handleYzId(e) : any { this.setState({ yzNoId : e.target.value }) } setHash() { this.setState({ hash : Math.random() }) } render(){ const { userName, password, yzNoId } = this.state; return( <p> <p className="nav-wrap"> <ul className="nav"> <li><Link to="/home">首页</Link></li> <li><Link to="/imgLoad">上传</Link></li> <li><Link to="/login">登陆</Link></li> </ul> </p> <p className="content"> <p className="login-warp"> <p> <input type="text" className="username" value={userName} onChange={this.handleUserName.bind(this)} placeholder="用户名"/> </p> <p> <input type="text" className="password" value={password} onChange={this.handlePassword.bind(this)} placeholder="密码"/> </p> <p> <input type="text" className="yz" value={yzNoId} onChange={this.handleYzId.bind(this)} placeholder="验证码"/> <img src={"http://localhost:3000/captcha?aaa="+this.state.hash} className="yz-img" onClick={this.setHash.bind(this)} /> </p> <p> <input type="button" className="submit" value="登陆" onClick={this.sbumit.bind(this,{userName:userName,password:password,captcha:yzNoId})} /> </p> </p> </p> </p> ) } }
在 router/index.js
var express = require('express'); var router = express.Router(); var rf = require('fs'); var Login = require('./controller/login'); var Tokens = require('./middleware/token') var t = new Tokens; var login = new Login; //主页 router.get('/', function(req, res, next) { res.render("wap/index") }); //获取图片验证码 router.get('/captcha', login.captcha); //登录验证 router.post('/login',login.loginer); //请求数据时 t.testToken 验证token router.post('/list',t.testToken,function(req, res, next){ res.json({ //在请求信息里面拿到数据 username : req.userInfo.userName, success : true, result : [ { name:'1111111' }, { name :'22222' } ] }) }) module.exports = router;
我们在另一个页面调用list接口试一下
import * as axios from 'axios'; import { transToken } from '../decorator/index' class Home extends React.Component<any,any>{ constructor(props){ super(props) this.state = { data : '' } } async getList(): Promise<any>{ let token = sessionStorage.getItem('token'); const config = { // 请求头信息 headers: {'x-access-token': token} } let res = await axios.post('http://localhost:3000/list',{},config); if(!res.data.success){ browserHistory.push('/login'); return; } this.setState({ data : res.data }) } render(){ const { data } = this.state; return( <p> <p className="nav-wrap"> <ul className="nav"> <li><Link to="/home">首页</Link></li> <li><Link to="/imgLoad">上传</Link></li> <li><Link to="/login">登陆</Link></li> </ul> </p> <p className="content"> Home <span onClick={this.getList.bind(this)}>获取数据</span> <p>{ data ? data.result.map( (val,k) => { return <li key = {k}>{val.name}</li> }) : null }</p> </p> </p> ) } } export default Home
当调用getList时,如果此时没有登录res.data.success就会为false,则跳到登录页。
全部代码
node.js
app.js
var express = require('express'); var path = require('path'); var favicon = require('serve-favicon'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var session = require("express-session"); var ejs = require('ejs'); var index = require('./routes/index'); var app = express(); // view engine setup app.set('views', path.join(__dirname, 'views')); // app.set('view engine', 'jade'); app.engine('html', ejs.__express); app.set('view engine', 'html'); app.use(session({ secret:"dabao", resave:false, saveUninitialized:true, cookie:{} })); // uncomment after placing your favicon in /public //app.use(favicon(path.join(__dirname, 'public', 'favicon.ico'))); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser({limit: 5000000})); app.use(bodyParser.urlencoded({ extended: false })); app.use(cookieParser()); app.use(express.static(path.join(__dirname, ''))); app.use('/', index); // catch 404 and forward to error handler app.use(function(req, res, next) { var err = new Error('Not Found'); err.status = 404; next(err); }); // error handler app.use(function(err, req, res, next) { // set locals, only providing error in development res.locals.message = err.message; res.locals.error = req.app.get('env') === 'development' ? err : {}; // render the error page res.status(err.status || 500); res.render('error'); }); module.exports = app;
index.js
var express = require('express'); var router = express.Router(); var rf = require('fs'); var Login = require('./controller/login'); var Tokens = require('./middleware/token') var t = new Tokens; var login = new Login; /* GET home page. */ router.get('/', function(req, res, next) { res.render("wap/index") }); router.post('/upLoadImg',function(req,res,next){ let imgData = req.body.imgData; console.log(imgData) let base64Data = imgData.replace(/^data:image\/\w+;base64,/, ""); let dataBuffer = new Buffer(base64Data, 'base64'); let timer = Number( new Date() ); console.log(timer) rf.writeFile("views/images/artCover"+timer+".png",dataBuffer, function(err) { if(err) { res.json({"code":400,"verson":false,"msg":err}); }else { res.json({"code":100,"verson":true,"url":"views/src/common/images/artCover/"+timer+".png"}); } }); }) router.get('/captcha', login.captcha); router.post('/login',login.loginer); router.post('/list',t.testToken,function(req, res, next){ // 先解析token console.log(req.userInfo) res.json({ username : req.userInfo.userName, success : true, result : [ { name:'1111111' }, { name :'22222' } ] }) }) module.exports = router;
controller/login.js
var rf = require('fs'); var jwt = require('jsonwebtoken'); var captchapng = require('captchapng'); var Tokens = require('../middleware/token') var t = new Tokens; class Login { constructor(){} captcha(req, res, next) { var str = parseInt(Math.random()*9000+1000); //随机生成数字 req.session.captcha = str; // 存入session var p = new captchapng(80, 30, str); //生成图片 p.color(0, 0, 0, 0); p.color(80, 80, 80, 255); var img = p.getBase64(); var imgbase64 = new Buffer(img, 'base64'); res.writeHead(200, { 'Content-Type': 'image/png' }); res.end(imgbase64); } loginer(req, res, next) { let captcha = req.body.captcha; let userName = req.body.userName; let password = req.body.password; if (captcha != req.session.captcha) { res.status(400).send({ message: '验证码错误' }); }else if(userName == "chenxuehui" && password == "123321"){ // 设置token var datas = {userName:"chenxuehui"} var token = t.setToken('cxh',300,datas) res.json({"code":100,"verson":true,"msg":"登陆成功","token":token}); }else{ res.json({"code":0,"verson":false,"msg":"密码错误"}); } } } module.exports = Login
middleware/token.js
var jwt = require('jsonwebtoken'); class Tokens { constructor(){} testToken(req,res,next) { var token = req.body.token || req.query.token || req.headers['x-access-token']; if(token) { jwt.verify(token, 'cxh' , function(err,decoded) { if(err) { return res.json({success:false,msg:'token错误'}) }else { req.userInfo = decoded; next() } }) }else { return res.status(403).send({success:false,msg:"没有token"}) } } setToken(name,time,data) { var jwtSecret = name; var token = jwt.sign(data, jwtSecret, { expiresIn: time }) return token; } } module.exports = Tokens
react部分
login.tsx
import * as React from 'react' import * as ReactDom from 'react-dom' import {Link, browserHistory} from 'react-router'; import * as axios from 'axios'; export default class Login extends React.Component<any,any>{ constructor(props){ super(props) this.state = { userName : '', password : '', yzNoId : '', hash : Math.random() } } public async sbumit(params : any) : Promise<any>{ let res = await axios.post('http://localhost:3000/login',params); if(res.data.verson){ sessionStorage.setItem('token',res.data.token); browserHistory.push("/home") } } handleUserName(e) : any { this.setState({ userName : e.target.value }) } handlePassword(e) : any { this.setState({ password : e.target.value }) } handleYzId(e) : any { this.setState({ yzNoId : e.target.value }) } setHash() { this.setState({ hash : Math.random() }) } render(){ const { userName, password, yzNoId } = this.state; return( <p> <p className="nav-wrap"> <ul className="nav"> <li><Link to="/home">首页</Link></li> <li><Link to="/imgLoad">上传</Link></li> <li><Link to="/login">登陆</Link></li> </ul> </p> <p className="content"> <p className="login-warp"> <p> <input type="text" className="username" value={userName} onChange={this.handleUserName.bind(this)} placeholder="用户名"/> </p> <p> <input type="text" className="password" value={password} onChange={this.handlePassword.bind(this)} placeholder="密码"/> </p> <p> <input type="text" className="yz" value={yzNoId} onChange={this.handleYzId.bind(this)} placeholder="验证码"/> <img src={"http://localhost:3000/captcha?aaa="+this.state.hash} className="yz-img" onClick={this.setHash.bind(this)} /> </p> <p> <input type="button" className="submit" value="登陆" onClick={this.sbumit.bind(this,{userName:userName,password:password,captcha:yzNoId})} /> </p> </p> </p> </p> ) } }
home.js 获取列表信息
import * as React from 'react' import * as ReactDom from 'react-dom' import {Link, browserHistory} from 'react-router'; import * as axios from 'axios'; class Home extends React.Component<any,any>{ constructor(props){ super(props) this.state = { data : '' } } async getList(): Promise<any>{ let token = sessionStorage.getItem('token'); const config = { // 请求头信息 headers: {'x-access-token': token} } let res = await axios.post('http://localhost:3000/list',{},config); if(!res.data.success){ browserHistory.push('/login'); return; } this.setState({ data : res.data }) } render(){ const { data } = this.state; return( <p> <p className="nav-wrap"> <ul className="nav"> <li><Link to="/home">首页</Link></li> <li><Link to="/imgLoad">上传</Link></li> <li><Link to="/login">登陆</Link></li> </ul> </p> <p className="content"> Home <span onClick={this.getList.bind(this)}>获取数据</span> <p>{ data ? data.result.map( (val,k) => { return <li key = {k}>{val.name}</li> }) : null }</p> </p> </p> ) } } export default Home
以上是透過使用node.js+captchapng+jsonwebtoken完成登入驗證的詳細內容。更多資訊請關注PHP中文網其他相關文章!