Correct http status code for resource which requires authorization

后端 未结 8 486
太阳男子
太阳男子 2021-01-29 23:51

There seems to be a lot of confusion about the correct http status code to return if the user tries to access a page which requires the user to login.

So basically what

8条回答
  •  花落未央
    2021-01-30 00:38

    If the user has not provided any credentials and your API requires them, return a 401 - Unauthorized. That will challenge the client to do so. There's usually little debate about this particular scenario.

    If the user has provided valid credentials but they are insufficient to access the requested resource (perhaps the credentials were for a freemium account but the requested resource is only for your paid users), you have a couple of options given the looseness of some of the HTTP code definitions:

    1. Return 403 - Forbidden. This is more descriptive and is typically understood as, "the supplied credentials were valid but still were not enough to grant access"
    2. Return 401 - Unauthorized. If you're paranoid about security, you might not want to give the extra information back to the client as was returned in (1) above
    3. Return either 401 or 403 but with helpful information in the response body describing the reasons why access is being denied. Again, that information might be more than you would want to provide in case it helps attackers somewhat.

    Personally, I've always used #1 for the scenario where valid credentials have been passed but the account they're associated with doesn't have access to the requested resource.

提交回复
热议问题