Hikvision error 401 shows when you try to view your cameras remotely on the iVMS-4200. In many cases, you can live view the cameras on the phone, or the web browser, however they don’t show up on iVMS-4200.
The issue is mostly related to the UDP/TCP protocol and the forwarded ports on the router. The full error message is: Failed to get stream. Start reconnection. Error code HCNetSDK.dll[401]. (No permission). Follow the steps below to fix the issue.
How to fix Hikvision error code 41 HCNetSDK.dll[401]
- Make sure you have open three ports on the router: http, (default 80), server (default 8000) and rtsp (default 554). Sometimes if you don’t open up the rtsp port, the cameras will fail to show images on iVMS-4200.
- On the router, port forward all the Hikvision ports (mentioned above) on UDP and TCP protocol. Double check to ensure all the ports are open.
- Make sure stream encryption is turned off or box unchecked. To do so, go to the settings under Network, then Platform Access and then uncheck the box above the verification code.
- It has been reported that changing the local configuration to UDP fixes the issue. Access your Hikvision NVR/DVR or IP camera, and go to Configuration > Local. Set the protocol to UDP. Click Save. Try again if you can see the cameras.
- When you view the cameras on the iVMS-4200 software, log in with an admin account (which in the iVMS-4200 is called a Super User account). If you log in with a regular user account, you may get the error code 41.
- Make sure the Hikvision NVR/DVR and IP cameras are updated to the latest firmware. Also, use the latest version of the iVMS-4200.
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
25.2k11 gold badges79 silver badges120 bronze badges
answered Aug 4, 2011 at 6:24
23
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
8,03510 gold badges42 silver badges49 bronze badges
answered Jul 21, 2010 at 7:28
OdedOded
485k98 gold badges877 silver badges1003 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.
answered Feb 5, 2013 at 17:14
ldrutldrut
3,7771 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
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
CumbayahCumbayah
4,3771 gold badge24 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.
answered Feb 27, 2013 at 9:44
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
72.1k25 gold badges236 silver badges175 bronze badges
answered Aug 6, 2019 at 12:37
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
4
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.
answered May 22, 2014 at 10:54
Dave WattsDave Watts
8407 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.Luca C.
11.1k1 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
LeviteLevite
16.9k8 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:
- If they are not logged in at all you should return 401 Unauthorized
- 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 MasudZaid Masud
13.1k9 gold badges66 silver badges88 bronze badges
4
I have created a simple note for you which will make it clear.
answered Nov 11, 2021 at 12:19
PrathamPratham
4673 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
JamesJames
4,6155 gold badges36 silver badges48 bronze badges
2
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
Vlad KorneaVlad Kornea
4,2493 gold badges38 silver badges40 bronze badges
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
emeryemery
8,03510 gold badges42 silver badges49 bronze badges
0
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
401
response means one of the following:
- An access token is missing.
- An access token is either expired, revoked, malformed, or invalid.
403
response 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 TurnerRan Turner
12.7k4 gold badges38 silver badges48 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).
answered Jun 5, 2018 at 15:26
cjbarthcjbarth
4,0526 gold badges41 silver badges60 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
theMyththeMyth
2544 silver badges14 bronze badges
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
3
Страница с ошибкой при обращении к WordPress-сайту всегда вызывает неудобства, вне зависимости от того, ваш это сайт или чужой. Как и в случае со многими другими кодами ответов HTTP, ошибка 401 не содержит детальных данных для диагностики и решения проблемы.
Ошибка 401 может появиться в любом браузере. В большинстве случаев ее легко решить.
В этой статье мы расскажем, что означает 401 ошибка, почему она происходит, и какие методы ее устранения существуют.
Итак, приступим!
Содержание
- Код ошибки 401 – что это?
- Что вызывает ошибку 401
- Как исправить ошибку 401 (5 методов)
Код ошибки 401 – что это?
Коды состояния HTTP 400 возникают в случае проблем с выполнением запросов. В частности, ошибка 401 появляется, когда браузер отказывает вам в доступе к странице, которую вы хотите посетить.
В результате вместо загрузки страниц браузер выведет сообщение об ошибке. Ошибки 401 могут возникать в любом браузере, потому отображаемое сообщение может варьироваться.
К примеру, в Chrome и Edge вы, скорее всего, увидите иконку бумаги с простым сообщением о том, что запрашиваемая страница не отвечает. Вы увидите фразу «HTTP Error 401». Вам будет предложено связаться с владельцем сайта, если ошибка не пропадет:
В иных случаях и в других браузерах вы можете получить менее дружелюбное предупреждение. К примеру, может выводиться пустая страница с сообщением «401 Authorization Required»:
Другие вариации текста:
- HTTP 401 Error – Unauthorized
- 401 Unauthorized
- Access Denied
Эти ошибки часто появляются на сайтах, где требуется вводить данные для входа. В большинстве случаев это означает, что что-то не так с учетными данными. Возможно, браузер перестал считать их действительными.
Эта ошибка похожа на HTTP 403 Forbidden Error, когда доступ к сайту для пользователя запрещен. Однако, в отличие от ошибки 403, сообщение об ошибке 401 указывает, что процесс аутентификации завершился неудачно.
Код ошибки передается через заголовок WWW-Authenticate, который отвечает за определение метода аутентификации, используемого для предоставления доступа к веб-странице или ресурсу.
Что вызывает ошибку 401
Если вы столкнулись с кодом ошибки в кодах 400, вы должны знать, что проблема произошла на стороне клиента (либо на стороне браузера). Случается, что виновником проблемы является браузер, но так бывает не всегда. Об этом мы еще расскажем позже.
Ошибки 401 возникают на ресурсах с ограниченным доступом – к примеру, на страницах, защищенных паролем. Потому можно предположить, что причина проблемы связана с данными аутентификации.
Устаревшие Cookie и кэш браузера
Одной из наиболее распространенных причин возникновения ошибки 401 является то, что кэш и файлы cookie вашего браузера устарели, что не позволяет выполнить авторизацию. Если ваш браузер использует недействительные данные для авторизации (либо вообще их не использует их), сервер отклонит запрос.
Несовместимые плагины
Также бывают ситуации, когда ошибка вызвана несовместимостью плагинов или какими-либо сбоями в них. К примеру, плагин безопасности может ошибочно принять вашу попытку входа за вредоносную активность, а потому будет возвращена ошибка 401 для защиты страницы.
Неверный URL или устаревшая ссылка
Бывает, что источником проблемы является незначительная оплошность. К примеру, был неверно введен URL, ссылка была устаревшей и т.д.
Как исправить ошибку 401 (5 методов)
Теперь, когда мы разобрались с причинами ошибки 401, пришло время обсудить, как ее устранить.
Давайте рассмотрим 5 методов, которые вы можете использовать.
- Проверьте ваш URL.
Начнем с самого простого потенциального решения: убедитесь, что вы использовали верный URL. Это может выглядеть банально, но 401 ошибки нередко появляются, если URL-адрес был введен неправильно.
Еще один вариант: ссылка, которую вы использовали для перехода на запрашиваемую страницу, указывает на неправильный URL. К примеру, ссылка устарела, ведет на страницу, которой больше нет (и редиректов не задано).
Стоит тщательно перепроверить URL-адрес, который вы использовали. Если вы набирали адрес самостоятельно, убедитесь, что все написано безошибочно. Если вы переходили по ссылке, убедитесь в том, что она ведет на страницу, к которой вы хотите получить доступ (либо попробуйте перейти на эту страницу непосредственно через сайт).
- Почистите кэш браузера.
Кэш браузера предназначен для улучшения процесса взаимодействия с сайтами в сети за счет сокращения времени загрузки страниц. К сожалению, иногда это может вести к нежелательным последствиям.
Как мы уже говорили выше, одной из распространенных причин появления ошибки 401 являются устаревшие или неправильные данные кэша или cookies. Потому, если URL введен верно, следующий шаг – чистка кэша браузера.
В итоге вы удалите любую недействительную информацию, которая хранится локально в вашем браузере и может приводить к прерываниям процесса аутентификации. Аналогично, файлы cookie вашего браузера могут содержать аутентификационные данные, которые нужно обновить.
Если вы пользуетесь Chrome, вам нужно щелкнуть по иконке с меню в правом верхнем углу браузера и выбрать пункт Settings. В разделе «Privacy and security» нажмите «Clear browsing data:»
Далее вводим URL требуемого сайта и очищаем для него данные.
В других браузерах процесс очистки кэша и cookie может отличаться. К примеру, в Firefox нужно щелкать по иконке с библиотекой и выбирать History > Clear Recent History:
Информацию по остальным браузерам вы можете найти в поисковиках.
- Очистка DNS.
Еще один метод, который вы можете попробовать для устранения ошибки 401 – это очистка DNS. Эта причина встречается относительно редко, но стоит попробовать и такой подход, особенно если первые два ничего не дали.
Чтобы очистить DNS, перейдите в Windows к меню «Пуск» и там уже введите в строку поиска cmd. Нажмите Enter. Откроется командная строка. Далее вставьте команду ipconfig/flushdns, после чего снова нажмите Enter.
Если вы пользуетесь Mac, вы можете открыть командную строку следующим образом: Finder > Applications > Utilities > Terminal.
Введите команду sudo killall -HUP mDNSResponder и нажмите Enter. Затем вы можете обновить страницу, чтобы посмотреть, пропала ли ошибка 401 или нет.
- Деактивируйте ваши плагины
Проблема может возникать и по вине плагинов.
Некоторые плагины, особенно связанные с безопасностью, могут выдавать ошибку 401 при подозрении на вредоносную активность. Также у них могут быть проблемы с совместимостью. Потому лучше всего деактивировать все плагины и посмотреть, будет ли страница работать.
Вы можете деактивировать все плагины разом, перейдя в раздел Plugins > Installed Plugins в консоли WordPress. Выберите все плагины и в меню Bulk Actions задайте Deactivate, после чего щелкните по кнопке Apply:
После этого попробуйте перезагрузить страницу с ошибкой. Если ошибка пропала, вы можете вручную по одному активировать плагины заново, чтобы выявить виновника всех бед.
Далее вы уже можете либо удалить плагин, либо написать его разработчикам, чтобы они предоставили рабочее решение.
- Проверьте заголовок WWW-Authenticate
Если проблема все еще остается, то в таком случае она может быть связана с ошибками на сервере. А значит, исправить ее будет чуть сложнее.
Как мы уже писали ранее, ответ 401 передается через заголовок WWW-Authenticate, который отображается как “WWW-Authenticate: <type> realm=<realm>”. Он включает в себя строки данных, указывающие на то, какой тип аутентификации требуется для предоставления доступа.
Вам нужно посмотреть, был ли отправлен ответ в WWW-Authenticate, а точнее какая схема аутентификации была использована. По крайней мере, это позволит вам приблизиться на один шаг к решению.
Перейдите на страницу с ошибкой 401 и откройте консоль разработчика в Chrome. Вы можете щелкнуть правой кнопкой мыши на странице и выбрать Inspect (Ctrl+Shift+J).
Далее перейдите на вкладку Network и перезагрузите страницу. Это позволит сгенерировать список ресурсов. Выберите заголовок Status, чтобы отсортировать таблицу, и найдите код 401:
Выберите данную запись, после чего перейдите на вкладку Headers. В Response Headers найдите заголовок WWW-Authenticate:
Информация, представленная в заголовке ответа, в частности, в схеме аутентификации, даст вам больше сведений о том, что произошло, и укажет на решение. Это позволит вам понять, какой тип аутентификации требуется серверу.
К примеру, в приведенном выше примере мы видим, что схема аутентификации задана как «Basic». Это означает, что запрос аутентификации требует только ID и password. Для получения более подробной информации и инструкций мы рекомендуем обратиться к HTTP Authentication Scheme Registry.
Источник: kinsta.com
Assume your Web API is protected and a client attempts to access it without the appropriate credentials. How do you deal with this scenario? Most likely, you know you have to return an HTTP status code. But what is the more appropriate one? Should it be 401 Unauthorized
or 403 Forbidden
? Or maybe something else?
As usual, it depends 🙂. It depends on the specific scenario and also on the security level you want to provide. Let’s go a little deeper.
If you prefer, you can watch a video on the same topic:
Web APIs and HTTP Status Codes
Before going into the specific topic, let’s take a quick look at the rationale of HTTP status codes in general. Most Web APIs are inspired by the REST paradigm. Although the vast majority of them don’t actually implement REST, they usually follow a few RESTful conventions when it comes to HTTP status codes.
The basic principle behind these conventions is that a status code returned in a response must make the client aware of what is going on and what the server expects the client to do next. You can fulfill this principle by giving answers to the following questions:
- Is there a problem or not?
- If there is a problem, on which side is it? On the client or on the server side?
- If there is a problem, what should the client do?
This is a general principle that applies to all the HTTP status codes. For example, if the client receives a 200 OK
status code, it knows there was no problem with its request and expects the requested resource representation in the response’s body. If the client receives a 201 Created
status code, it knows there was no problem with its request, but the resource representation is not in the response’s body. Similarly, when the client receives a 500 Internal Server Error
status code, it knows that this is a problem on the server side, and the client can’t do anything to mitigate it.
In summary, your Web API’s response should provide the client with enough information to realize how it can move forward opportunely.
Let’s consider the case when a client attempts to call a protected API. If the client provides the appropriate credentials (e.g., a valid access token), its request is accepted and processed. What happens when the client has no appropriate credentials? What status code should your API return when a request is not legitimate? What information should it return, and how to guarantee the best security experience?
Fortunately, in the OAuth security context, you have some guidelines. Of course, you can use them even if you don’t use OAuth to secure your API.
«The basic principle behind REST status code conventions is that a status code must make the client aware of what is going on and what the server expects the client to do next»
Tweet This
When to Use 400 Bad Request?
Let’s start with a simple case: a client calls your protected API, omitting a required parameter. In this case, your API should respond with a 400 Bad Request
status code. In fact, if that parameter is required, your API can’t even process the client request. The client’s request is malformed.
Your API should return the same status code even when the client provides an unsupported parameter or repeats the same parameter multiple times in its request. In both cases, the client’s request is not as expected and should be refused.
Following the general principle discussed above, the client should be empowered to understand what to do to fix the problem. So, you should add in your response’s body what was wrong with the client’s request. You can provide those details in the format you prefer, such as simple text, XML, JSON, etc. However, using a standard format like the one proposed by the Problem Details for HTTP APIs specifications would be more appropriate to enable uniform problem management across clients.
For example, if your client calls your API with an empty value for the required data
parameter, the API could reply with the following response:
HTTP/1.1 400 Bad Request
Content-Type: application/problem+json
Content-Language: en
{
"type": "https://myapi.com/validation-error",
"title": "Validation error",
"detail": "Your request parameters are not valid.",
"invalid-params": [
{
"name": "data",
"reason": "cannot be blank."
}
]
}
When to Use 401 Unauthorized?
Now, let’s assume that the client calls your protected API with a well-formed request but no valid credentials. For example, in the OAuth context, this may fall in one of the following cases:
- An access token is missing.
- An access token is expired, revoked, malformed, or invalid for other reasons.
In both cases, the appropriate status code to reply with is 401 Unauthorized
. In the spirit of mutual collaboration between the client and the API, the response must include a hint on how to obtain such authorization. That comes in the form of the WWW-Authenticate
header with the specific authentication scheme to use. For example, in the case of OAuth2, the response should look like the following:
HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer realm="example"
You have to use the Bearer
scheme and provide the realm
parameter to indicate the set of resources the API is protecting.
If the client request does not include any access token, demonstrating that it wasn’t aware that the API is protected, the API’s response should not include any other information.
On the other hand, if the client’s request includes an expired access token, the API response could include the reason for the denied access, as shown in the following example:
HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer realm="example",
error="invalid_token",
error_description="The access token expired"
When to Use 403 Forbidden?
Let’s explore a different case now. Assume, for example, that your client sends a request to modify a document and provides a valid access token to the API. However, that token doesn’t include or imply any permission or scope that allows the client to perform the desired action.
In this case, your API should respond with a 403 Forbidden
status code. With this status code, your API tells the client that the credentials it provided (e.g., the access token) are valid, but it needs appropriate privileges to perform the requested action.
To help the client understand what to do next, your API may include what privileges are needed in its response. For example, according to the OAuth2 guidelines, your API may include information about the missing scope to access the protected resource.
Try out the most powerful authentication platform for free.Get started →
Security Considerations
When you plan how to respond to your client’s requests, always keep security in mind.
How to deal with response details
A primary security concern is to avoid providing useful information to potential attackers. In other words, returning detailed information in the API responses to attempts to access protected resources may be a security risk.
For example, suppose your API returns a 401 Unauthorized
status code with an error description like The access token is expired
. In this case, it gives information about the token itself to a potential attacker. The same happens when your API responds with a 403 Forbidden
status code and reports the missing scope or privilege.
In other words, sharing this information can improve the collaboration between the client and the server, according to the basic principle of the REST paradigm. However, the same information may be used by malicious attackers to elaborate their attack strategy.
Since this additional information is optional for both the HTTP specifications and the OAuth2 bearer token guidelines, maybe you should think carefully about sharing it. The basic principle on sharing that additional information should be based on the answer to this question: how would the client behave any differently if provided with more information?
For example, in the case of a response with a 401 Unauthorized
status code, does the client’s behavior change when it knows that its token is expired or revoked? In any case, it must request a new token. So, adding that information doesn’t change the client’s behavior.
Different is the case with 403 Forbidden
. By informing your client that it needs a specific permission, your API makes it learn what to do next, i.e., requesting that additional permission. If your API doesn’t provide this additional information, it will behave differently because it doesn’t know what to do to access that resource.
Don’t let the client know…
Now, assume your client attempts to access a resource that it MUST NOT access at all, for example, because it belongs to another user. What status code should your API return? Should it return a 403
or a 401
status code?
You may be tempted to return a 403
status code anyway. But, actually, you can’t suggest any missing permission because that client has no way to access that resource. So, the 403
status code gives no actual helpful information. You may think that returning a 401
status code makes sense in this case. After all, the resource belongs to another user, so the request should come from a different user.
However, since that resource shouldn’t be reached by the current client, the best option is to hide it. Letting the client (and especially the user behind it) know that resource exists could possibly lead to Insecure Direct Object References (IDOR), an access control vulnerability based on the knowledge of resources you shouldn’t access. Therefore, in these cases, your API should respond with a 404 Not Found
status code. This is an option provided by the HTTP specification:
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).
For example, this is the strategy adopted by GitHub when you don’t have any permission to access a repository. This approach avoids that an attacker attempts to access the resource again with a slightly different strategy.
How to deal with bad requests
When a client sends a malformed request, you know you should reply with a 400 Bad Request
status code. You may be tempted to analyze the request’s correctness before evaluating the client credentials. You shouldn’t do this for a few reasons:
- By evaluating the client credentials before the request’s validity, you avoid your API processing requests that aren’t allowed to be there.
- A potential attacker could figure out how a request should look without being authenticated, even before obtaining or stealing a legitimate access token.
Also, consider that in infrastructures with an API gateway, the client credentials will be evaluated beforehand by the gateway itself, which doesn’t know at all what parameters the API is expecting.
The security measures discussed here must be applied in the production environment. Of course, in the development environment, your API can provide all the information you need to be able to diagnose the causes of an authorization failure.
Recap
Throughout this article, you learned that:
400 Bad Request
is the status code to return when the form of the client request is not as the API expects.401 Unauthorized
is the status code to return when the client provides no credentials or invalid credentials.403 Forbidden
is the status code to return when a client has valid credentials but not enough privileges to perform an action on a resource.
You also learned that some security concerns might arise when your API exposes details that malicious attackers may exploit. In these cases, you may adopt a more restricted strategy by including just the needed details in the response body or even using the 404 Not Found
status code instead of 403 Forbidden
or 401 Unauthorized
.
The following cheat sheet summarizes what you learned:
Перейти к содержанию
Ошибка 401 – это код состояния HTTP, который означает, что страница к которой вы пытались получить доступ, не может быть загружена, пока вы не войдете в систему с действительным идентификатором пользователя и паролем.
Если вы только что вошли в систему и получили 401 ошибку, это означает, что введенные вами учетные данные по какой-то причине были недействительными.
401 Несанкционированные сообщения об ошибках часто настраиваются каждым веб-сайтом индивидуально, поэтому имейте в виду, что эта ошибка может проявляться в большем количестве вариаций написания, самые распространенные:
- 401 Несанкционированный доступ
- Требуется авторизация
- Ошибка HTTP 401 unautorized access denided
Ошибка авторизации 401 отображается в окне веб-браузера. Как и большинство подобных ошибок, вы можете встретить их во всех браузерах, работающих в любой операционной системе.
Содержание
- Как исправить ошибку 401
- Коды ошибки 401: основные внутренние ошибки сервера
- Ошибки похожие на 401
Как исправить ошибку 401
-
Проверьте правильность написания URL на наличие ошибок. Возможно, произошла ошибка 401 Unauthorized, потому что URL был введен неправильно или выбранная ссылка указывает на неправильный URL – только для авторизованных пользователей.
-
Если вы уверены, что URL-адрес правильный, посетите главную страницу веб-сайта и найдите ссылку с надписью «Логин» или «Безопасный доступ». Введите свои учетные данные здесь, а затем попробуйте загрузить страницу еще раз.
Если у вас нет учетных данных или вы их забыли, следуйте инструкциям на веб-сайте для настройки учетной записи или изменения пароля.
- Почистите кеш вашего браузера. Возможно, в вашем браузере хранится неверная информация для входа в систему, что нарушает процесс входа и выдает ошибку 401. Очистка кэша устранит все проблемы в этих файлах и даст странице возможность загружать свежие файлы прямо с сервера.
- Если вы уверены, что страница, которую вы пытаетесь открыть, не нуждается в авторизации, сообщение 401 Unauthorized может быть ошибкой. В этот момент, вероятно, лучше всего связаться с веб-мастером или другим контактом веб-сайта и сообщить им о проблеме.
- Перезагрузите страницу. Как бы просто это не показалось, закрытия страницы и ее повторного открытия может быть достаточно для исправления ошибки 401, но только если она вызвана ошибочно загруженной страницей.
Коды ошибки 401: основные внутренние ошибки сервера
Веб-серверы, работающие под управлением Microsoft IIS, могут предоставить дополнительную информацию об ошибке 401 Unauthorized, например:
Коды ошибок Microsoft IIS 401 | |
---|---|
ошибка | объяснение |
401,1 | Войти не удалось. |
401,2 | Ошибка входа в систему из-за конфигурации сервера. |
401,3 | Несанкционированный из-за ACL на ресурс. |
401,4 | Авторизация не пройдена фильтром. |
401,5 | Ошибка авторизации приложением ISAPI / CGI. |
401,501 | Доступ запрещен: слишком много запросов с одного и того же клиентского IP ; Ограничение динамического IP-адреса Достигнут предел одновременных запросов. |
401,502 | Запрещено: слишком много запросов с одного IP-адреса клиента; Ограничение динамического IP- адреса Достигнут максимальный предел скорости запросов. |
401,503 | Отказ в доступе: IP-адрес включен в список Запретить ограничение IP |
401,504 | Отказ в доступе: имя хоста включено в список Запретить ограничение IP |
Ошибки похожие на 401
Просмотров 6.6к.
Обновлено 18.04.2020