Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- if (req.header.authorization) {
- // do soemthing
- } else {
- var cookieValues = req.cookies["demo"]
- }
- WWW-Authenticate: Basic realm="your server"
- Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==
- var express = require('express');
- var morgan = require('morgan');
- var cookieParser = require('cookie-parser');
- var hostname = 'localhost';
- var port = 3000;
- var app = express();
- app.use(morgan('dev'));
- app.use(cookieParser('12345-67890-09876-54321')); // secret key
- function auth( req, res, next){
- if (!req.signedCookies.user){//如果user不存在
- console.log(req.headers);
- var authHeader = req.headers.authorization;//获取认证情况的集合
- if(!authHeader){
- var err = new Error("you could not be authorized");
- err.status = 401;
- next(err);
- return;
- }
- console.log('authHeader :'+authHeader);
- //cookie 里名称,密码形式为: user: password
- var auth = new Buffer(authHeader.split(' ')[1], 'base64').toString().split(':');
- var user = auth[0];
- var pass = auth[1];
- if (user == 'admin' && pass =='password') {
- res.cookie('user', 'admin', {signed: true});
- next();
- }else{
- var err = new Error("you could not be authorized");
- err.status = 401;
- next(err);
- }
- }
- else {
- if (req.signedCookies.user == 'admin') {
- next();
- }else{
- var err = new Error("you could not be authorized");
- err.status = 401;
- next(err);
- }
- }
- }
- app.use(auth);
- app.use(express.static(__dirname+'/public'));
- app.use(function(err, req, res, next){
- res.writeHead(err.status || 500,
- {'WWW-Authenticate':'Basic',
- 'Content-Type':'text/plain'
- });
- res.end(err.message);
- });
- // print
- app.listen(port, hostname, function(){
- console.log('Server running at :'+hostname+ ': '+port);
- });
Add Comment
Please, Sign In to add comment