passport.js无法使用手动表单数据发布请求角度

时间:2017-10-31 11:29:59

标签: forms angular passport.js

我已经创建了一个有角度的表单,点击提交按钮我正在点击带Content-Type标题且价​​值为application/x-www-form-urlencoded的帖子请求。

onSubmit(user:User) {
    let headers = new Headers();
    // to send data as form data as passport library want it as a form data
    headers.append('Content-Type', 'application/x-www-form-urlencoded');
    return this.http.post('/login', user, { headers: headers }).subscribe((data) => {
      console.log("Data : ", data);
    });
} 

,模型用户的类型为

// Class to bind user data
class User {
  constructor(private name: string, private password: string) {
  }
}

这是服务器端代码

 let userList: User[] = [new User(1, "Sunil"), new User(2, "Sukhi")];

        let app = express();

        // passport library
        let passport = require('passport');
        let LocalStrategy = require('passport-local').Strategy;

        // middlewares
        app.use(express.static("public"));
        app.use(bodyParser.json());
        app.use(bodyParser.urlencoded({ extended: false }));
        app.use(session({ resave: false, saveUninitialized: true, secret: "secretKey123!!" }));

        // passport middleware invoked on every request to ensure session contains passport.user object
        app.use(passport.initialize());

        // load seriliazed session user object to req.user 
        app.use(passport.session());

        // Only during the authentication to specify what user information should be stored in the session.
        passport.serializeUser(function (user, done) {
            console.log("Serializer : ", user)
            done(null, user.userId);
        });

        // Invoked on every request by passport.session
        passport.deserializeUser(function (userId, done) {
            let user = userList.filter(user => userId === user.userId);
            console.log("D-serializer : ", user);
            // only pass if user exist in the session
            if (user.length) {
                done(null, user[0]);
            }
        });
// passport strategy : Only invoked on the route which uses the passport.authenticate middleware.
        passport.use(new LocalStrategy({
            usernameField: 'name',
            passwordField: 'password'
        },
            function (username, password, done) {
                console.log("Strategy : Authenticating if user is valid  :", username)
                let user = userList.filter(user => username === user.userName);
                console.log("Valid user : ",user)
                if (!user) {
                    return done(null, false, { message: 'Incorrect username.' });
                }
                return done(null, user[0]);
            }
));

app.post('/login', passport.authenticate('local', {
     successRedirect: '/done',
     failureRedirect: '/login'
}));
app.get('/done', function (req, res) {
     console.log("Done")
     res.send(req.session)
})


app.get('/login', function (req, res) {
     console.log("login")
     res.send("login")
})

但每次返回登录

1 个答案:

答案 0 :(得分:1)

就我而言,问题在于请求正文。我直接发送用户对象,所以这不起作用。为了解决这个问题,我使用URLSearchParams创建了body对象。

let  body = new URLSearchParams();
body.append('name', this.user.name);
body.append('password', this.user.password); 

以下是onSubmit方法

onSubmit() {
    let  body = new URLSearchParams();
    body.append('name', this.user.name);
    body.append('password', this.user.password);

    let headers = new Headers({'Content-Type': 'application/x-www-form-urlencoded'});
    let options = new RequestOptions({headers});

    this.http.post("/services/login", body.toString(), options).subscribe((response)=>{
        let arrUrl = response.url.split("/");
        let url = "/" + arrUrl[arrUrl.length-1];
        this.router.navigate([url]);
    });
}

其次,从登录表单中,我没有传递password字段的值。因此本地策略的回调(使用用户名和密码)没有被调用。

如果您没有通过任何字段,则不会调用回调方法,并会重定向到failureRedirect网址。