Guest User

Untitled

a guest
Jun 20th, 2018
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.83 KB | None | 0 0
  1. if (req.header.authorization) {
  2. // do soemthing
  3. } else {
  4. var cookieValues = req.cookies["demo"]
  5. }
  6.  
  7. WWW-Authenticate: Basic realm="your server"
  8.  
  9. Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==
  10.  
  11. var express = require('express');
  12. var morgan = require('morgan');
  13. var cookieParser = require('cookie-parser');
  14.  
  15.  
  16. var hostname = 'localhost';
  17. var port = 3000;
  18.  
  19. var app = express();
  20.  
  21. app.use(morgan('dev'));
  22.  
  23.  
  24. app.use(cookieParser('12345-67890-09876-54321')); // secret key
  25.  
  26.  
  27. function auth( req, res, next){
  28. if (!req.signedCookies.user){//如果user不存在
  29. console.log(req.headers);
  30. var authHeader = req.headers.authorization;//获取认证情况的集合
  31. if(!authHeader){
  32. var err = new Error("you could not be authorized");
  33. err.status = 401;
  34. next(err);
  35. return;
  36. }
  37. console.log('authHeader :'+authHeader);
  38. //cookie 里名称,密码形式为: user: password
  39. var auth = new Buffer(authHeader.split(' ')[1], 'base64').toString().split(':');
  40. var user = auth[0];
  41. var pass = auth[1];
  42. if (user == 'admin' && pass =='password') {
  43. res.cookie('user', 'admin', {signed: true});
  44.  
  45. next();
  46. }else{
  47. var err = new Error("you could not be authorized");
  48. err.status = 401;
  49. next(err);
  50.  
  51. }
  52. }
  53. else {
  54. if (req.signedCookies.user == 'admin') {
  55. next();
  56. }else{
  57. var err = new Error("you could not be authorized");
  58. err.status = 401;
  59. next(err);
  60. }
  61. }
  62.  
  63.  
  64. }
  65.  
  66.  
  67. app.use(auth);
  68.  
  69. app.use(express.static(__dirname+'/public'));
  70. app.use(function(err, req, res, next){
  71. res.writeHead(err.status || 500,
  72. {'WWW-Authenticate':'Basic',
  73. 'Content-Type':'text/plain'
  74. });
  75. res.end(err.message);
  76. });
  77.  
  78. // print
  79. app.listen(port, hostname, function(){
  80. console.log('Server running at :'+hostname+ ': '+port);
  81. });
Add Comment
Please, Sign In to add comment