2

I am using Stormpath for Expressjs (without Passport at the moment) to handle my user registration. I am very concerned about what is the proper way to logout an user.

Before, I always did it through the GET method, however Stormpath explicitly requires a POST call to the /logout page.

I display a user menu only when the user is logged in through Stormpath, this is the super-simple middleware that I have in my router.js in Express:

router.use(stormpath.getUser, function (req, res, next) {
    if (req.user) {
        req.session.useremail = req.user.email;
    }
    next();
});

Now, of course in this menu there is the Logout entry. I want my user to click this link to Logout, however I know that when anchor links like <a href="/logout">Logout</a> are used, a GET request is sent, not a POST.

I have been looking for countless number of ways to redirect a GET request to a POST, but I feel that this is absolutely the wrong way. Also I feel it would make no sense to use a form inside a menu like:

<ul>
    <li>User Profile</li>
    <li>User Settings</li>
    <form action="/logout" method="/post">
         <input type="submit">
    </form>
</ul>

So the question is: what is the best way to simply logout an user via POST?

wiredmark
  • 1,098
  • 6
  • 26
  • 44
  • Hi there! I work at [Stormpath](https://stormpath.com) and I implemented the change to POST. This SO discussion is a good summary of why we chose to go with POST: http://stackoverflow.com/questions/3521290/logout-get-or-post – robertjd Apr 06 '16 at 18:19

1 Answers1

3

I don't think there is anything particularity bad about having the form in the menu but if you really want to have a get request you would probably need to do something like so:

var request = require('request')

app.get('/logout', function(req, res) {

  // Send logout POST request to stormpath REST api
  request.post({
      url: 'https://stormpath/logout/url',
      form: {
        key: 'value'
      }
    },
    function(err, httpResponse, body) {
      // Check if there was an error logging the user-out
      if (err) return res.send('Error logging out')
        // If no error, user is logged out so redirect them or something
      res.redirect('/')
    }) 
})

So your express app accepts the GET request and then makes the POST request to Stormpath on the user's behalf to log the user out.

If you do move on to using the Stormpath passport stratergy I think you can simply call req.logout().

Ash
  • 6,483
  • 7
  • 29
  • 37
  • In the end I implemented the
    solution but I will mark this as a valid answer as it actually answers my question.
    – wiredmark Apr 05 '16 at 17:06