91

In a webpage, it uses YUI connection manager/datasource to send AJAX requests to the server, if the session (which contains the info on whether the user has been authenticated) has already timed out, those ajax responses that can only be viewed by authenticated users should return an http status code, telling the client that the session has already timed out, then the client either simply redirects him to the login page or asks him if he wants to extend the session.

My question is that, in this situation, what http status code is the most appropriate to tell the client the session has timed out?

List of HTTP status codes from wiki

bobo
  • 8,439
  • 11
  • 57
  • 81
  • Are you wanting to warn the user that the session is about to expire so the user can do something to renew it? If that's the case, it would have to be handled by a timer in JavaScript that goes off before the session timeout on the server. By the time the status code is sent by the server, it would already have expired. A timer would also be needed if you were redirecting them to another page automatically if they left the page idle. – Jason Oct 31 '09 at 05:45
  • 8
    Why, 418 of course! Short and stout ... – Tim Post Oct 31 '09 at 05:47
  • Vaadin uses 410 Gone, but since it's cachable by the browser, I would not recommend it – sreg Aug 14 '15 at 15:48

11 Answers11

80

Best I can suggest is a HTTP 401 status code with a WWW-Authenticate header.

The problem with 403 requests is the the RFC 2616 states "Authorization will not help and the request SHOULD NOT be repeated." (i.e. doesn't matter if you are authenticated or not, you are not going to get access to that resource, ever).

The problem with 401 requests is it states they "MUST include a WWW-Authenticate header field". As someone has noted it doesn't appear to be in violation of the spec to use a custom value in a WWW-Authenticate header.

I can't see any reason in RFC 2617 why an HTTP 401 status combined with a custom WWW-Authenticate header like this wouldn't be okay:

WWW-Authenticate: MyAuthScheme realm="http://example.com"

The oAuth spec actually seems to do just this, as they recommend this (though they have to my mind an odd interpretation of the RFC):

WWW-Authenticate: OAuth realm="http://server.example.com/"

This doesn't appear to be specifically SANCTIONED by the RFC, but I can't actually see that it's forbidden by it (it doesn't seem to conflict with any MUST or MUST NOT, SHOULD or SHOULD NOT condition).

I wish there was a more specific HTTP status code for timeouts and for things like CSRF tokens being invalid so this was clearer.

Community
  • 1
  • 1
Iain Collins
  • 6,774
  • 3
  • 43
  • 43
40

I would recommend an HTTP 401.

Whereas a 403 basically says, "You're not allowed, go away and don't come back", a 401 says, "We don't know if you're allowed or not because you didn't bring your ID. Go get it and try again."

Compare Wikipedia's definitions:

HTTP 403 - The request was a legal request, but the server is refusing to respond to it.

HTTP 401 - Similar to 403 Forbidden, but specifically for use when authentication is possible but has failed or not yet been provided.

Jonathon Hill
  • 3,445
  • 1
  • 33
  • 31
  • 3
    401 is meant to be for *HTTP authentication*. RFC 2616 says `response MUST include a WWW-Authenticate header field`. So it's *wrong* to send that code without a *WWW-Authenticate header field*. – toxalot Mar 18 '14 at 20:01
19

What about 419 - it is not standard, but the description on Wikipedia seems to fit:

419 Authentication Timeout

Not a part of the HTTP standard, 419 Authentication Timeout denotes that previously valid authentication has expired. It is used as an alternative to 401 Unauthorized in order to differentiate from otherwise authenticated clients being denied access to specific server resources.

tokarev
  • 2,575
  • 1
  • 21
  • 26
John Reichert
  • 415
  • 3
  • 12
14

As you post a link, in that link i found this HTTP status code 440. you can use 440 HTTP status code for session expired.

440 Login Time-out : Microsoft's Internet Information Services (IIS)

 The client's session has expired and must log in again.

401 Unauthorized we can use when, user login credential is wrong. or auth token passed in header is invalid.

403 Forbidden we can use this when user does not has specific permission for requested resource.

So in my opinion you can use one of the above statusCode.

Vinay Pandya
  • 3,020
  • 2
  • 26
  • 42
12

I believe the appropriate code is going to be 403/Forbidden. There aren't any that are directly related to sessions.

Jason
  • 2,545
  • 16
  • 20
  • 1
    Absolutely this is the correct answer. Since the session has timed out, the request is forbidden, so this is the best choice. – marcc Oct 31 '09 at 05:37
  • 3
    403 tells the client (basically) "Don't do that again unless you modify your request" , but if the session was established, no modification would be needed. Furthermore, you can't do anything to the (current) request to re-establish the session in most cases. – Tim Post Oct 31 '09 at 11:37
  • 1
    Exactly! 401 would be better, I think, but it requires HTTP authentication. I think this calls for a new status along the lines of 401+303 (so, obviously, 704) that means "Not Authorized, See Other to gain authorization". In addition to it being more semantically correct, it could also be the HTTP solution for trampoline redirection, basically "go here, then when you get back we'll try this again", so that the login page could be agnostic in regards to the destination. – Anthony Apr 01 '12 at 12:08
  • 6
    I can't agree with this one, RFC 2616 explicitly states that requests that result in a 403 response "SHOULD NOT be repeated" by the client and that "authorization will not help". – Iain Collins Mar 14 '13 at 15:56
  • 5
    `authorization will not help` - I take that to mean *HTTP authentication* won't help. Which is correct. Sending an Authorization header will not change anything. Neither 401 nor 403 is ideal, but I think 403 is *better* than 401. 401 is *wrong* for session timeout because RFC 2616 explicitly states `client MAY repeat the request with a suitable Authorization header field`. But, in this case, the client **SHOULD NOT** repeat the request (at least not without an interim step). Unfortunately, we can't communicate the latter part with a status code. – toxalot Jun 07 '13 at 16:07
11

As per the Wikipedia link of Http Status Codes provided above by Bobo:

440 Login Timeout (Microsoft)

    A Microsoft extension. Indicates that your session has expired.
Faisal Mq
  • 5,036
  • 4
  • 35
  • 39
  • Do notice apache may convert that return status to 500, as mine did - https://stackoverflow.com/questions/17735514/php-apache-silently-converting-http-429-and-others-to-500 – commonpike Jan 28 '18 at 10:43
  • I like this solution for ASP.NET environments. – TroySteven Apr 06 '20 at 14:21
  • 1
    This code is specific to Microsoft IIS servers. It is not an official HTTP response code which is backed by an RFC. – 8bitjunkie Feb 03 '21 at 00:48
9

Truth is, there is no standard HTTP status code for a session timeout. Sessions are implemented in the application layer, not the HTTP transport layer.

There is a custom status code that Microsoft have been using for session timeout: 599, or simply make up your own status code in the 5xx range.

From the Status Codes Wiki:

599 Network connect timeout error (Unknown) This status code is not specified in any RFCs, but is used by Microsoft Corp. HTTP proxies to signal a network connect timeout behind the proxy to a client in front of the proxy.

I use the custom status code 599 for a session timeout and then check for it in the AJAX response.

Dermot Doherty
  • 500
  • 5
  • 6
  • 3
    A network connection timeout is very different from a session timeout. If you are going to use a code from a Microsoft extension, why not use `440 Login Timeout (Microsoft)` as per [Faisal Mq's answer](http://stackoverflow.com/a/22484262/1862009) – toxalot Mar 18 '14 at 19:54
  • That Wikipedia page about 599 was wrong and had no citations. It apparently used to say that Microsoft proxies raise 599 on network timeout, but I couldn't find any evidence of that either. – Gareth Davidson Aug 03 '17 at 10:41
4

Technically, the accepted answer is of course correct: If you already know for sure that you are going to be failing the request, and you are asking which failure code to return, then HTTP 401 "Unauthorized (Unauthenticated)" is the appropriate one, so as to prompt re-authentication.

But first of all, ask yourself: should you fail the request?

Consider that the user may simply be visiting a public page of your website, in which case you are going to be slapping them across the face with an "Unauthorized!" message, and requiring them to re-authenticate, in order to see a page that they would normally be able to see without authentication. That's not cool.

My advice is to ignore the fact that the session token is unknown, and simply proceed to generate a new session token and create a new session for it. The initial state of the session will of course be "not-yet-authenticated", so if the user is trying to access a non-public page, then the page will see to it that they receive an HTTP 401 "Unauthorized (Unauthenticated)" and must authenticate. But if the user lands on a public page, they won't notice anything different.

Mike Nakis
  • 56,297
  • 11
  • 110
  • 142
-1

I would use a 302 redirection response, with a "Location" header directing to a resource path like "/auth-required"

The client could route the resource path to a modal with a login/password form, avoiding to tranfer the user to another page.

pinei
  • 2,233
  • 1
  • 24
  • 25
-2

For non-Ajax requests, I use a 302 redirect.

For Ajax requests, I use 200 for known errors. That way I can take advantage of the data object. I find the data object easier to work with than parsing jqXHR for info. And then I don't need to worry about what HTTP status code to try to re-purpose for my situation.

jQuery Example:

$.ajax({
    //send data to server
})
.done(function(data, textStatus, jqXHR) {
    if (data.success) {
        //then process return data
    }
    else {
        //get error type or message from data object
        //could use custom error codes
    }
})
.fail(function(jqXHR, textStatus, errorThrown) {
    //handle unknown errors
});
toxalot
  • 11,260
  • 6
  • 35
  • 58
  • 6
    Not wanting to parse the response is not a good reason to deviate from the HTTP spec, especially when you can just JSON.parse(responseText). – David Nelson Apr 17 '14 at 15:02
  • I don't think using a 200 response code deviates from the HTTP spec in this case because the request was *technically* successful at the transport layer. To me, session timeouts are similar to form errors where I return a user-friendly error message. The disagreements expressed in the answers to this question clearly indicate that the HTTP spec does *not* provide an industry-accepted response code for session timeouts. How can one deviate from a spec that doesn't exist? – toxalot Oct 16 '20 at 22:50
-4

Code 408. "Request timeout", seems perfect -- RFC 2616 explains it means

The client did not produce a request within the time that the server was prepared to wait.

i.e., exactly a "time-out", just as you require!

Alex Martelli
  • 854,459
  • 170
  • 1,222
  • 1,395
  • 4
    Ah, but take a look at the rest of the definition: "The client may repeat the request without modifications at any later time." "Without modifications" would imply that a new session could be created simply by reloading/refreshing the request. In most cases, when authentication is being used, the user would have to login again first. – AJ. Oct 31 '09 at 05:33
  • @AJ, of course the repeated request may run into an authentication challenge (HTTP code 401) -- don't see anything in HTTP specs forbidding **that**, can you point to anything? – Alex Martelli Oct 31 '09 at 05:43
  • 5
    408 tells the client that they should just try re-submitting the request as is, which obviously can't work if the session has timed out. – Tim Post Oct 31 '09 at 11:37
  • 4
    408 is a 'request' timeout not session timeout. Meaning, the socket was established but was taking too long. This site does a good job explaining it: http://www.checkupdown.com/status/E408.html – Brad Cupit Apr 29 '11 at 15:01