我已经关注了每个博客,这些博客描述了如何使用本地策略和快递上运行的护照。用户数据位于mysql上,我创建了服务器代码
let express = require('express')
let bodyParser = require('body-parser');
let path = require('path');
let app = express()
let cors = require('cors');
let passport = require('passport');
let flash = require('connect-flash');
let morgan = require('morgan');
let cookieParser = require('cookie-parser');
let session = require('express-session');
app.use(morgan('dev')); // log every request to the console
app.use(cookieParser()); // read cookies (needed for auth)
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: false }))
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-
With, Content-Type, Accept");
next();
});
app.use(cors());
app.use('/', express.static(path.join(__dirname, 'public')));
app.use(session({
secret: 'secretme',
resave: true,
saveUninitialized: true
})); // session secret
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash()); // use connect-flash for flash messages stored in
session
require('./config/passport')(passport); // pass passport for
configuration
function isAuthenticated(req, res, next) {
//if (req.user && req.user.authenticated)
// return next();
if (req.isAuthenticated())
return next();
res.status(401).send()
}
app.get('/api/about', isAuthenticated, (req, res) => {
res.json({
version: '1.1'
})
})
登录传递确定,这是函数:
app.post('/api/login', passport.authenticate('local-login', {
failureRedirect: '/bad-login',
failureFlash: true // allow flash messages
}), (req, res) => {
res.status(200).send();
})
关于客户端,我使用的是Angular v4,登录调用通过ok
login(email: string, password: string) {
var headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
let options = new RequestOptions({
headers: headers
})
let data = new URLSearchParams();
data.append('email', email);
data.append('password', password);
let body = data.toString()
return this._http.post(`http://X.X.X.X/api/login`, body, options)
.toPromise()
.then(response => response.status)
}
当我打电话给api时,我得到401.我错过了什么?
about(): Promise<About> {
return this._http.get(`http://X.X.X.X/api/about`, { withCredentials: true })
.toPromise()
.then(response => response.json() as About)
}
登录代码:
let LocalStrategy = require('passport-local').Strategy;
let bcrypt = require('bcrypt-nodejs');
let Users = require('../user');
module.exports = passport => {
// used to serialize the user for the session
passport.serializeUser(function(user, done) {
done(null, user.email);
});
// used to deserialize the user
passport.deserializeUser(function(id, done) {
let userDao = new Users();
userDao.getUser(id).then(user => {
done(undefined, user);
})
});
passport.use('local-login', new LocalStrategy({
// by default, local strategy uses username and password, we will override with email
usernameField: 'email',
passwordField: 'password',
passReqToCallback: true // allows us to pass back the entire request to the callback
},
function(req, email, password, done) { // callback with email and password from our form
let userDao = new Users();
userDao.getUser(email)
.then(users => {
if (!users.length) {
return done(null, false, req.flash('loginMessage', 'No user found.'));
}
let user = users[0];
if (!bcrypt.compareSync(password, user.password)) {
return done(null, false, req.flash('loginMessage', 'Oops! Wrong password.'));
}
return done(null, user);
}).catch(err => {
console.log(`got error in login: ${err}`)
})
}));
}