令牌过期-JSON REST API-错误代码

我有一个 JSON REST API。有一个握手,将给你一个令牌是有效的15分钟。你在15分钟内打的所有电话应该都能正常工作。15分钟后,我返回了一个错误对象(包括代码,消息,成功 = 错误) ,但我也想知道我应该返回什么 HTTP 错误代码?使用 HTTP 错误代码是否会给某些客户端带来麻烦?(HTML5,iPhone,Android).在这种情况下,什么是最佳实践?

110906 次浏览

You should return a 401 Unauthorized Status Code. You might additionally provide hypermedia to establish the token again

Think about what happens in a web app. You go to say a banking site. If not auth'd it will send you to the log in page. Then you log in and you are good to go for a time. Then it expires and the cycle repeats.

Just a thought.

FWIW Facebook uses 400 with a custom JSON response. I personally would prefer 401 with custom JSON response.

Here is FB's response body:

{
"error": {
"message": "Error validating access token: Session has expired on Jul 17, 2014 9:00am. The current time is Jul 17, 2014 9:07am.",
"type": "OAuthException",
"code": 190,
"error_subcode": 463
}
}

according to the spec rfc6750 - "The OAuth 2.0 Authorization Framework: Bearer Token Usage", https://www.rfc-editor.org/rfc/rfc6750, p.8, section 3.1, resource server should return 401:

invalid_token The access token provided is expired, revoked, malformed, or invalid for other reasons. The resource SHOULD respond with the HTTP 401 (Unauthorized) status code. The client MAY request a new access token and retry the protected resource request.