How to compare and validate the requested URL with a custom URL string?












0














I have a route that goes to the index page. I have a secret token that allows access to this page. I want to compare the requested URL with a custom string. The current URL in use is http://localhost:3000/?token=secret but if I enter http://localhost:3000/as?token=secret it doesn't render the 404 error page that I created, instead says Cannot GET /as. I wondering how to validate this and render out the error page correctly



app.get('/', (req, res) => {
console.log(req.url); // /?token=secret
if (req.url !== `/?token=${websocket_token}`) {
res.render('error', {
title: '404 Not Found',
errorMessage: '404 Not Found'
});
return;
}
});









share|improve this question
























  • That makes no sense at all. Are you changing the request somewhere in middleware or something? You are going to /helloworld you say. Not /as.
    – Charlie Fish
    Dec 28 '18 at 0:34










  • @CharlieFish no sorry I have changed it
    – User123
    Dec 28 '18 at 0:37










  • Oh got it. One second while I write up an answer.
    – Charlie Fish
    Dec 28 '18 at 0:38










  • I assume you are interested in query string which you can get by req.query prop in express. Make middleware, before your route-s, that handle and check query string and just if pass that middlware user will be able to see your routes.
    – Deathmras
    Dec 28 '18 at 0:39












  • @Deathmras req.url will work too. See nodejs.org/api/http.html#http_message_url. It includes the query string as well.
    – Charlie Fish
    Dec 28 '18 at 0:44
















0














I have a route that goes to the index page. I have a secret token that allows access to this page. I want to compare the requested URL with a custom string. The current URL in use is http://localhost:3000/?token=secret but if I enter http://localhost:3000/as?token=secret it doesn't render the 404 error page that I created, instead says Cannot GET /as. I wondering how to validate this and render out the error page correctly



app.get('/', (req, res) => {
console.log(req.url); // /?token=secret
if (req.url !== `/?token=${websocket_token}`) {
res.render('error', {
title: '404 Not Found',
errorMessage: '404 Not Found'
});
return;
}
});









share|improve this question
























  • That makes no sense at all. Are you changing the request somewhere in middleware or something? You are going to /helloworld you say. Not /as.
    – Charlie Fish
    Dec 28 '18 at 0:34










  • @CharlieFish no sorry I have changed it
    – User123
    Dec 28 '18 at 0:37










  • Oh got it. One second while I write up an answer.
    – Charlie Fish
    Dec 28 '18 at 0:38










  • I assume you are interested in query string which you can get by req.query prop in express. Make middleware, before your route-s, that handle and check query string and just if pass that middlware user will be able to see your routes.
    – Deathmras
    Dec 28 '18 at 0:39












  • @Deathmras req.url will work too. See nodejs.org/api/http.html#http_message_url. It includes the query string as well.
    – Charlie Fish
    Dec 28 '18 at 0:44














0












0








0







I have a route that goes to the index page. I have a secret token that allows access to this page. I want to compare the requested URL with a custom string. The current URL in use is http://localhost:3000/?token=secret but if I enter http://localhost:3000/as?token=secret it doesn't render the 404 error page that I created, instead says Cannot GET /as. I wondering how to validate this and render out the error page correctly



app.get('/', (req, res) => {
console.log(req.url); // /?token=secret
if (req.url !== `/?token=${websocket_token}`) {
res.render('error', {
title: '404 Not Found',
errorMessage: '404 Not Found'
});
return;
}
});









share|improve this question















I have a route that goes to the index page. I have a secret token that allows access to this page. I want to compare the requested URL with a custom string. The current URL in use is http://localhost:3000/?token=secret but if I enter http://localhost:3000/as?token=secret it doesn't render the 404 error page that I created, instead says Cannot GET /as. I wondering how to validate this and render out the error page correctly



app.get('/', (req, res) => {
console.log(req.url); // /?token=secret
if (req.url !== `/?token=${websocket_token}`) {
res.render('error', {
title: '404 Not Found',
errorMessage: '404 Not Found'
});
return;
}
});






javascript express ecmascript-6






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Dec 28 '18 at 0:36

























asked Dec 28 '18 at 0:32









User123

567




567












  • That makes no sense at all. Are you changing the request somewhere in middleware or something? You are going to /helloworld you say. Not /as.
    – Charlie Fish
    Dec 28 '18 at 0:34










  • @CharlieFish no sorry I have changed it
    – User123
    Dec 28 '18 at 0:37










  • Oh got it. One second while I write up an answer.
    – Charlie Fish
    Dec 28 '18 at 0:38










  • I assume you are interested in query string which you can get by req.query prop in express. Make middleware, before your route-s, that handle and check query string and just if pass that middlware user will be able to see your routes.
    – Deathmras
    Dec 28 '18 at 0:39












  • @Deathmras req.url will work too. See nodejs.org/api/http.html#http_message_url. It includes the query string as well.
    – Charlie Fish
    Dec 28 '18 at 0:44


















  • That makes no sense at all. Are you changing the request somewhere in middleware or something? You are going to /helloworld you say. Not /as.
    – Charlie Fish
    Dec 28 '18 at 0:34










  • @CharlieFish no sorry I have changed it
    – User123
    Dec 28 '18 at 0:37










  • Oh got it. One second while I write up an answer.
    – Charlie Fish
    Dec 28 '18 at 0:38










  • I assume you are interested in query string which you can get by req.query prop in express. Make middleware, before your route-s, that handle and check query string and just if pass that middlware user will be able to see your routes.
    – Deathmras
    Dec 28 '18 at 0:39












  • @Deathmras req.url will work too. See nodejs.org/api/http.html#http_message_url. It includes the query string as well.
    – Charlie Fish
    Dec 28 '18 at 0:44
















That makes no sense at all. Are you changing the request somewhere in middleware or something? You are going to /helloworld you say. Not /as.
– Charlie Fish
Dec 28 '18 at 0:34




That makes no sense at all. Are you changing the request somewhere in middleware or something? You are going to /helloworld you say. Not /as.
– Charlie Fish
Dec 28 '18 at 0:34












@CharlieFish no sorry I have changed it
– User123
Dec 28 '18 at 0:37




@CharlieFish no sorry I have changed it
– User123
Dec 28 '18 at 0:37












Oh got it. One second while I write up an answer.
– Charlie Fish
Dec 28 '18 at 0:38




Oh got it. One second while I write up an answer.
– Charlie Fish
Dec 28 '18 at 0:38












I assume you are interested in query string which you can get by req.query prop in express. Make middleware, before your route-s, that handle and check query string and just if pass that middlware user will be able to see your routes.
– Deathmras
Dec 28 '18 at 0:39






I assume you are interested in query string which you can get by req.query prop in express. Make middleware, before your route-s, that handle and check query string and just if pass that middlware user will be able to see your routes.
– Deathmras
Dec 28 '18 at 0:39














@Deathmras req.url will work too. See nodejs.org/api/http.html#http_message_url. It includes the query string as well.
– Charlie Fish
Dec 28 '18 at 0:44




@Deathmras req.url will work too. See nodejs.org/api/http.html#http_message_url. It includes the query string as well.
– Charlie Fish
Dec 28 '18 at 0:44












3 Answers
3






active

oldest

votes


















0














In Express each app.get or other related method handles it's own route. So when you do app.get('/' you are only matching routes that are / not /as.



You could change it to * to match all routes. Maybe like the following?



app.get('*', (req, res) => {
console.log(req.url); // /?token=secret
if (req.url !== `/?token=${websocket_token}`) {
res.render('error', {
title: '404 Not Found',
errorMessage: '404 Not Found'
});
return;
}
});


Or of course you could have a dedicated section for your 404 messages.



app.get('/', (req, res, next) => {
console.log(req.url); // /?token=secret
if (req.url !== `/?token=${websocket_token}`) {
return next();
}
// Valid request
});

app.get('*', (req, res) => {
res.render('error', {
title: '404 Not Found',
errorMessage: '404 Not Found'
});
});


At the end of the day there are so many ways you can handle Express routing. It's very powerful and flexible.



I'd suggest you look here under the How do I handle 404 responses? section for another idea as well.





Also, remember, having secrets in a URL like that, probably isn't the most secure thing. So there are a lot of reasons I wouldn't suggest this for security reasons. But just answering your question, the above should work.






share|improve this answer





























    0














    The idiomatic way to handle 404s in Express is to register your final route handler with the use method rather than using one of the HTTP-specific methods.



    app.use((req, res) => {
    res.render('error', {
    title: '404 not found',
    errorMessage: '404 not found'
    })
    })


    I emphasize the word final because use registers a catch-all handler, so this will override any route that it precedes in your code. If all your other routes are registered before this, then this will catch any request that has not matched any other route – regardless of the HTTP method that was used. So this will apply to any GET, POST, PUT, DELETE request.



    An even more idiomatic way in Express to handle 404s (and all HTTP error responses) is to use the next argument that comes with all route handlers. This will re-route the request to the next handler that specifically takes an error as it's first argument:



    app.use((req, res, next) => {
    const error = new Error('404 not found')
    error.statusCode = 404
    next(error)
    })

    app.use((error, req, res, next) => {
    res.status(error.status || 500)
    res.render('error', {
    title: error.message,
    errorMessage: error.message
    })
    })


    This is great because you now have a generic error handler, which you can access from inside any other route. So this will handle not only 404s, but also 401s, 403s, 503s, anything you want that doesn't render successfully for the user. And you can access this route simply by calling next with an error as the first argument from inside any other route handler.






    share|improve this answer





























      0














      I suggest you to use passport-auth-token for validating the token & display success or error pages.



      Configure Strategy



      The token authentication strategy authenticates users using a token. The strategy requires a verify callback, which accepts these credentials and calls done providing a user.



      passport.use('authtoken', new AuthTokenStrategy(
      function(token, done) {
      AccessToken.findOne({
      id: token
      }, function(error, accessToken) {
      if (error) {
      return done(error);
      }

      if (accessToken) {
      if (!token.isValid(accessToken)) {
      return done(null, false);
      }

      User.findOne({
      id: accessToken.userId
      }, function(error, user) {
      if (error) {
      return done(error);
      }

      if (!user) {
      return done(null, false);
      }

      return done(null, user);
      });
      } else {
      return done(null);
      }
      });
      }
      ));


      Authenticate Requests



      Use passport.authenticate(), specifying the 'authtoken' strategy, to authenticate requests.



      For example, as route middleware in an Express application:



      app.post('/login',
      passport.authenticate(
      'authtoken',
      {
      session: false,
      optional: false
      }
      ),
      function(req, res) {
      res.redirect('/');
      }
      );





      share|improve this answer





















        Your Answer






        StackExchange.ifUsing("editor", function () {
        StackExchange.using("externalEditor", function () {
        StackExchange.using("snippets", function () {
        StackExchange.snippets.init();
        });
        });
        }, "code-snippets");

        StackExchange.ready(function() {
        var channelOptions = {
        tags: "".split(" "),
        id: "1"
        };
        initTagRenderer("".split(" "), "".split(" "), channelOptions);

        StackExchange.using("externalEditor", function() {
        // Have to fire editor after snippets, if snippets enabled
        if (StackExchange.settings.snippets.snippetsEnabled) {
        StackExchange.using("snippets", function() {
        createEditor();
        });
        }
        else {
        createEditor();
        }
        });

        function createEditor() {
        StackExchange.prepareEditor({
        heartbeatType: 'answer',
        autoActivateHeartbeat: false,
        convertImagesToLinks: true,
        noModals: true,
        showLowRepImageUploadWarning: true,
        reputationToPostImages: 10,
        bindNavPrevention: true,
        postfix: "",
        imageUploader: {
        brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
        contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
        allowUrls: true
        },
        onDemand: true,
        discardSelector: ".discard-answer"
        ,immediatelyShowMarkdownHelp:true
        });


        }
        });














        draft saved

        draft discarded


















        StackExchange.ready(
        function () {
        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53952382%2fhow-to-compare-and-validate-the-requested-url-with-a-custom-url-string%23new-answer', 'question_page');
        }
        );

        Post as a guest















        Required, but never shown

























        3 Answers
        3






        active

        oldest

        votes








        3 Answers
        3






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        0














        In Express each app.get or other related method handles it's own route. So when you do app.get('/' you are only matching routes that are / not /as.



        You could change it to * to match all routes. Maybe like the following?



        app.get('*', (req, res) => {
        console.log(req.url); // /?token=secret
        if (req.url !== `/?token=${websocket_token}`) {
        res.render('error', {
        title: '404 Not Found',
        errorMessage: '404 Not Found'
        });
        return;
        }
        });


        Or of course you could have a dedicated section for your 404 messages.



        app.get('/', (req, res, next) => {
        console.log(req.url); // /?token=secret
        if (req.url !== `/?token=${websocket_token}`) {
        return next();
        }
        // Valid request
        });

        app.get('*', (req, res) => {
        res.render('error', {
        title: '404 Not Found',
        errorMessage: '404 Not Found'
        });
        });


        At the end of the day there are so many ways you can handle Express routing. It's very powerful and flexible.



        I'd suggest you look here under the How do I handle 404 responses? section for another idea as well.





        Also, remember, having secrets in a URL like that, probably isn't the most secure thing. So there are a lot of reasons I wouldn't suggest this for security reasons. But just answering your question, the above should work.






        share|improve this answer


























          0














          In Express each app.get or other related method handles it's own route. So when you do app.get('/' you are only matching routes that are / not /as.



          You could change it to * to match all routes. Maybe like the following?



          app.get('*', (req, res) => {
          console.log(req.url); // /?token=secret
          if (req.url !== `/?token=${websocket_token}`) {
          res.render('error', {
          title: '404 Not Found',
          errorMessage: '404 Not Found'
          });
          return;
          }
          });


          Or of course you could have a dedicated section for your 404 messages.



          app.get('/', (req, res, next) => {
          console.log(req.url); // /?token=secret
          if (req.url !== `/?token=${websocket_token}`) {
          return next();
          }
          // Valid request
          });

          app.get('*', (req, res) => {
          res.render('error', {
          title: '404 Not Found',
          errorMessage: '404 Not Found'
          });
          });


          At the end of the day there are so many ways you can handle Express routing. It's very powerful and flexible.



          I'd suggest you look here under the How do I handle 404 responses? section for another idea as well.





          Also, remember, having secrets in a URL like that, probably isn't the most secure thing. So there are a lot of reasons I wouldn't suggest this for security reasons. But just answering your question, the above should work.






          share|improve this answer
























            0












            0








            0






            In Express each app.get or other related method handles it's own route. So when you do app.get('/' you are only matching routes that are / not /as.



            You could change it to * to match all routes. Maybe like the following?



            app.get('*', (req, res) => {
            console.log(req.url); // /?token=secret
            if (req.url !== `/?token=${websocket_token}`) {
            res.render('error', {
            title: '404 Not Found',
            errorMessage: '404 Not Found'
            });
            return;
            }
            });


            Or of course you could have a dedicated section for your 404 messages.



            app.get('/', (req, res, next) => {
            console.log(req.url); // /?token=secret
            if (req.url !== `/?token=${websocket_token}`) {
            return next();
            }
            // Valid request
            });

            app.get('*', (req, res) => {
            res.render('error', {
            title: '404 Not Found',
            errorMessage: '404 Not Found'
            });
            });


            At the end of the day there are so many ways you can handle Express routing. It's very powerful and flexible.



            I'd suggest you look here under the How do I handle 404 responses? section for another idea as well.





            Also, remember, having secrets in a URL like that, probably isn't the most secure thing. So there are a lot of reasons I wouldn't suggest this for security reasons. But just answering your question, the above should work.






            share|improve this answer












            In Express each app.get or other related method handles it's own route. So when you do app.get('/' you are only matching routes that are / not /as.



            You could change it to * to match all routes. Maybe like the following?



            app.get('*', (req, res) => {
            console.log(req.url); // /?token=secret
            if (req.url !== `/?token=${websocket_token}`) {
            res.render('error', {
            title: '404 Not Found',
            errorMessage: '404 Not Found'
            });
            return;
            }
            });


            Or of course you could have a dedicated section for your 404 messages.



            app.get('/', (req, res, next) => {
            console.log(req.url); // /?token=secret
            if (req.url !== `/?token=${websocket_token}`) {
            return next();
            }
            // Valid request
            });

            app.get('*', (req, res) => {
            res.render('error', {
            title: '404 Not Found',
            errorMessage: '404 Not Found'
            });
            });


            At the end of the day there are so many ways you can handle Express routing. It's very powerful and flexible.



            I'd suggest you look here under the How do I handle 404 responses? section for another idea as well.





            Also, remember, having secrets in a URL like that, probably isn't the most secure thing. So there are a lot of reasons I wouldn't suggest this for security reasons. But just answering your question, the above should work.







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Dec 28 '18 at 0:42









            Charlie Fish

            5,43942971




            5,43942971

























                0














                The idiomatic way to handle 404s in Express is to register your final route handler with the use method rather than using one of the HTTP-specific methods.



                app.use((req, res) => {
                res.render('error', {
                title: '404 not found',
                errorMessage: '404 not found'
                })
                })


                I emphasize the word final because use registers a catch-all handler, so this will override any route that it precedes in your code. If all your other routes are registered before this, then this will catch any request that has not matched any other route – regardless of the HTTP method that was used. So this will apply to any GET, POST, PUT, DELETE request.



                An even more idiomatic way in Express to handle 404s (and all HTTP error responses) is to use the next argument that comes with all route handlers. This will re-route the request to the next handler that specifically takes an error as it's first argument:



                app.use((req, res, next) => {
                const error = new Error('404 not found')
                error.statusCode = 404
                next(error)
                })

                app.use((error, req, res, next) => {
                res.status(error.status || 500)
                res.render('error', {
                title: error.message,
                errorMessage: error.message
                })
                })


                This is great because you now have a generic error handler, which you can access from inside any other route. So this will handle not only 404s, but also 401s, 403s, 503s, anything you want that doesn't render successfully for the user. And you can access this route simply by calling next with an error as the first argument from inside any other route handler.






                share|improve this answer


























                  0














                  The idiomatic way to handle 404s in Express is to register your final route handler with the use method rather than using one of the HTTP-specific methods.



                  app.use((req, res) => {
                  res.render('error', {
                  title: '404 not found',
                  errorMessage: '404 not found'
                  })
                  })


                  I emphasize the word final because use registers a catch-all handler, so this will override any route that it precedes in your code. If all your other routes are registered before this, then this will catch any request that has not matched any other route – regardless of the HTTP method that was used. So this will apply to any GET, POST, PUT, DELETE request.



                  An even more idiomatic way in Express to handle 404s (and all HTTP error responses) is to use the next argument that comes with all route handlers. This will re-route the request to the next handler that specifically takes an error as it's first argument:



                  app.use((req, res, next) => {
                  const error = new Error('404 not found')
                  error.statusCode = 404
                  next(error)
                  })

                  app.use((error, req, res, next) => {
                  res.status(error.status || 500)
                  res.render('error', {
                  title: error.message,
                  errorMessage: error.message
                  })
                  })


                  This is great because you now have a generic error handler, which you can access from inside any other route. So this will handle not only 404s, but also 401s, 403s, 503s, anything you want that doesn't render successfully for the user. And you can access this route simply by calling next with an error as the first argument from inside any other route handler.






                  share|improve this answer
























                    0












                    0








                    0






                    The idiomatic way to handle 404s in Express is to register your final route handler with the use method rather than using one of the HTTP-specific methods.



                    app.use((req, res) => {
                    res.render('error', {
                    title: '404 not found',
                    errorMessage: '404 not found'
                    })
                    })


                    I emphasize the word final because use registers a catch-all handler, so this will override any route that it precedes in your code. If all your other routes are registered before this, then this will catch any request that has not matched any other route – regardless of the HTTP method that was used. So this will apply to any GET, POST, PUT, DELETE request.



                    An even more idiomatic way in Express to handle 404s (and all HTTP error responses) is to use the next argument that comes with all route handlers. This will re-route the request to the next handler that specifically takes an error as it's first argument:



                    app.use((req, res, next) => {
                    const error = new Error('404 not found')
                    error.statusCode = 404
                    next(error)
                    })

                    app.use((error, req, res, next) => {
                    res.status(error.status || 500)
                    res.render('error', {
                    title: error.message,
                    errorMessage: error.message
                    })
                    })


                    This is great because you now have a generic error handler, which you can access from inside any other route. So this will handle not only 404s, but also 401s, 403s, 503s, anything you want that doesn't render successfully for the user. And you can access this route simply by calling next with an error as the first argument from inside any other route handler.






                    share|improve this answer












                    The idiomatic way to handle 404s in Express is to register your final route handler with the use method rather than using one of the HTTP-specific methods.



                    app.use((req, res) => {
                    res.render('error', {
                    title: '404 not found',
                    errorMessage: '404 not found'
                    })
                    })


                    I emphasize the word final because use registers a catch-all handler, so this will override any route that it precedes in your code. If all your other routes are registered before this, then this will catch any request that has not matched any other route – regardless of the HTTP method that was used. So this will apply to any GET, POST, PUT, DELETE request.



                    An even more idiomatic way in Express to handle 404s (and all HTTP error responses) is to use the next argument that comes with all route handlers. This will re-route the request to the next handler that specifically takes an error as it's first argument:



                    app.use((req, res, next) => {
                    const error = new Error('404 not found')
                    error.statusCode = 404
                    next(error)
                    })

                    app.use((error, req, res, next) => {
                    res.status(error.status || 500)
                    res.render('error', {
                    title: error.message,
                    errorMessage: error.message
                    })
                    })


                    This is great because you now have a generic error handler, which you can access from inside any other route. So this will handle not only 404s, but also 401s, 403s, 503s, anything you want that doesn't render successfully for the user. And you can access this route simply by calling next with an error as the first argument from inside any other route handler.







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Dec 28 '18 at 9:19









                    djfdev

                    2,40311226




                    2,40311226























                        0














                        I suggest you to use passport-auth-token for validating the token & display success or error pages.



                        Configure Strategy



                        The token authentication strategy authenticates users using a token. The strategy requires a verify callback, which accepts these credentials and calls done providing a user.



                        passport.use('authtoken', new AuthTokenStrategy(
                        function(token, done) {
                        AccessToken.findOne({
                        id: token
                        }, function(error, accessToken) {
                        if (error) {
                        return done(error);
                        }

                        if (accessToken) {
                        if (!token.isValid(accessToken)) {
                        return done(null, false);
                        }

                        User.findOne({
                        id: accessToken.userId
                        }, function(error, user) {
                        if (error) {
                        return done(error);
                        }

                        if (!user) {
                        return done(null, false);
                        }

                        return done(null, user);
                        });
                        } else {
                        return done(null);
                        }
                        });
                        }
                        ));


                        Authenticate Requests



                        Use passport.authenticate(), specifying the 'authtoken' strategy, to authenticate requests.



                        For example, as route middleware in an Express application:



                        app.post('/login',
                        passport.authenticate(
                        'authtoken',
                        {
                        session: false,
                        optional: false
                        }
                        ),
                        function(req, res) {
                        res.redirect('/');
                        }
                        );





                        share|improve this answer


























                          0














                          I suggest you to use passport-auth-token for validating the token & display success or error pages.



                          Configure Strategy



                          The token authentication strategy authenticates users using a token. The strategy requires a verify callback, which accepts these credentials and calls done providing a user.



                          passport.use('authtoken', new AuthTokenStrategy(
                          function(token, done) {
                          AccessToken.findOne({
                          id: token
                          }, function(error, accessToken) {
                          if (error) {
                          return done(error);
                          }

                          if (accessToken) {
                          if (!token.isValid(accessToken)) {
                          return done(null, false);
                          }

                          User.findOne({
                          id: accessToken.userId
                          }, function(error, user) {
                          if (error) {
                          return done(error);
                          }

                          if (!user) {
                          return done(null, false);
                          }

                          return done(null, user);
                          });
                          } else {
                          return done(null);
                          }
                          });
                          }
                          ));


                          Authenticate Requests



                          Use passport.authenticate(), specifying the 'authtoken' strategy, to authenticate requests.



                          For example, as route middleware in an Express application:



                          app.post('/login',
                          passport.authenticate(
                          'authtoken',
                          {
                          session: false,
                          optional: false
                          }
                          ),
                          function(req, res) {
                          res.redirect('/');
                          }
                          );





                          share|improve this answer
























                            0












                            0








                            0






                            I suggest you to use passport-auth-token for validating the token & display success or error pages.



                            Configure Strategy



                            The token authentication strategy authenticates users using a token. The strategy requires a verify callback, which accepts these credentials and calls done providing a user.



                            passport.use('authtoken', new AuthTokenStrategy(
                            function(token, done) {
                            AccessToken.findOne({
                            id: token
                            }, function(error, accessToken) {
                            if (error) {
                            return done(error);
                            }

                            if (accessToken) {
                            if (!token.isValid(accessToken)) {
                            return done(null, false);
                            }

                            User.findOne({
                            id: accessToken.userId
                            }, function(error, user) {
                            if (error) {
                            return done(error);
                            }

                            if (!user) {
                            return done(null, false);
                            }

                            return done(null, user);
                            });
                            } else {
                            return done(null);
                            }
                            });
                            }
                            ));


                            Authenticate Requests



                            Use passport.authenticate(), specifying the 'authtoken' strategy, to authenticate requests.



                            For example, as route middleware in an Express application:



                            app.post('/login',
                            passport.authenticate(
                            'authtoken',
                            {
                            session: false,
                            optional: false
                            }
                            ),
                            function(req, res) {
                            res.redirect('/');
                            }
                            );





                            share|improve this answer












                            I suggest you to use passport-auth-token for validating the token & display success or error pages.



                            Configure Strategy



                            The token authentication strategy authenticates users using a token. The strategy requires a verify callback, which accepts these credentials and calls done providing a user.



                            passport.use('authtoken', new AuthTokenStrategy(
                            function(token, done) {
                            AccessToken.findOne({
                            id: token
                            }, function(error, accessToken) {
                            if (error) {
                            return done(error);
                            }

                            if (accessToken) {
                            if (!token.isValid(accessToken)) {
                            return done(null, false);
                            }

                            User.findOne({
                            id: accessToken.userId
                            }, function(error, user) {
                            if (error) {
                            return done(error);
                            }

                            if (!user) {
                            return done(null, false);
                            }

                            return done(null, user);
                            });
                            } else {
                            return done(null);
                            }
                            });
                            }
                            ));


                            Authenticate Requests



                            Use passport.authenticate(), specifying the 'authtoken' strategy, to authenticate requests.



                            For example, as route middleware in an Express application:



                            app.post('/login',
                            passport.authenticate(
                            'authtoken',
                            {
                            session: false,
                            optional: false
                            }
                            ),
                            function(req, res) {
                            res.redirect('/');
                            }
                            );






                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Dec 28 '18 at 9:35









                            kRiZ

                            9817




                            9817






























                                draft saved

                                draft discarded




















































                                Thanks for contributing an answer to Stack Overflow!


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid



                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.


                                To learn more, see our tips on writing great answers.





                                Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                                Please pay close attention to the following guidance:


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid



                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.


                                To learn more, see our tips on writing great answers.




                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function () {
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53952382%2fhow-to-compare-and-validate-the-requested-url-with-a-custom-url-string%23new-answer', 'question_page');
                                }
                                );

                                Post as a guest















                                Required, but never shown





















































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown

































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown







                                Popular posts from this blog

                                Monofisismo

                                Angular Downloading a file using contenturl with Basic Authentication

                                Olmecas