波卡的验证人节点_简易节点身份验证:Google

波卡的验证人节点

Welcome to Part 4 of our Easy Node Authentication with Passport series. We will be using the foundation of that tutorial to use Google authentication with our application. We already have a good application structure for our application packages, user model, application setup and views.

node-auth-google-index
Since we set up our application to be as clean and efficient as possible, we will only have to create our Google application and add to 4 different files:

欢迎使用我们的Passport轻松节点身份验证系列的第4部分 。 我们将利用该教程的基础,在我们的应用程序中使用Google身份验证。 我们已经为应用程序包用户模型应用程序设置和视图提供了良好的应用程序结构。 由于我们将应用程序设置为尽可能干净和高效,因此我们仅需创建Google应用程序并添加到4个不同的文件中:

Creating the Google App, Client ID, and Client Secret config/auth.js
Configuring the Passport Google Strategy config/passport.js
Generating Routes app/routes.js
Updating Views views/
创建Google App,客户端ID和客户端密钥 config/auth.js
配置Passport Google 策略 config/passport.js
生成路线 app/routes.js
更新视图 views/

Since we are already familiar with code organization (the first tutorial) and where we need to add code to authenticate with a social network (the second tutorial), we’ll jump right into configuring our Passport Google Strategy.

由于我们已经熟悉代码组织(第一个教程),并且需要在其中添加代码以通过社交网络进行身份验证(第二个教程),因此,我们将直接开始配置Passport Google Strategy。

使用Passport向Google进行身份验证 (Authenticating with Google using Passport)

创建我们的Google应用程序 (Creating Our Google Application)

The place to create Google applications can be found at their Cloud API Console. Applications can be found under Project > APIs & auth.

可以在其Cloud API控制台中找到创建Google应用程序的位置。 可以在Project > APIs & auth下找到应用程序。

Let's go ahead and create our application with the correct redirect URL: http://localhost:8080/auth/google/callback.

让我们继续使用正确的重定向URL创建我们的应用程序: http://localhost:8080/auth/google/callback

http://localhost:8080, then use http://localhost:8080 ,请使用 http://127.0.0.1:8080. http://127.0.0.1:8080

node-auth-google-credentials
Let’s add our Client ID and our client secret to our auth.js file so that our application knows the secrets it needs to authenticate with Google.

让我们将我们的客户ID和客户机密添加到我们的auth.js文件中,以便我们的应用程序知道它需要通过Google进行身份验证的机密。

// config/auth.js

// expose our config directly to our application using module.exports
module.exports = {

    'facebookAuth' : {
        'clientID'      : 'your-secret-clientID-here', // your App ID
        'clientSecret'  : 'your-client-secret-here', // your App Secret
        'callbackURL'   : 'http://localhost:8080/auth/facebook/callback'
    },

    'twitterAuth' : {
        'consumerKey'       : 'your-consumer-key-here',
        'consumerSecret'    : 'your-client-secret-here',
        'callbackURL'       : 'http://localhost:8080/auth/twitter/callback'
    },

    'googleAuth' : {
        'clientID'      : 'your-secret-clientID-here',
        'clientSecret'  : 'your-client-secret-here',
        'callbackURL'   : 'http://localhost:8080/auth/google/callback'
    }

};

自定义您的应用程序屏幕 (Customizing Your Application Screen)

Google let's you change the default login screen so that you can customize it with your brand's logo and text. This can be found on the same page where your client ID and secret are. The option is under Consent Screen.

Google让您更改默认的登录屏幕,以便可以使用品牌的徽标和文字对其进行自定义。 可以在您的客户ID和密码所在的同一页面上找到此文件。 该选项位于“ 同意屏幕”下

Here is the customization screen:

这是定制屏幕:

node-auth-google-customization
With our application ready to go, let's set up our Passport Google Strategy.

准备好我们的应用程序后,让我们设置我们的Passport Google策略。

配置Passport的Google策略config / passport.js (Configuring Passport's Google Strategy config/passport.js)

We will be using the passport-google-oauth package by Jared Hanson so that we can authenticate with OAuth2.

我们将使用Jared Hanson 的password-google-oauth软件包,以便我们可以通过OAuth2进行身份验证。

There will be comments as placeholders for the previous article's strategies.

上一篇文章的策略将以占位符的形式出现注释。

// config/passport.js

// load all the things we need
var LocalStrategy    = require('passport-local').Strategy;
var FacebookStrategy = require('passport-facebook').Strategy;
var TwitterStrategy  = require('passport-twitter').Strategy;
var GoogleStrategy = require('passport-google-oauth').OAuth2Strategy;

// load up the user model
var User       = require('../app/models/user');

// load the auth variables
var configAuth = require('./auth');

module.exports = function(passport) {

    // used to serialize the user for the session
    passport.serializeUser(function(user, done) {
        done(null, user.id);
    });

    // used to deserialize the user
    passport.deserializeUser(function(id, done) {
        User.findById(id, function(err, user) {
            done(err, user);
        });
    });

    // code for login (use('local-login', new LocalStategy))
    // code for signup (use('local-signup', new LocalStategy))
    // code for facebook (use('facebook', new FacebookStrategy))
    // code for twitter (use('twitter', new TwitterStrategy))

    // =========================================================================
    // GOOGLE ==================================================================
    // =========================================================================
    passport.use(new GoogleStrategy({

        clientID        : configAuth.googleAuth.clientID,
        clientSecret    : configAuth.googleAuth.clientSecret,
        callbackURL     : configAuth.googleAuth.callbackURL,

    },
    function(token, refreshToken, profile, done) {

        // make the code asynchronous
        // User.findOne won't fire until we have all our data back from Google
        process.nextTick(function() {

            // try to find the user based on their google id
            User.findOne({ 'google.id' : profile.id }, function(err, user) {
                if (err)
                    return done(err);

                if (user) {

                    // if a user is found, log them in
                    return done(null, user);
                } else {
                    // if the user isnt in our database, create a new user
                    var newUser          = new User();

                    // set all of the relevant information
                    newUser.google.id    = profile.id;
                    newUser.google.token = token;
                    newUser.google.name  = profile.displayName;
                    newUser.google.email = profile.emails[0].value; // pull the first email

                    // save the user
                    newUser.save(function(err) {
                        if (err)
                            throw err;
                        return done(null, newUser);
                    });
                }
            });
        });

    }));

};

Now we have the Google Strategy that will search for a user based on their google.id that corresponds to their profile.id we get back from Google. Next let's handle our routes to use our new Strategy.

现在,我们有了Google策略,它将根据与他们的profile.id相对应的google.id搜索用户,我们从Google那里获得了该策略。 接下来,让我们处理使用新策略的路线

生成我们的路线app / routes.js (Generating Our Routes app/routes.js)

We will need 2 routes.

我们将需要2条路线。

  • /auth/google: Send our user to Google to authenticate

    / auth / google :将我们的用户发送到Google进行身份验证
  • /auth/google/callback: Google sends our user back to our application with token and profile

    / auth / google / callback :Google使用令牌和个人资料将我们的用户发送回我们的应用程序
// app/routes.js

module.exports = function(app, passport) {

    // route for home page
    app.get('/', function(req, res) {
        res.render('index.ejs'); // load the index.ejs file
    });

    // route for login form
    // route for processing the login form
    // route for signup form
    // route for processing the signup form

    // route for showing the profile page
    app.get('/profile', isLoggedIn, function(req, res) {
        res.render('profile.ejs', {
            user : req.user // get the user out of session and pass to template
        });
    });

    // route for logging out
    app.get('/logout', function(req, res) {
        req.logout();
        res.redirect('/');
    });

    // facebook routes
    // twitter routes

    // =====================================
    // GOOGLE ROUTES =======================
    // =====================================
    // send to google to do the authentication
    // profile gets us their basic information including their name
    // email gets their emails
    app.get('/auth/google', passport.authenticate('google', { scope : ['profile', 'email'] }));

    // the callback after google has authenticated the user
    app.get('/auth/google/callback',
            passport.authenticate('google', {
                    successRedirect : '/profile',
                    failureRedirect : '/'
            }));

};

// route middleware to make sure a user is logged in
function isLoggedIn(req, res, next) {

    // if user is authenticated in the session, carry on
    if (req.isAuthenticated())
        return next();

    // if they aren't redirect them to the home page
    res.redirect('/');
}

Our routes are very simple. Just authenticate and handle the callback.

我们的路线很简单。 只需验证并处理回调即可。

显示我们的用户index.ejs,profile.ejs (Showing Our User index.ejs, profile.ejs)

Once a user is authenticated, they will be redirected to their profile page. Last thing we need to do is show their user information.

用户通过身份验证后,将被重定向到其个人资料页面 。 我们需要做的最后一件事是显示其用户信息。

Google登录按钮views / index.ejs (Google Login Button views/index.ejs)

Let's create the Google login button.

让我们创建Google登录按钮。

<!-- views/index.ejs -->

<!doctype html>
<html>
<head>
    <title>Node Authentication</title>
    <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.2/css/bootstrap.min.css"> <!-- load bootstrap css -->
    <link rel="stylesheet" href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.min.css"> <!-- load fontawesome -->
    <style>
        body        { padding-top:80px; }
    </style>
</head>
<body>
<div class="container">

    <div class="jumbotron text-center">
        <h1><span class="fa fa-lock"></span> Node Authentication</h1>

        <p>Login or Register with:</p>

        <a href="/auth/google" class="btn btn-danger"><span class="fa fa-google-plus"></span> Google</a>

    </div>

</div>
</body>
</html>

node-auth-google-index
When a user clicks on our authentication link, they will be directed to Google. A user will have to login and then grant permissions.

当用户单击我们的身份验证链接时,他们将被定向到Google。 用户将必须登录 ,然后授予权限

node-auth-google-signin
node-auth-google-accept

个人资料页面浏览量/profile.ejs (Profile Page views/profile.ejs)

Once a user registers, they will be added to our database. Let's show their user information.

用户注册后,他们将被添加到我们的数据库中。 让我们显示他们的用户信息。

<!-- views/profile.ejs -->
<!doctype html>
<html>
<head>
    <title>Node Authentication</title>
    <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.2/css/bootstrap.min.css">
    <link rel="stylesheet" href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.min.css">
    <style>
        body        { padding-top:80px; word-wrap:break-word; }
    </style>
</head>
<body>
<div class="container">

    <div class="page-header text-center">
        <h1><span class="fa fa-anchor"></span> Profile Page</h1>
        <a href="/logout" class="btn btn-default btn-sm">Logout</a>
    </div>

    <div class="row">

        <!-- GOOGLE INFORMATION -->
        <div class="col-sm-6">
            <div class="well">
                <h3 class="text-danger"><span class="fa fa-google-plus"></span> Google</h3>

                    <p>
                        <strong>id</strong>: <%= user.google.id %><br>
                        <strong>token</strong>: <%= user.google.token %><br>
                        <strong>email</strong>: <%= user.google.email %><br>
                        <strong>name</strong>: <%= user.google.name %>
                    </p>

            </div>
        </div>

    </div>

</div>
</body>
</html>

Now we have their profile page!

现在我们有了他们的个人资料页面!

node-auth-google-profile

全做完了! (All Done!)

Just like the other articles in this series, it is fairly straightforward to authenticate a user using a social network and OAuth 2.0.

就像本系列中的其他文章一样,使用社交网络和OAuth 2.0对用户进行身份验证非常简单。

In our next and final article, we will be dealing with the giant task of combining all of these methods of authentication into one user.

在下一篇和最后一篇文章中,我们将处理将所有这些身份验证方法组合到一个用户中的艰巨任务。

We'll be diving into many ideas like linking social accounts under one user, unlinking an account, and handling all the other complex scenarios involved with this process.

我们将深入探讨许多想法,例如在一个用户下关联社交帐户取消关联帐户以及处理此过程涉及的所有其他复杂情况。

翻译自: https://scotch.io/tutorials/easy-node-authentication-google

波卡的验证人节点

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值