401 и 403 ошибки отличия

A clear explanation from Daniel Irvine [original link]:

There’s a problem with 401 Unauthorized, the HTTP status code for authentication errors. And that’s just it: it’s for authentication, not authorization.
Receiving a 401 response is the server telling you, “you aren’t
authenticated–either not authenticated at all or authenticated
incorrectly–but please reauthenticate and try again.” To help you out,
it will always include a WWW-Authenticate header that describes how
to authenticate.

This is a response generally returned by your web server, not your web
application.

It’s also something very temporary; the server is asking you to try
again.

So, for authorization I use the 403 Forbidden response. It’s
permanent, it’s tied to my application logic, and it’s a more concrete
response than a 401.

Receiving a 403 response is the server telling you, “I’m sorry. I know
who you are–I believe who you say you are–but you just don’t have
permission to access this resource. Maybe if you ask the system
administrator nicely, you’ll get permission. But please don’t bother
me again until your predicament changes.”

In summary, a 401 Unauthorized response should be used for missing
or bad authentication, and a 403 Forbidden response should be used
afterwards, when the user is authenticated but isn’t authorized to
perform the requested operation on the given resource.

Another nice pictorial format of how http status codes should be used.

Nick T's user avatar

Nick T

25.5k11 gold badges80 silver badges121 bronze badges

answered Aug 4, 2011 at 6:24

JPReddy's user avatar

24

Edit: RFC2616 is obsolete, see RFC9110.

401 Unauthorized:

If the request already included Authorization credentials, then the 401 response indicates that authorization has been refused for those credentials.

403 Forbidden:

The server understood the request, but is refusing to fulfill it.

From your use case, it appears that the user is not authenticated. I would return 401.


emery's user avatar

emery

8,43310 gold badges43 silver badges51 bronze badges

answered Jul 21, 2010 at 7:28

Oded's user avatar

OdedOded

488k99 gold badges881 silver badges1007 bronze badges

11

Something the other answers are missing is that it must be understood that Authentication and Authorization in the context of RFC 2616 refers ONLY to the HTTP Authentication protocol of RFC 2617. Authentication by schemes outside of RFC2617 is not supported in HTTP status codes and are not considered when deciding whether to use 401 or 403.

Brief and Terse

Unauthorized indicates that the client is not RFC2617 authenticated and the server is initiating the authentication process. Forbidden indicates either that the client is RFC2617 authenticated and does not have authorization or that the server does not support RFC2617 for the requested resource.

Meaning if you have your own roll-your-own login process and never use HTTP Authentication, 403 is always the proper response and 401 should never be used.

Detailed and In-Depth

From RFC2616

10.4.2 401 Unauthorized

The request requires user authentication. The response MUST include a WWW-Authenticate header field (section 14.47) containing a challenge applicable to the requested resource. The client MAY repeat the request with a suitable Authorization header field (section 14.8).

and

10.4.4 403 Forbidden
The server understood the request but is refusing to fulfil it. Authorization will not help and the request SHOULD NOT be repeated.

The first thing to keep in mind is that «Authentication» and «Authorization» in the context of this document refer specifically to the HTTP Authentication protocols from RFC 2617. They do not refer to any roll-your-own authentication protocols you may have created using login pages, etc. I will use «login» to refer to authentication and authorization by methods other than RFC2617

So the real difference is not what the problem is or even if there is a solution. The difference is what the server expects the client to do next.

401 indicates that the resource can not be provided, but the server is REQUESTING that the client log in through HTTP Authentication and has sent reply headers to initiate the process. Possibly there are authorizations that will permit access to the resource, possibly there are not, but let’s give it a try and see what happens.

403 indicates that the resource can not be provided and there is, for the current user, no way to solve this through RFC2617 and no point in trying. This may be because it is known that no level of authentication is sufficient (for instance because of an IP blacklist), but it may be because the user is already authenticated and does not have authority. The RFC2617 model is one-user, one-credentials so the case where the user may have a second set of credentials that could be authorized may be ignored. It neither suggests nor implies that some sort of login page or other non-RFC2617 authentication protocol may or may not help — that is outside the RFC2616 standards and definition.


Edit: RFC2616 is obsolete, see RFC7231 and RFC7235.

Community's user avatar

answered Feb 5, 2013 at 17:14

ldrut's user avatar

ldrutldrut

3,7971 gold badge17 silver badges4 bronze badges

7

  +-----------------------
  | RESOURCE EXISTS ? (if private it is often checked AFTER auth check)
  +-----------------------
    |       |
 NO |       v YES
    v      +-----------------------
   404     | IS LOGGED-IN ? (authenticated, aka user session)
   or      +-----------------------
   401        |              |
   403     NO |              | YES
   3xx        v              v
              401            +-----------------------
       (404 no reveal)       | CAN ACCESS RESOURCE ? (permission, authorized, ...)
              or             +-----------------------
             redirect          |            |
             to login       NO |            | YES
                               |            |
                               v            v
                               403          OK 200, redirect, ...
                      (or 404: no reveal)
                      (or 404: resource does not exist if private)
                      (or 3xx: redirection)

Checks are usually done in this order:

  • 404 if resource is public and does not exist or 3xx redirection
  • OTHERWISE:
  • 401 if not logged-in or session expired
  • 403 if user does not have permission to access resource (file, json, …)
  • 404 if resource does not exist or not willing to reveal anything, or 3xx redirection

UNAUTHORIZED: Status code (401) indicating that the request requires authentication, usually this means user needs to be logged-in (session). User/agent unknown by the server. Can repeat with other credentials. NOTE: This is confusing as this should have been named ‘unauthenticated’ instead of ‘unauthorized’. This can also happen after login if session expired.
Special case: Can be used instead of 404 to avoid revealing presence or non-presence of resource (credits @gingerCodeNinja)

FORBIDDEN: Status code (403) indicating the server understood the request but refused to fulfill it. User/agent known by the server but has insufficient credentials. Repeating request will not work, unless credentials changed, which is very unlikely in a short time span.
Special case: Can be used instead of 404 to avoid revealing presence or non-presence of resource (credits @gingerCodeNinja) in the case that revealing the presence of the resource exposes sensitive data or gives an attacker useful information.

NOT FOUND: Status code (404) indicating that the requested resource is not available. User/agent known but server will not reveal anything about the resource, does as if it does not exist. Repeating will not work. This is a special use of 404 (github does it for example).

As mentioned by @ChrisH there are a few options for redirection 3xx (301, 302, 303, 307 or not redirecting at all and using a 401):

  • Difference between HTTP redirect codes
  • How long do browsers cache HTTP 301s?
  • What is correct HTTP status code when redirecting to a login page?
  • What’s the difference between a 302 and a 307 redirect?

answered Feb 23, 2015 at 11:00

Christophe Roussy's user avatar

9

According to RFC 2616 (HTTP/1.1) 403 is sent when:

The server understood the request, but is refusing to fulfill it. Authorization will not help and the request SHOULD NOT be repeated. If the request method was not HEAD and the server wishes to make public why the request has not been fulfilled, it SHOULD describe the reason for the refusal in the entity. If the server does not wish to make this information available to the client, the status code 404 (Not Found) can be used instead

In other words, if the client CAN get access to the resource by authenticating, 401 should be sent.

answered Jul 21, 2010 at 7:26

Cumbayah's user avatar

CumbayahCumbayah

4,4071 gold badge25 silver badges32 bronze badges

6

Assuming HTTP authentication (WWW-Authenticate and Authorization headers) is in use, if authenticating as another user would grant access to the requested resource, then 401 Unauthorized should be returned.

403 Forbidden is used when access to the resource is forbidden to everyone or restricted to a given network or allowed only over SSL, whatever as long as it is no related to HTTP authentication.

If HTTP authentication is not in use and the service has a cookie-based authentication scheme as is the norm nowadays, then a 403 or a 404 should be returned.

Regarding 401, this is from RFC 7235 (Hypertext Transfer Protocol (HTTP/1.1): Authentication):

3.1. 401 Unauthorized

The 401 (Unauthorized) status code indicates that the request has not been applied because it lacks valid authentication credentials for the target resource. The origin server MUST send a WWW-Authenticate header field (Section 4.4) containing at least one challenge applicable to the target resource. If the request included authentication credentials, then the 401 response indicates that authorization has been refused for those credentials. The client MAY repeat the request with a new or replaced Authorization header field (Section 4.1). If the 401 response contains the same challenge as the prior response, and the user agent has already attempted authentication at least once, then the user agent SHOULD present the enclosed representation to the user, since it usually contains relevant diagnostic information.

The semantics of 403 (and 404) have changed over time. This is from 1999 (RFC 2616):

10.4.4 403 Forbidden

The server understood the request, but is refusing to fulfill it. Authorization will not help and the request SHOULD NOT be repeated. If the request method was not HEAD and the server wishes to make public why the request has not been fulfilled, it SHOULD describe the reason for the refusal in the entity. If the server does not wish to make this information available to the client, the status code 404 (Not Found) can be used instead.

In 2014 RFC 7231 (Hypertext Transfer Protocol (HTTP/1.1): Semantics and Content) changed the meaning of 403:

6.5.3. 403 Forbidden

The 403 (Forbidden) status code indicates that the server understood the request but refuses to authorize it. A server that wishes to make public why the request has been forbidden can describe that reason in the response payload (if any).

If authentication credentials were provided in the request, the server considers them insufficient to grant access. The client SHOULD NOT automatically repeat the request with the same credentials. The client MAY repeat the request with new or different credentials. However, a request might be forbidden for reasons unrelated to the credentials.

An origin server that wishes to «hide» the current existence of a forbidden target resource MAY instead respond with a status code of 404 (Not Found).

Thus, a 403 (or a 404) might now mean about anything. Providing new credentials might help… or it might not.

I believe the reason why this has changed is RFC 2616 assumed HTTP authentication would be used when in practice today’s Web apps build custom authentication schemes using for example forms and cookies.

Community's user avatar

answered Feb 27, 2013 at 9:44

Erwan Legrand's user avatar

6

  • 401 Unauthorized: I don’t know who you are. This an authentication error.
  • 403 Forbidden: I know who you are, but you don’t have permission to access this resource. This is an authorization error.

Premraj's user avatar

Premraj

71k26 gold badges235 silver badges179 bronze badges

answered Aug 6, 2019 at 12:37

Akshay Misal's user avatar

4

This is an older question, but one option that was never really brought up was to return a 404. From a security perspective, the highest voted answer suffers from a potential information leakage vulnerability. Say, for instance, that the secure web page in question is a system admin page, or perhaps more commonly, is a record in a system that the user doesn’t have access to. Ideally you wouldn’t want a malicious user to even know that there’s a page / record there, let alone that they don’t have access. When I’m building something like this, I’ll try to record unauthenticate / unauthorized requests in an internal log, but return a 404.

OWASP has some more information about how an attacker could use this type of information as part of an attack.

answered Dec 25, 2014 at 9:09

Patrick White's user avatar

5

This question was asked some time ago, but people’s thinking moves on.

Section 6.5.3 in this draft (authored by Fielding and Reschke) gives status code 403 a slightly different meaning to the one documented in RFC 2616.

It reflects what happens in authentication & authorization schemes employed by a number of popular web-servers and frameworks.

I’ve emphasized the bit I think is most salient.

6.5.3. 403 Forbidden

The 403 (Forbidden) status code indicates that the server understood the request but refuses to authorize it. A server that wishes to make public why the request has been forbidden can describe that reason in the response payload (if any).

If authentication credentials were provided in the request, the server considers them insufficient to grant access. The client SHOULD NOT repeat the request with the same credentials. The client MAY repeat the request with new or different credentials. However, a request might be forbidden for reasons unrelated to the credentials.

An origin server that wishes to «hide» the current existence of a forbidden target resource MAY instead respond with a status code of 404 (Not Found).

Whatever convention you use, the important thing is to provide uniformity across your site / API.

Community's user avatar

answered May 22, 2014 at 10:54

Dave Watts's user avatar

Dave WattsDave Watts

8707 silver badges11 bronze badges

1

These are the meanings:

401: User not (correctly) authenticated, the resource/page require authentication

403: User’s role or permissions does not allow to access requested resource, for instance user is not an administrator and requested page is for administrators.

Note: Technically, 403 is a superset of 401, since is legal to give 403 for unauthenticated user too. Anyway is more meaningful to differentiate.

answered Nov 19, 2019 at 10:17

Luca C.'s user avatar

Luca C.Luca C.

11.4k1 gold badge86 silver badges77 bronze badges

3

!!! DEPR: The answer reflects what used to be common practice, up until 2014 !!!

TL;DR

  • 401: A refusal that has to do with authentication
  • 403: A refusal that has NOTHING to do with authentication

Practical Examples

If apache requires authentication (via .htaccess), and you hit Cancel, it will respond with a 401 Authorization Required

If nginx finds a file, but has no access rights (user/group) to read/access it, it will respond with 403 Forbidden

RFC (2616 Section 10)

401 Unauthorized (10.4.2)

Meaning 1: Need to authenticate

The request requires user authentication. …

Meaning 2: Authentication insufficient

… If the request already included Authorization credentials, then the 401 response indicates that authorization has been refused for those credentials. …

403 Forbidden (10.4.4)

Meaning: Unrelated to authentication

… Authorization will not help …

More details:

The server understood the request, but is refusing to fulfill it.

It SHOULD describe the reason for the refusal in the entity

The status code 404 (Not Found) can be used instead

(If the server wants to keep this information from client)

answered Feb 25, 2015 at 9:03

Levite's user avatar

LeviteLevite

17.2k8 gold badges50 silver badges50 bronze badges

2

they are not logged in or do not belong to the proper user group

You have stated two different cases; each case should have a different response:

  1. If they are not logged in at all you should return 401 Unauthorized
  2. If they are logged in but don’t belong to the proper user group, you should return 403 Forbidden

Note on the RFC based on comments received to this answer:

If the user is not logged in they are un-authenticated, the HTTP equivalent of which is 401 and is misleadingly called Unauthorized in the RFC. As section 10.4.2 states for 401 Unauthorized:

«The request requires user authentication

If you’re unauthenticated, 401 is the correct response. However if you’re unauthorized, in the semantically correct sense, 403 is the correct response.

answered Oct 1, 2012 at 14:34

Zaid Masud's user avatar

Zaid MasudZaid Masud

13.2k9 gold badges66 silver badges88 bronze badges

4

I have created a simple note for you which will make it clear.

enter image description here

answered Nov 11, 2021 at 12:19

Pratham's user avatar

PrathamPratham

4773 silver badges7 bronze badges

In English:

401

You are potentially allowed access but for some reason on this request you were
denied. Such as a bad password? Try again, with the correct request
you will get a success response instead.

403

You are not, ever, allowed. Your name is not on the list, you won’t
ever get in, go away, don’t send a re-try request, it will be refused,
always. Go away.

answered Apr 8, 2020 at 14:23

James's user avatar

JamesJames

4,6335 gold badges36 silver badges48 bronze badges

2

401: Who are you again?? (programmer walks into a bar with no ID or invalid ID)

403: Oh great, you again. I’ve got my eye on you. Go on, get outta here. (programmer walks into a bar they are 86’d from)

answered Aug 11, 2022 at 23:10

emery's user avatar

emeryemery

8,43310 gold badges43 silver badges51 bronze badges

0

401: You need HTTP basic auth to see this.

If the user just needs to log in using you site’s standard HTML login form, 401 would not be appropriate because it is specific to HTTP basic auth.

403: This resource exists but you are not authorized to see it, and HTTP basic auth won’t help.

I don’t recommend using 403 to deny access to things like /includes, because as far as the web is concerned, those resources don’t exist at all and should therefore 404.

In other words, 403 means «this resource requires some form of auth other than HTTP basic auth (such as using the web site’s standard HTML login form)».

https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.2

answered Sep 23, 2017 at 12:33

Val Kornea's user avatar

Val KorneaVal Kornea

4,4293 gold badges39 silver badges41 bronze badges

I think it is important to consider that, to a browser, 401 initiates an authentication dialog for the user to enter new credentials, while 403 does not. Browsers think that, if a 401 is returned, then the user should re-authenticate. So 401 stands for invalid authentication while 403 stands for a lack of permission.

Here are some cases under that logic where an error would be returned from authentication or authorization, with important phrases bolded.

  • A resource requires authentication but no credentials were specified.

401: The client should specify credentials.

  • The specified credentials are in an invalid format.

400: That’s neither 401 nor 403, as syntax errors should always return 400.

  • The specified credentials reference a user which does not exist.

401: The client should specify valid credentials.

  • The specified credentials are invalid but specify a valid user (or don’t specify a user if a specified user is not required).

401: Again, the client should specify valid credentials.

  • The specified credentials have expired.

401: This is practically the same as having invalid credentials in general, so the client should specify valid credentials.

  • The specified credentials are completely valid but do not suffice the particular resource, though it is possible that credentials with more permission could.

403: Specifying valid credentials would not grant access to the resource, as the current credentials are already valid but only do not have permission.

  • The particular resource is inaccessible regardless of credentials.

403: This is regardless of credentials, so specifying valid credentials cannot help.

  • The specified credentials are completely valid but the particular client is blocked from using them.

403: If the client is blocked, specifying new credentials will not do anything.

answered Jun 2, 2018 at 23:34

Grant Gryczan's user avatar

A 401 response code means one of the following:

  1. An access token is missing.
  2. An access token is either expired, revoked, malformed, or invalid.

A 403 response code on the other hand means that the access token is indeed valid, but that the user does not have appropriate privileges to perform the requested action.

answered Feb 17, 2022 at 11:16

Ran Turner's user avatar

Ran TurnerRan Turner

14.1k4 gold badges44 silver badges50 bronze badges

0

Given the latest RFC’s on the matter (7231 and 7235) the use-case seems quite clear (italics added):

  • 401 is for unauthenticated («lacks valid authentication»); i.e. ‘I don’t know who you are, or I don’t trust you are who you say you are.’

401 Unauthorized

The 401 (Unauthorized) status code indicates that the request has not
been applied because it lacks valid authentication credentials for
the target resource. The server generating a 401 response MUST send
a WWW-Authenticate header field (Section 4.1) containing at least one
challenge applicable to the target resource.

If the request included authentication credentials, then the 401
response indicates that authorization has been refused for those
credentials. The user agent MAY repeat the request with a new or
replaced Authorization header field (Section 4.2). If the 401
response contains the same challenge as the prior response, and the
user agent has already attempted authentication at least once, then
the user agent SHOULD present the enclosed representation to the
user, since it usually contains relevant diagnostic information.

  • 403 is for unauthorized («refuses to authorize»); i.e. ‘I know who you are, but you don’t have permission to access this resource.’

403 Forbidden

The 403 (Forbidden) status code indicates that the server understood
the request but refuses to authorize it. A server that wishes to
make public why the request has been forbidden can describe that
reason in the response payload (if any).

If authentication credentials were provided in the request, the
server considers them insufficient to grant access. The client
SHOULD NOT automatically repeat the request with the same
credentials. The client MAY repeat the request with new or different
credentials. However, a request might be forbidden for reasons
unrelated to the credentials.

An origin server that wishes to «hide» the current existence of a
forbidden target resource MAY instead respond with a status code of
404 (Not Found).

Community's user avatar

answered Jun 5, 2018 at 15:26

cjbarth's user avatar

cjbarthcjbarth

4,1696 gold badges42 silver badges62 bronze badges

3

I have a slightly different take on it from the accepted answer.

It seems more semantic and logical to return a 403 when authentication fails and a 401 when authorisation fails.

Here is my reasoning for this:

When you are requesting to be authenticated, You are authorised to make that request. You need to otherwise no one would even be able to be authenticated in the first place.

If your authentication fails you are forbidden, that makes semantic sense.

On the other hand the forbidden can also apply for Authorisation, but
Say you are authenticated and you are not authorised to access a particular endpoint. It seems more semantic to return a 401 Unauthorised.

Spring Boot’s security returns 403 for a failed authentication attempt

answered Apr 6, 2022 at 22:44

In the case of 401 vs 403, this has been answered many times. This is essentially a ‘HTTP request environment’ debate, not an ‘application’ debate.

There seems to be a question on the roll-your-own-login issue (application).

In this case, simply not being logged in is not sufficient to send a 401 or a 403, unless you use HTTP Auth vs a login page (not tied to setting HTTP Auth). It sounds like you may be looking for a «201 Created», with a roll-your-own-login screen present (instead of the requested resource) for the application-level access to a file. This says:

«I heard you, it’s here, but try this instead (you are not allowed to see it)»

answered Dec 12, 2014 at 19:01

Shawn's user avatar

3

HTTP 401 error and difference from HTTP 403 error

Error 403(Forbidden) and Error 401 (Unauthorized) are almost like identical twins, but what do you think is the exact difference between the two?

If you own or create websites, you may have come across HTTP error numbers 401 and 403. When a person tries to access a limited website or resource, this error occurs. While they may appear to be the same, there are significant variations between the two error numbers. In the following article, we’ll go over the distinctions between error 401 and error 403, as well as their meaning and causes.

RFC Standards

Error 401

The RFC Standard defining Error 401 (Unauthorized) is RFC7235 which says that the code conveys the message indicating the canceled request because of lacking authentication credentials for the target resource… You could then try to repeat the request with a new or replaced Authorization header field.

But, the RFC standard that defines Error 403 (Forbidden) is RFC 7231 and it states that the server has successfully understood the request but has refused to authorize it. The authorization credentials that were provided in the request are insufficient for the server to provide access.

Main Causes Of The Errors

So now we know, that Error 403 happens when the user has logged in but they do not have the permission required to access the requested resource. For instance, you could be logging in to access the admin route when you only have permission for the generic user route.

On the other hand, you will mostly encounter a 401 error when you have provided the wrong password or you have not logged in at all.

These, we can say, are the most common causes for Errors 401 and 403.

Some Obscure Causes

Http 401 error causes

There are a few occasions when the cause for the error might not be that straightforward.

There can be occasions when the error 403 is not entirely dependent on the logged-in user’s credentials.

For instance, there could be a server that has locked down its resources such that it only allows access from a fixed range of IP addresses. The VPN could be potentially circumvented with the latter.

On the other hand, even if you have entered the correct credentials, the 401 error could occur. But, it has to be admitted that this could only be encountered while developing authenticated back ends of your own. But a malformed authorisation header will again return a 401.

For instance, you might want to include in the request a JWT (JSON Web Token), if you have it. A JWT expects the format Authorization: Bearer eyJhbGci……yJV_adQssw5c.

You could encounter the 401 error if you forget to use the word “Bearer’ before the JWT.

Conclusion

Understanding the membership and identity operators in Python is essential for writing efficient and concise code. By using these operators, you can easily check for the presence or absence of values in a sequence, or compare the identity of two objects. Similarly, understanding the differences between error 401 and error 403 is crucial for website owners and developers to troubleshoot issues related to restricted access. By applying the knowledge gained from this article, you’ll be better equipped to handle these common scenarios and write more robust Python code.

Frequently Asked Questions

1: What is a 401 error in HTTP?

A 401 error in HTTP is an «Unauthorized» error code that occurs when a client attempts to access a resource without proper authentication or authorisation credentials.

2: What is a 403 error in HTTP?

A 403 error in HTTP is a «Forbidden» error code that occurs when a client attempts to access a resource that they do not have permission to access, even with proper authentication credentials.

3: How are 401 and 403 errors different?

401 errors occur when a client is not authenticated or authorised to access a resource. 403 errors occur when a client is authenticated but does not have permission to access a resource.

4: What can cause a 401 error?

A 401 error can be caused by various factors, such as entering incorrect login credentials, missing or expired authentication tokens, or attempting to access a protected resource without proper authorisation.

Викинг и четыре ошибки на его пути

Понимать суть и знать, как действовать — то, что необходимо, когда встречаешься лицом к лицу с ошибками на своём сайте. Особенно если речь идёт об ошибках на стороне клиента, код которых начинается с цифры 4. Объясним смысл самых частых ошибок такого рода и расскажем, что можно предпринять в каждом из случаев.

400 Bad Request (Неверный запрос)

Сервер сообщает, что обнаружена ошибка в синтаксисе запроса к нему, то есть в правилах его написания. Обычно это происходит из-за проблем на устройстве или в браузере, однако есть небольшая вероятность, что всему виной неполадки на самом сервере. Но сначала исходим из того, что сервер здесь ни при чём.

Смысл ошибки 400

Если вы открыли свой сайт и увидели ошибку 400, то в первую очередь сделайте то, что вы сделали бы в случае посещения любого другого сайта:

1. Проверьте, что адрес страницы написан верно (нет неподходящих символов, нет проблем с регистром букв и отсутствуют пробелы).

2. Посмотрите, происходит ли то же самое в других браузерах. Если нет, то обновите браузер, показывающий ошибку, и очистите куки.

3. Ошибка продолжает появляться? Проверьте устройство антивирусом, затем отключите антивирус и/или брандмауэр, если вредоносная активность не была обнаружена. В случае исчезновения ошибки настройте антивирус / брандмауэр так, чтобы он больше доверял вашему браузеру.

4. Ошибка всё-таки видна во всех браузерах? Обновите компонент .NET Framework, если вы используете компьютер с Windows, затем просканируйте саму Windows на предмет «мусора» и неполадок, обновите необновлённые драйвера и обновите сам Windows. После каждого из этих шагов проверяйте, продолжает ли появляться ошибка.

5. Если всё это не помогло, обратитесь к интернет-провайдеру — возможно, проблема на его стороне.

Теперь разбираемся с ошибкой как администраторы сайта:

1. Обратитесь к хостингу, если ошибка появляется при посещении сайта с других устройств.

2. В случае, когда ошибка возникает только на одном устройстве, посмотрите, всё ли хорошо с заголовками HTTP-запросов. Они могут считываться как слишком длинные либо ошибочные или вовсе не обнаруживаться.

3. Если при запросе загружается большой по размеру файл, попробуйте загрузить файл меньшего размера.

4. Ошибка возникла после обновления CMS либо установки расширения, модуля или плагина? По возможности верните предыдущую версию CMS и удалите недавно установленные компоненты.

5. Посмотрите лог-файлы сервера и поищите в них причину неполадок.

6. Проведите аудит кода.

При всех действиях с сайтом убедитесь, что сохранена свежая резервная копия файлов сайта и баз данных.

401 Unauthorized (Не авторизован)

Такой код состояния сервера возникает, когда пользователю не удаётся авторизоваться на сайте. Возможно, дело в неверных логине и пароле или в попытке посмотреть контент, доступный только для авторизованных пользователей.

Смысл ошибки 401

Но если это не так, то искать причину ошибки нужно на стороне сайта:

1. Обратитесь к хостинг-провайдеру для выяснения причины ошибки.

2. Удостоверьтесь в том, что уровни доступа для пользователей указаны верно.

3. Ограничьте индексацию поисковиками страниц с ошибкой, написав в файле robots.txt строку Disallow: /адрес страницы. После этого организуйте перенаправление с этих страниц на страницу с авторизацией, указав в файле .htaccess следующее:

Redirect 301 /стараястраница.html http://example.com/новаястраница.html

4. Проверьте, не установлена ли слишком маленькая длительность сессии в файле php.ini на сервере. Установите для параметров session.gc_maxlifetime и session.cookie_lifetime значения 1440 и 0 соответственно.

5. Посмотрите код сайта и скрипты на наличие ошибок.

403 Forbidden (Запрещено)

Здесь ситуация схожа с 401-ой ошибкой: не удаётся войти в систему. Но если в том случае система просто не может определить пользователя, то здесь система понимает, кто перед ней, и сознательно не предоставляет доступ.

Смысл ошибки 403

Что можно сделать?

1. Просто подождать, если ошибка возникла после переноса домена с одного аккаунта хостинга на другой.

2. Уведомление появилось после установки нового плагина? Найдите этот плагин, затем измените его параметры или удалите его.

3. Удостоверьтесь, что в имени индексного файла нет ошибок: index, точка, расширение файла строчными буквами.

4. Также проверьте, что файлы сайта загружены в предназначенную для них папку.

5. Уточните, какие права установлены на папке, где находится запрашиваемый файл или папка. Рекомендуется установить права 744 (выполнять может только владелец) или 755 (выполнять могут и владелец, и пользователи).

6. Посмотрите файл .htaccess на предмет неверно указанных редиректов и излишнего ограничений доступа к файлам.

404 Not Found (Не найдено)

Наверное, самая известная всем ошибка. Она говорит о том, что запрашиваемой страницы нет из-за отсутствия файла с ней или из-за ошибки в URL.

Смысл ошибки 404

1. Если страница по указанному адресу была удалена случайно, верните её.

2. На сайте имеются ссылки, по которым выдаётся ошибка 404? Удалите их или сделайте редирект 301 в файле .htacсess на подходящую страницу-замену.

3. На будущее создайте свою собственную страницу с 404-ой ошибкой. Оформите её в стиле других страниц сайта, также разместите на ней ссылку на главную страницу и, если потребуется, на другие важные разделы ресурса.

Остались вопросы? Посмотрите ответы на вопросы из нашего раздела FAQ:

  • Отчего возникает ошибка 403 (Forbidden)?
  • Отчего возникает ошибка 404 (Not Found)?
  • Как изменить страницы ошибок 403, 404 и 500?

Также мы раньше в целом рассказали о кодах состояния сервера, к которым относятся в том числе и коды ошибок.

To understand the difference between these two status codes let’s define what authentication and authorization mean.

In my opinion, they’re often confused with each other.

Most of modern web security systems are based on the two-step process of granting authority.

Authentication 🚪🔑

Authentication is the process of verification of the identity of a person or a device.

Common use case: entering a username and password to grant access to the website or web application.

Authorization 🕵️‍♀️

Authorization is the security mechanism that determines the permissions level the user/client has in the system related to the server resources.

In the HTTP `Authorization` is also one of the request headers. It is used for authentication purposes.

401 – Unauthorized – Authentication issue

The 401 (Unauthorized) status code indicates that the request has not been applied because it lacks valid authentication credentials for the target resource

Example:

You’d like to access the content of the resource but you’re not logged in (so not authenticated yet). The server will return you a 401 error. You need to log in to be able to access the resource.

A common use case of the 401 status code is when the user is not authenticated – which means not logged in or has been logged out etc.

403 – Forbidden – Authorization issue

The 403 (Forbidden) status code indicates that the server understood the request but refuses to authorize it.

Example:

You’d like to delete the user, but you’re authenticated as a regular user, not as an admin. The server doesn’t allow regular users to perform such requests, so as the result, the server will send you a 403 error. Re-authentication won’t make any difference.

The common use case of the 403 status code is when the user has no permission to perform the action.

Conclusion

I’m sure you got the difference now. Take a look at the responses you get from the various services to understand them better.

I hope that understanding the difference between 401 and 403 status codes will help you to design and implement better APIs in your applications.

Resources

  • RFC 7235 – Section 3.1 – 401 Unauthorized
  • RFC 7231 – Section 6.5.3 – 403 Forbidded

Response c кодом 401 или 403 означает, что клиент не может просмотреть страницу, т.к. недостаточно прав для этого.

 Переведём официальную документацию, чтобы понять, какой http-код лучше использовать (401 vs 403).

Код 401 Unauthorized

401 Unauthorized:

The request requires user authentication. The response MUST include a WWW-Authenticate header field (section 14.47) containing a challenge applicable to the requested resource. The client MAY repeat the request with a suitable Authorization header field (section 14.8). If the request already included Authorization credentials, then the 401 response indicates that authorization has been refused for those credentials. If the 401 response contains the same challenge as the prior response, and the user agent has already attempted authentication at least once, then the user SHOULD be presented the entity that was given in the response, since that entity might include relevant diagnostic information. HTTP access authentication is explained in «HTTP Authentication: Basic and Digest Access Authentication».

Для выполнения запроса пользователь должен быть авторизован. Ответ должен включать заголовок с полем «WWW-Authenticate», где через запятую должны быть перечислены параметры, необходимые для авторизации. При ответе с кодом 401 пользователь может повторить свой запрос. Клиент должен выполнить условия авторизации, после чего сделать повторный запрос.

Код 403 Forbidden.

403 Forbidden:

The server understood the request, but is refusing to fulfill it. Authorization will not help and the request SHOULD NOT be repeated. If the request method was not HEAD and the server wishes to make public why the request has not been fulfilled, it SHOULD describe the reason for the refusal in the entity. If the server does not wish to make this information available to the client, the status code 404 (Not Found) can be used instead.

Сервер понял запрос, но не захотел его выполнять. Нет разрешения на запрос и запрос не должен быть повторён. Сервер должен объяснить клиенту, почему запрос не может быть выполнен (это касается всех методов, кроме HEAD). Если сервер не хочет описывать причину не выполнения запроса клиенту, то сервер должен возвращать http-статус 404 Not Found вместо 403 Forbidden.

Подведём итог, использовать 401 или 403?

Если клиент может получить доступ к странице (например, пройдя авторизацию), то нужно возвращать http-код 401. 401 нужно возвращать при отсутствующей или просроченной авторизации.

Если мы знаем, что доступ к странице для клиента закрыт, не может быть получен, то нужно возвращать http-код 403. Код 403 также следует возвращать, если клиент авторизован, но у него недостаточно прав для просмотра данной страницы.

Т.е. 403 код говорит «Извините, я знаю кто вы (вы авторизованы). Но, к сожалению, у вас нет прав для доступа к данному ресурсу. Возможно, вам нужно обратиться к администратору ресурса за получением разрешений.» Клиенту не имеет смысл повторять запрос.

ответил 8 лет назад

avatar

Понравилась статья? Поделить с друзьями:

Не пропустите эти материалы по теме:

  • Яндекс еда ошибка привязки карты
  • 4007 ошибка туарег
  • 400671 ошибка бмв
  • 400635 ошибка бмв 730
  • 400626 ошибка бмв

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии