Meteor - initiate client login automatically

2019-03-02 10:38发布

i have a meteor app where i'm using nginx with an internal SSO service to authenticate. I'm able to do this successfully and retrieve user details in the nginx set http headers on the server Meteor.onConnection method.

At this point, i'm not sure what the best approach is to get access to the user details on the client side. I feel like i should use the built in Meteor Accounts but i'm not sure how to initiate the login process from the client since the user will not actually be logging in through the Meteor client but through a redirect that happens through nginx. I feel like i need a way to automatically initiate the login process on the meteor side to set up the meteor.users collection appropriately, but i can't figure out a way to do that.

标签: meteor nginx
1条回答
Root(大扎)
2楼-- · 2019-03-02 11:24

Checkout the answers here. You can pass the userId (or in whatever you want to pass the user) through nginx to the server then onto the client to login. You can generate and insert the token in a Webapp.connectHandler.

import { Inject } from 'meteor/meteorhacks:inject-initial';
// server/main.js
Meteor.startup(() => {
    WebApp.connectHandlers.use("/login",function(req, res, next) {
      Fiber(function() {
        var userId = req.headers["user-id"]
        if (userId){
           var stampedLoginToken = Accounts._generateStampedLoginToken();
           //check if user exists
           Accounts._insertLoginToken(userId, stampedLoginToken);
           Inject.obj('auth', {
             'loginToken':stampedLoginToken
           },res);             
           return next() 
        }
      }).run()
    })       
}

Now you can login on the client side with the help of the meteor-inject-initial package

import { Inject } from 'meteor/meteorhacks:inject-initial';
// iron router
Router.route('/login', {
    action: function() {
        if (!Meteor.userId()){
            Meteor.loginWithToken(Inject.getObj('auth').loginToken.token, 
                function(err,res){
                    if (err){
                        console.log(err)
                    }
                }
            )
        } else {
            Router.go('/home')
        }
    },
});
查看更多
登录 后发表回答