401 ошибка при api

  1. Error description
  2. Short error description in the response
  3. Example of an error message

If an error occurs, the request processing stops, and the server returns an HTTP response code that identifies the error. In addition to the code, the response contains a short error description.

The error message is returned in the format specified in the request URL after the method name or in the Accept HTTP header.

The error description is passed in the error parameter. This parameter contains the error code (the code parameter) and a short error description (the message parameter).

Code

Name

Explanation

200

OK

The request is successfully completed.

206

Partial Content

The request is partially completed.

400

Bad Request

The request is invalid.

401

Unauthorized

The request doesn’t include authorization data.

403

Forbidden

Incorrect authorization data is specified in the request, or access to the requested resource is denied.

404

Not Found

The requested resource isn’t found.

405

Method Not Allowed

The requested method isn’t supported for the specified resource.

415

Unsupported Media Type

The requested content type isn’t supported by the method.

420

Enhance Your Calm

The resource access restriction is exceeded.

500

Internal Server Error

Internal server error. Try calling the method after a while. If the error persists, contact the Yandex.Market support service.

503

Service Unavailable

The server is temporarily unavailable due to high load. Try calling the method after a while.

  • For the 400 Bad Request error:

    Description

    Explanation

    Possible solution

    Collection of field must not be empty

    The parameter must not be empty.

    Specify at least one element for the parameter.

    Invalid status: 'status'

    Invalid status is specified.

    Check if the sent status is correct for order filtering by status.

    JSON: {message}

    The JSON data format contains an error.

    Check if the data passed in the request body has the correct JSON format.

    Missing field

    The required parameter isn’t specified.

    Specify a value for the required parameter.

    The request is too big

    The HTTP request size limit is exceeded.

    Cut the request size by reducing the amount of the sent data.

    Too long time period. Maximum is 'maxPeriod' days

    The specified date range is too large. Maximum range — maxPeriod.

    Reduce the date range to filter orders by date.

    Unexpected character 'character': expected a valid value 'values'

    Invalid character.

    Check the request body encoding. The required encoding is UTF-8.

    Unexpected end of content

    The request body ends unexpectedly.

    Check if the data passed in the request body has the correct format.

    Value / length of field (value) must be between min and max [exclusively]

    The parameter value (length) must be between the min and max values and not equal to them.

    Check if the parameter value is correct.

    Value / length of field (value) must be greater / less than [or equal to] limit

    The parameter value (length) must be equal to or greater than (less than) the specified limit value.

    Check if the parameter value is correct.

    Value of field has too high scale: 'price'

    The accuracy of the parameter is set too high.

    Set the parameter values with less precision.

    Value of field must match the pattern: 'regExp'

    The parameter value must match the regular expression.

    Check if the parameter value is correct.

    XML: {message}

    The XML data format contains an error.

    Check if the data passed in the request body has the correct XML format.

    Other short descriptions that can be found in messages about this error are provided in the descriptions of the corresponding resources.

  • For the 401 Unauthorized error:

    Description

    Explanation

    Possible solution

    Unsupported authorization type specified in Authorization header

    Authorization type passed in the Authorization HTTP header isn’t supported.

    Check if the authorization data is correct.

    Authorization header has invalid syntax

    The Authorization HTTP header format is incorrect.

    Check if the authorization data is correct.

    OAuth credentials are not specified

    The request doesn’t include authorization data.

    Check that the authorization data is correct.

    OAuth token is not specified

    The request doesn’t include the authorization token (the oauth_token parameter).

    Check if the authorization data is correct.

    OAuth client id is not specified

    The request doesn’t include the application ID (the oauth_client_id parameter).

    Check if the authorization data is correct.

  • For the 403 Forbidden error:

    Description

    Explanation

    Possible solution

    Access denied

    Access to the specified resource is prohibited.

    Check if the resource is specified correctly, and if the authorized user login has access to it.

    Access to API denied for the client / campaign

    The client or store isn’t allowed to access the Yandex.Market Partner API.

    Agency clients should contact their agency about getting access to the Yandex.Market Partner API.

    Client id is invalid

    The specified application ID (the oauth_client_id parameter) is invalid.

    Check if the authorization data is correct. If they are correct, get a new app ID, repeat the request with the new authorization data.

    Scope is invalid

    The specified authorization token (the oauth_token parameter) doesn’t have the necessary set of rights.

    Get a new authorization token, mention the right to use the Yandex.Market Partner API when you receive it, and repeat the request with the new authorization data.

    Token is invalid

    The specified authorization token (parameter oauth_token) is invalid.

    Check if the authorization data is correct. If they are correct, get a new authorization token, repeat the request with the new authorization data.

    User account is disabled

    The user account for which the specified authorization token was issued is blocked.

    Contact the Yandex.Market support service.

  • For the 404 Not Found error:

    Description

    Explanation

    Possible solution

    Feed not found: 'feedId'

    The price list specified in the request isn’t found.

    Check if the sent price list ID is correct.

    Login not found: 'login'

    The username specified in the request isn’t found.

    Check if the sent username is correct.

    Model not found: 'modelId'

    The model specified in the request isn’t found.

    Check if the model ID you are passing is correct.

  • For the 405 Method Not Allowed error:

    Description

    Explanation

    Possible solution

    Request method 'method' not supported

    The requested HTTP method isn’t supported.

    Check the methods supported by the resource. You can find the list of methods in the Requests reference section.

  • For the 415 Unsupported Media Type error:

    Description

    Explanation

    Possible solution

    Content type 'content-type' not supported

    The requested content type isn’t supported.

    Pass one of the supported content types.

    Missing Content-Type

    The content type isn’t specified.

    Pass the content type.

    Unknown content-type: 'content-type'

    The requested content type is unknown.

    Pass one of the supported content types.

  • For the 420 Enhance Your Calm error:

    Description

    Explanation

    Possible solution

    Hit rate limit of 'N' parallel requests

    Exceeded the global limit on the number of simultaneous requests to the Yandex.Market Partner API.

    Reduce the number of concurrent requests to the partner API within a single store or partner to N requests.

    Hit rate limit of 'N' requests per 'period' for resource 'R'

    The resource restriction for the N number of requests to the R resource over the period for the same store or partner is exceeded.

    The time until which the limit applies is specified in the X-RateLimit-Resource-Until header. You can use of the resource after the specified time.

  • For the 503 Service Unavailable error:

    Description

    Explanation

    Possible solution

    Service temporarily unavailable. Please, try again later

    The server is temporarily unavailable due to high load.

    Try repeating the request after a while.

Request example:

GET /v2/campaigns.xml HTTP/1.1
Host: api.partner.market.yandex.ru
Accept: */*
Authorization: OAuth oauth_token=,oauth_client_id=b12320932d4e401ab6e1ba43d553d433

Response example:

<response>
  <errors>
    <error code="UNAUTHORIZED" message="OAuth token is not specified"/>
  </errors>
  <error code="401">
    <message>OAuth token is not specified</message>
  </error>
</response>

Request example:

GET /v2/campaigns.json HTTP/1.1
Host: api.partner.market.yandex.ru
Accept: */*
Authorization: OAuth oauth_token=,oauth_client_id=b12320932d4e401ab6e1ba43d553d433

Response example:

{
  "errors":
  [
    {
      "code": "UNAUTHORIZED",
      "message": "OAuth token is not specified"
    }
  ],
  "error":
  {
    "code": 401,
    "message": "OAuth token is not specified"
  }
}

Improve Article

Save Article

Like Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    Like Article

    The 401 Unauthorized Error is an HTTP status code error that represented the request sent by the client to the server that lacks valid authentication credentials. It may be represented as 401 Unauthorized, Authorization required, HTTP error 401- Unauthorized. It represents that the request could not be authenticated. It consists of a www-Authenticate header which contains the hint on how to authorize correctly. 

    401 Unauthorized Error Occur: This error may occur due to the reasons described below: 

    • It may occur client does not provide the proper authentication credentials to the server within the request time.
    • It may occur when the server rejects the request of the client for some reason even though the client provides proper authentication credentials.
    • When the client is banned for some reason by the server.

    Methods to rectify the error: The 401 Unauthorized error can be fixed by using any of the following ways: 

    • Check The URL: Due to manual errors in typing the URL, the 401 unauthorized error may occur. Hence, checking the URL and rectifying the mistakes in it will fix the 401 error status.
    • Flush the DNS: Errors in DNS also creates 401 error status sometimes. Therefore, clearing the DNS will also rectify this error. In Windows, the DNS can be flushed by typing ipconfig/flushdns in the command prompt and clicking on ENTER.
    • Clear Browser Cookie: In some situations, the cookies may not work smoothly leading to improper server authentication. Thus, by clearing the cookies, the error can be rectified.
    • Logging out and Logging in again: This error may also occur during the maintenance time of the websites. Therefore, visiting the website and logging in again by providing the credentials may also rectify this error.
    • Website mistake: A few times all the above things are good or accurate but still you will get the 401 Unauthorized Error, which is a mistake of the website. That time you need to contact the webmaster of that website and inform that the server is down. You can email them at webmaster@webmaster.com replace the webmaster.com with the website, or you can see the contact us option on any website through that you can inform them.

    Some other ways of 401 Authentication error: This error can occur in the below forms also: 

    • 401.1: This error represents that the login has failed due to some reasons.
    • 401.2: This error represents that the login has failed due to server configuration.
    • 401.3: This error represents that the login has failed due to ACL(Access-control list) on the resource.
    • 401.3: This error represents that the authorization has been failed by the filter.
    • 401.501: This error represents that too many requests have been generated by the client i.e. maximum request limit has been reached by the client.
    • 401.502: This error occurs when any specific client(sam IP) requests multiple times on a single server that the dynamic IP Restriction Concurrent request rate limit reached. Then this error will occur 
       
    • 401.503: This error represents that the IP address of the client is in the deny list of IP restrictions on the server-side.
    • 401.504: This error represents that the Hostname of the client is in the deny list of IP restrictions on the server-side.

    Last Updated :
    24 May, 2021

    Like Article

    Save Article

    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

    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:

    4xx HTTP status codes cheat sheet

    REST API использует строку состояния в HTTP ответе (статус ответа), чтобы информировать Клиентов о результате запроса.

    Вообще HTTP определяет 40 стандартных кодов состояния (статусов ответа), которые делятся на пять категорий. Ниже выделены только те коды состояния, которые часто используются в REST API.

    Категория Описание
    1xx: Информация В этот класс содержит заголовки информирующие о процессе передачи. Это обычно предварительный ответ, состоящий только из Status-Line и опциональных заголовков, и завершается пустой строкой. Нет обязательных заголовков. Серверы НЕ ДОЛЖНЫ посылать 1xx ответы HTTP/1.0 клиентам.
    2xx: Успех Этот класс кодов состояния указывает, что запрос клиента был успешно получен, понят, и принят.
    3xx: Перенаправление Коды этого класса сообщают клиенту, что для успешного выполнения операции необходимо сделать другой запрос, как правило, по другому URI. Из данного класса пять кодов 301, 302, 303, 305 и 307 относятся непосредственно к перенаправлениям.
    4xx: Ошибка клиента Класс кодов 4xx предназначен для указания ошибок со стороны клиента.
    5xx: Ошибка сервера Коды ответов, начинающиеся с «5» указывают на случаи, когда сервер знает, что произошла ошибка или он не может обработать запрос.

    Коды состояний в REST

    Звездочкой * помечены популярные (часто используемые) коды ответов.

    200 * (OK)

    Запрос выполнен успешно. Информация, возвращаемая с ответом зависит от метода, используемого в запросе, например при:

    • GET Получен объект, соответствующий запрошенному ресурсу.
    • HEAD Получены поля заголовков, соответствующие запрошенному ресурсу, тело ответа пустое.
    • POST Запрошенное действие выполнено.

    201 * (Created — Создано)

    REST API отвечает кодом состояния 201 при каждом создании ресурса в коллекции. Также могут быть случаи, когда новый ресурс создается в результате какого-либо действия контроллера, и в этом случае 201 также будет подходящем ответом.

    Ссылка (URL) на новый ресурс может быть в теле ответа или в поле заголовка ответа Location.

    Сервер должен создать ресурс перед тем как вернуть 201 статус. Если это невозможно сделать сразу, тогда сервер должен ответить кодом 202 (Accepted).

    202 (Accepted — Принято)

    Ответ 202 обычно используется для действий, которые занимают много времени для обработки и не могут быть выполнены сразу. Это означает, что запрос принят к обработке, но обработка не завершена.

    Его цель состоит в том, чтобы позволить серверу принять запрос на какой-либо другой процесс (возможно, пакетный процесс, который выполняется только один раз в день), не требуя, чтобы соединение агента пользователя с сервером сохранялось до тех пор, пока процесс не будет завершен.

    Сущность, возвращаемая с этим ответом, должна содержать указание на текущее состояние запроса и указатель на монитор состояния (расположение очереди заданий) или некоторую оценку того, когда пользователь может ожидать выполнения запроса.

    203 (Non-Authoritative Information — Неавторитетная информация)

    Предоставленная информация взята не из оригинального источника (а, например, из кэша, который мог устареть, или из резервной копии, которая могла потерять актуальность). Этот факт отражен в заголовке ответа и подтверждается этим кодом. Предоставленная информация может совпадать, а может и не совпадать с оригинальными данными.

    204 * (No Content — Нет контента)

    Код состояния 204 обычно отправляется в ответ на запрос PUT, POST или DELETE, когда REST API отказывается отправлять обратно любое сообщение о состоянии проделанной работы.

    API может также отправить 204 статус в ответ на GET запрос, чтобы указать, что запрошенный ресурс существует, но не имеет данных для добавления их в тело ответа.

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

    205 — (Reset Content — Сброшенное содержимое)

    Сервер успешно обработал запрос и обязывает клиента сбросить введенные пользователем данные. В ответе не должно передаваться никаких данных (в теле ответа). Обычно применяется для возврата в начальное состояние формы ввода данных на клиенте.

    206 — (Partial Content — Частичное содержимое)

    Сервер выполнил часть GET запроса ресурса. Запрос ДОЛЖЕН был содержать поле заголовка Range (секция 14.35), который указывает на желаемый диапазон и МОГ содержать поле заголовка If-Range (секция 14.27), который делает запрос условным.

    Запрос ДОЛЖЕН содержать следующие поля заголовка:

    • Либо поле Content-Range (секция 14.16), который показывает диапазон, включённый в этот запрос, либо Content-Type со значением multipart/byteranges, включающими в себя поля Content-Range для каждой части. Если в заголовке запроса есть поле Content-Length, его значение ДОЛЖНО совпадать с фактическим количеством октетов, переданных в теле сообщения.
    • Date
    • ETag и/или Content-Location, если ранее был получен ответ 200 на такой же запрос.
    • Expires, Cache-Control, и/или Vary, если значение поля изменилось с момента отправления последнего такого же запроса

    Если ответ 206 — это результат выполнения условного запроса, который использовал строгий кэш-валидатор (подробнее в секции 13.3.3), в ответ НЕ СЛЕДУЕТ включать какие-либо другие заголовки сущности. Если такой ответ — результат выполнения запроса If-Range, который использовал «слабый» валидатор, то ответ НЕ ДОЛЖЕН содержать другие заголовки сущности; это предотвращает несоответствие между закэшированными телами сущностей и обновлёнными заголовками. В противном случае ответ ДОЛЖЕН содержать все заголовки сущностей, которые вернули статус 200 (OK) на тот же запрос.

    Кэш НЕ ДОЛЖЕН объединять ответ 206 с другими ранее закэшированными данными, если поле ETag или Last-Modified в точности не совпадают (подробнее в секции 16.5.4)

    Кэш, который не поддерживает заголовки Range и Content-Range НЕ ДОЛЖЕН кэшировать ответы 206 (Partial).

    300 — (Multiple Choices — Несколько вариантов)

    По указанному URI существует несколько вариантов предоставления ресурса по типу MIME, по языку или по другим характеристикам. Сервер передаёт с сообщением список альтернатив, давая возможность сделать выбор клиенту автоматически или пользователю.

    Если это не запрос HEAD, ответ ДОЛЖЕН включать объект, содержащий список характеристик и адресов, из которого пользователь или агент пользователя может выбрать один наиболее подходящий. Формат объекта определяется по типу данных приведённых в Content-Type поля заголовка. В зависимости от формата и возможностей агента пользователя, выбор наиболее подходящего варианта может выполняться автоматически. Однако эта спецификация не определяет никакого стандарта для автоматического выбора.

    Если у сервера есть предпочтительный выбор представления, он ДОЛЖЕН включить конкретный URI для этого представления в поле Location; агент пользователя МОЖЕТ использовать заголовок Location для автоматического перенаправления к предложенному ресурсу. Этот запрос может быть закэширован, если явно не было указано иного.

    301 (Moved Permanently — Перемещено навсегда)

    Код перенаправления. Указывает, что модель ресурсов REST API была сильно изменена и теперь имеет новый URL. Rest API должен указать новый URI в заголовке ответа Location, и все будущие запросы должны быть направлены на указанный URI.

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

    302 (Found — Найдено)

    Является распространенным способом выполнить перенаправление на другой URL. HTTP-ответ с этим кодом должен дополнительно предоставит URL-адрес куда перенаправлять в поле заголовка Location. Агенту пользователя (например, браузеру) предлагается в ответе с этим кодом сделать второй запрос на новый URL.

    Многие браузеры реализовали этот код таким образом, что нарушили стандарт. Они начали изменять Тип исходного запроса, например с POST на GET. Коды состояния 303 и 307 были добавлены для серверов, которые хотят однозначно определить, какая реакция ожидается от клиента.

    303 (See Other — Смотрите другое)

    Ответ 303 указывает, что ресурс контроллера завершил свою работу, но вместо отправки нежелательного тела ответа он отправляет клиенту URI ресурса. Это может быть URI временного сообщения о состоянии ресурса или URI для уже существующего постоянного ресурса.

    Код состояния 303 позволяет REST API указать ссылку на ресурс, не заставляя клиента загружать ответ. Вместо этого клиент может отправить GET запрос на URL указанный в заголовке Location.

    Ответ 303 не должен кэшироваться, но ответ на второй (перенаправленный) запрос может быть кэшируемым.

    304 * (Not Modified — Не изменен)

    Этот код состояния похож на 204 (Нет контента), так как тело ответа должно быть пустым. Ключевое различие состоит в том, что 204 используется, когда нет ничего для отправки в теле, тогда как 304 используется, когда ресурс не был изменен с версии, указанной заголовками запроса If-Modified-Since или If-None-Match.

    В таком случае нет необходимости повторно передавать ресурс, так как у клиента все еще есть ранее загруженная копия.

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

    305 — (Use Proxy — Используйте прокси)

    Доступ к запрошенному ресурсу ДОЛЖЕН быть осуществлен через прокси-сервер, указанный в поле Location. Поле Location предоставляет URI прокси. Ожидается, что получатель повторит этот запрос с помощью прокси. Ответ 305 может генерироваться ТОЛЬКО серверами-источниками.

    Заметьте: в спецификации RFC 2068 однозначно не сказано, что ответ 305 предназначен для перенаправления единственного запроса, и что он должен генерироваться только сервером-источником. Упущение этих ограничений вызвало ряд значительных последствий для безопасности.

    Многие HTTP клиенты (такие, как Mozilla и Internet Explorer) обрабатывают этот статус некорректно прежде всего из соображений безопасности.

    307 (Temporary Redirect — Временный редирект)

    Ответ 307 указывает, что rest API не будет обрабатывать запрос клиента. Вместо этого клиент должен повторно отправить запрос на URL, указанный в заголовке Location. Однако в будущих запросах клиент по-прежнему должен использоваться исходный URL.

    Rest API может использовать этот код состояния для назначения временного URL запрашиваемому ресурсу.

    Если метод запроса не HEAD, тело ответа должно содержать короткую заметку с гиперссылкой на новый URL. Если код 307 был получен в ответ на запрос, отличный от GET или HEAD, Клиент не должен автоматически перенаправлять запрос, если он не может быть подтвержден Клиентом, так как это может изменить условия, при которых был создан запрос.

    308 — (Permanent Redirect — Постоянное перенаправление) (experimental)

    Нужно повторить запрос на другой адрес без изменения применяемого метода.

    Этот и все последующие запросы нужно повторить на другой URI. 307 и 308 (как предложено) Схож в поведении с 302 и 301, но не требуют замены HTTP метода. Таким образом, например, отправку формы на «постоянно перенаправленный» ресурс можно продолжать без проблем.

    400 * (Bad Request — Плохой запрос)

    Это общий статус ошибки на стороне Клиента. Используется, когда никакой другой код ошибки 4xx не уместен. Ошибки могут быть как неправильный синтаксис запроса, неверные параметры запроса, запросы вводящие в заблуждение или маршрутизатор и т.д.

    Клиент не должен повторять точно такой же запрос.

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

    401 сообщение об ошибке указывает, что клиент пытается работать с закрытым ресурсом без предоставления данных авторизации. Возможно, он предоставил неправильные учетные данные или вообще ничего. Ответ должен включать поле заголовка WWW-Authenticate, содержащего описание проблемы.

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

    402 — (Payment Required — Требуется оплата)

    Этот код зарезервирован для использования в будущем.

    Предполагается использовать в будущем. В настоящий момент не используется. Этот код предусмотрен для платных пользовательских сервисов, а не для хостинговых компаний. Имеется в виду, что эта ошибка не будет выдана хостинговым провайдером в случае просроченной оплаты его услуг. Зарезервирован, начиная с HTTP/1.1.

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

    Ошибка 403 указывает, что rest API отказывается выполнять запрос клиента, т.е. Клиент не имеет необходимых разрешений для доступа. Ответ 403 не является случаем, когда нужна авторизация (для ошибки авторизации используется код 401).

    Попытка аутентификация не поможет, и повторные запросы не имеют смысла.

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

    Указывает, что rest API не может сопоставить URL клиента с ресурсом, но этот URL может быть доступен в будущем. Последующие запросы клиента допустимы.

    404 не указывает, является ли состояние временным или постоянным. Для указания постоянного состояния используется код 410 (Gone — Пропал). 410 использоваться, если сервер знает, что старый ресурс постоянно недоступен и более не имеет адреса.

    405 (Method Not Allowed — Метод не разрешен)

    API выдает ошибку 405, когда клиент пытался использовать HTTP метод, который недопустим для ресурса. Например, указан метод PUT, но такого метода у ресурса нет.

    Ответ 405 должен включать Заголовок Allow, в котором перечислены поддерживаемые HTTP методы, например, Allow: GET, POST.

    406 (Not Acceptable — Неприемлемый)

    API не может генерировать предпочитаемые клиентом типы данных, которые указаны в заголовке запроса Accept. Например, запрос клиента на данные в формате application/xml получит ответ 406, если API умеет отдавать данные только в формате application/json.

    В таких случаях Клиент должен решить проблему данных у себя и только потом отправлять запросы повторно.

    407 — (Proxy Authentication Required — Требуется прокси-аутентификация)

    Ответ аналогичен коду 401, за исключением того, что аутентификация производится для прокси-сервера. Механизм аналогичен идентификации на исходном сервере.

    Пользователь должен сначала авторизоваться через прокси. Прокси-сервер должен вернуть Proxy-Authenticate заголовок, содержащий запрос ресурса. Клиент может повторить запрос вместе с Proxy-Authenticate заголовком. Появился в HTTP/1.1.

    408 — (Request Timeout — Таймаут запроса)

    Время ожидания сервером передачи от клиента истекло. Клиент не предоставил запрос за то время, пока сервер был готов его принят. Клиент МОЖЕТ повторить запрос без изменений в любое время.

    Например, такая ситуация может возникнуть при загрузке на сервер объёмного файла методом POST или PUT. В какой-то момент передачи источник данных перестал отвечать, например, из-за повреждения компакт-диска или потери связи с другим компьютером в локальной сети. Пока клиент ничего не передаёт, ожидая от него ответа, соединение с сервером держится. Через некоторое время сервер может закрыть соединение со своей стороны, чтобы дать возможность другим клиентам сделать запрос.

    409 * (Conflict — Конфликт)

    Запрос нельзя обработать из-за конфликта в текущем состоянии ресурса. Этот код разрешается использовать только в тех случаях, когда ожидается, что пользователь может самостоятельно разрешить этот конфликт и повторить запрос. В тело ответа СЛЕДУЕТ включить достаточное количество информации для того, чтобы пользователь смог понять причину конфликта. В идеале ответ должен содержать такую информацию, которая поможет пользователю или его агенту исправить проблему. Однако это не всегда возможно и это не обязательно.

    Как правило, конфликты происходят во время PUT-запроса. Например, во время использования версионирования, если сущность, к которой обращаются методом PUT, содержит изменения, конфликтующие с теми, что были сделаны ранее третьей стороной, серверу следует использовать ответ 409, чтобы дать понять пользователю, что этот запрос нельзя завершить. В этом случае в ответной сущности должен содержаться список изменений между двумя версиями в формате, который указан в поле заголовка Content-Type.

    410 — (Gone — Исчез)

    Такой ответ сервер посылает, если ресурс раньше был по указанному URL, но был удалён и теперь недоступен. Серверу в этом случае неизвестно и местоположение альтернативного документа, например, копии. Если у сервера есть подозрение, что документ в ближайшее время может быть восстановлен, то лучше клиенту передать код 404. Появился в HTTP/1.1.

    411 — (Length Required — Требуется длина)

    Для указанного ресурса клиент должен указать Content-Length в заголовке запроса. Без указания этого поля не стоит делать повторную попытку запроса к серверу по данному URI. Такой ответ естественен для запросов типа POST и PUT. Например, если по указанному URI производится загрузка файлов, а на сервере стоит ограничение на их объём. Тогда разумней будет проверить в самом начале заголовок Content-Length и сразу отказать в загрузке, чем провоцировать бессмысленную нагрузку, разрывая соединение, когда клиент действительно пришлёт слишком объёмное сообщение.

    412 — (Precondition Failed — Предварительное условие не выполнено)

    Возвращается, если ни одно из условных полей заголовка запроса не было выполнено.

    Когда клиент указывает rest API выполнять запрос только при выполнении определенных условий, а API не может выполнить запрос при таких условиях, то возвращается ответ 412.

    Этот код ответа позволяет клиенту записывать предварительные условия в метаинформации текущего ресурса, таким образом, предотвращая применение запрошенного метода к ресурсу, кроме того, что ожидается.

    413 — (Request Entity Too Large — Сущность запроса слишком большая)

    Возвращается в случае, если сервер отказывается обработать запрос по причине слишком большого размера тела запроса. Сервер может закрыть соединение, чтобы прекратить дальнейшую передачу запроса.

    Если проблема временная, то рекомендуется в ответ сервера включить заголовок Retry-After с указанием времени, по истечении которого можно повторить аналогичный запрос.

    414 — (Request-URI Too Long — Запрос-URI Слишком длинный)

    Сервер не может обработать запрос из-за слишком длинного указанного URL. Эту редкую ошибку можно спровоцировать, например, когда клиент пытается передать длинные параметры через метод GET, а не POST, когда клиент попадает в «чёрную дыру» перенаправлений (например, когда префикс URI указывает на своё же окончание), или когда сервер подвергается атаке со стороны клиента, который пытается использовать дыры в безопасности, которые встречаются на серверах с фиксированной длиной буфера для чтения или обработки Request-URI.

    415 (Unsupported Media Type — Неподдерживаемый медиа тип)

    Сообщение об ошибке 415 указывает, что API не может обработать предоставленный клиентом Тип медиа, как указано в заголовке запроса Content-Type.

    Например, запрос клиента содержит данные в формате application/xml, а API готов обработать только application/json. В этом случае клиент получит ответ 415.

    Например, клиент загружает изображение как image/svg+xml, но сервер требует, чтобы изображения использовали другой формат.

    428 — (Precondition Required — Требуется предварительное условие)

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

    Его типичное использование — избежать проблемы «потерянного обновления», когда клиент ПОЛУЧАЕТ состояние ресурса, изменяет его и ОТПРАВЛЯЕТ обратно на сервер, когда тем временем третья сторона изменила состояние на сервере, что привело к конфликту. Требуя, чтобы запросы были условными, сервер может гарантировать, что клиенты работают с правильными копиями.

    Ответы с этим кодом состояния ДОЛЖНЫ объяснять, как повторно отправить запрос.

    429 — (Too Many Requests — Слишком много запросов)

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

    Представления ответа ДОЛЖНЫ включать подробности, объясняющие условие, и МОГУТ включать заголовок Retry-After, указывающий, как долго ждать, прежде чем делать новый запрос.

    431 — (Request Header Fields Too Large — Слишком большие поля заголовка запроса)

    Код состояния 431 указывает на то, что сервер не желает обрабатывать запрос, поскольку его поля заголовка слишком велики. Запрос МОЖЕТ быть отправлен повторно после уменьшения размера полей заголовка запроса.

    Его можно использовать как в случае, когда совокупность полей заголовка запроса слишком велика, так и в случае неисправности одного поля заголовка. В последнем случае представление ответа ДОЛЖНО указывать, какое поле заголовка было слишком большим.

    444 — (No Response — Нет ответа) (Nginx)

    Код ответа Nginx. Сервер не вернул информацию и закрыл соединение. (полезно в качестве сдерживающего фактора для вредоносных программ)

    451 — (Unavailable For Legal Reasons — Недоступен по юридическим причинам)

    Доступ к ресурсу закрыт по юридическим причинам. Наиболее близким из существующих является код 403 Forbidden (сервер понял запрос, но отказывается его обработать). Однако в случае цензуры, особенно когда это требование к провайдерам заблокировать доступ к сайту, сервер никак не мог понять запроса — он его даже не получил. Совершенно точно подходит другой код: 305 Use Proxy. Однако такое использование этого кода может не понравиться цензорам. Было предложено несколько вариантов для нового кода, включая «112 Emergency. Censorship in action» и «460 Blocked by Repressive Regime»

    500 * (Internal Server Error — Внутренняя ошибка сервера)

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

    Большинство веб-платформ автоматически отвечают этим кодом состояния, когда при выполнении кода обработчика запроса возникла ошибка.

    Ошибка 500 никогда не зависит от клиента, поэтому для клиента разумно повторить точно такой же запрос, и надеяться что в этот раз сервер отработает без ошибок.

    501 (Not Implemented — Не реализован)

    Серверу либо неизвестен метод запроса, или ему (серверу) не хватает возможностей выполнить запрос. Обычно это подразумевает будущую доступность (например, новая функция API веб-сервиса).

    Если же метод серверу известен, но он не применим к данному ресурсу, то нужно вернуть ответ 405.

    502 — (Bad Gateway — Плохой шлюз)

    Сервер, выступая в роли шлюза или прокси-сервера, получил некорректный ответ от вышестоящего сервера, к которому он обратился. Появился в HTTP/1.0.

    503 — (Service Unavailable — Служба недоступна)

    Сервер не может обработать запрос из-за временной перегрузки или технических работ. Это временное состояние, из которого сервер выйдет через какое-то время. Если это время известно, то его МОЖНО передать в заголовке Retry-After.

    504 — (Gateway Timeout — Таймаут шлюза)

    Сервер, в роли шлюза или прокси-сервера, не дождался в рамках установленного таймаута ответа от вышестоящего сервера текущего запроса.

    505 — (HTTP Version Not Supported — Версия HTTP не поддерживается)

    Сервер не поддерживает или отказывается поддерживать указанную в запросе версию протокола HTTP.

    510 — (Not Extended — Не расширен)

    В запросе не соблюдена политика доступа к ресурсу. Сервер должен отправить обратно всю информацию, необходимую клиенту для отправки расширенного запроса. Указание того, как расширения информируют клиента, выходит за рамки данной спецификации.

    Источники и более подробная информация:

    • https://restapitutorial.ru/httpstatuscodes.html
    • https://www.restapitutorial.com/httpstatuscodes.html
    • https://restfulapi.net/http-status-codes/
    • https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/428

    Trying to access a site and being met with an error page is at best inconvenient, whether that site is yours or someone else’s. As with many HTTP response codes, part of what makes a 401 error so frustrating is the lack of information it offers for diagnosing and resolving the issue.

    The 401 error can happen with any browser, so it’s a pretty common issue people face. In most cases, this problem is relatively simple and straightforward to fix.

    In this post, we’ll explain what 401 error messages are and why they happen. Then, we’ll walk you through five methods you can use to fix them.

    Let’s get started!

    What is the 401 Error Code?

    The Internet Engineering Task Force (IETF) defines the error 401 Unauthorized as:

    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 containing at least one challenge applicable to the target resource.

    An Introduction to the 401 Error Code

    HTTP 400 status codes are encountered when there is a problem making a request. A 401 error, in particular, happens when your browser denies you access to the page you’re trying to visit.

    As a result, instead of loading the web page, the browser will load an error message. 401 errors can happen within any browser so the message appearing may differ.

    For example, in Chrome or Edge, you’ll likely see a paper icon along with a simple message telling you that the page in question isn’t working. It will include the phrase “HTTP Error 401” at the bottom, and instruct you to contact the site’s owner if the problem persists:

    http error 401 in Chrome

    The 401 Error in Chrome

    At other times and in other browsers, you might get a slightly less friendly warning that’s just a blank page with a “401 Authorization Required” message:

    401 error Authorization Required

    Nginx 401 Authorization Required error message

    Other variations include:

    • “HTTP 401 Error – Unauthorized”
    • “401 Unauthorized”
    • “Access Denied”

    These errors occur on websites that require a login in order to access them. In most cases, it means that something is either wrong with the credentials or with the browser’s ability to read them as valid.

    This is similar to HTTP 403 Forbidden Error, in that access isn’t permitted to the user. However, unlike with the 403 error, the 401 error message indicates that the authentication process failed.

    The code is sent via the WWW-Authenticate header, which is responsible for identifying the authentication method used for granting access to a web page or resource.

    Error Code HTTP 401 Unauthorized Error
    Error Type Commonly a client-side error
    Error Variations 401 Authorization Required
    401 Unauthorized
    HTTP 401 Error – Unauthorized
    Access Denied
    Error Causes Outdated Browser Cache and Cookies
    Plugin Incompatibility
    Incorrect URL or Outdated Link

    The HTTP 401 error is all too common 🤦‍♀️ — and this guide will give you everything you need to fix it the next time you see that message showing up ✅Click to Tweet

    What Causes a 401 Error?

    If you encounter an error code in the 400s, you know you’re dealing with a client-side (or browser-side) issue. While the problem may be happening within your browser, however, it doesn’t necessarily always mean that’s the culprit, which we’ll explain in more detail later.

    401 errors occur on restricted resources, such as password-protected pages of your WordPress site. So it’s safe to assume that the cause of the problem has something to do with the authentication credentials.

    Outdated Browser Cache and Cookies

    One of the most common reasons you might experience a 401 error is that your browser’s cache and cookies are out of date, preventing the authorization from successfully going through. If your browser isn’t using the valid authentication credentials (or any at all), the server will reject the request.

    Plugin Incompatibility

    At other times, this error is caused by a plugin incompatibility or error. For example, a firewall or security plugin can mistake your login attempt as malicious activity, and return a 401 error to protect the page.

    Incorrect URL or Outdated Link

    It’s also possible that the source of the problem can be attributed to a minor mistake. Common culprits in this category include an incorrectly-typed URL or an outdated link.

    How to Fix the 401 Error?

    Now that we’ve gone through a bit of background on the 401 error, it’s time to discuss how you can resolve it.

    Let’s take a look at five methods you can use:

    1. Look for Errors in the URL

    We’ll start off with the easiest potential fix: making sure you used the correct URL. This may sound simple, but 401 errors can sometimes appear if the URL wasn’t correctly entered in.

    Another possibility is that the link you used to visit the page in question points to the wrong URL. For example, it might be outdated, or leading to a page that no longer exists (and no redirects are in place).

    Therefore, it’s worth double-checking the URL you used. If you typed it in yourself, verify that you spelled everything correctly. If you clicked on a link, confirm that it’s pointing to the page you’re trying to access (or try to visit that page directly through the website).

    2. Clear Your Browser’s Cache

    Your browser’s cache is designed to improve your online experience, by reducing page loading times. Unfortunately, sometimes it can also cause unwanted interruptions.

    As we mentioned earlier, one of the common causes of the 401 error is outdated or incorrect cache data or cookies. Therefore, if you don’t notice any issues with the page’s URL, the next step is to clear your browser’s cache.

    This will clean out any invalid information that’s locally stored in your browser, which could be interrupting the authentication process. Similarly, your browser’s cookies might contain authentication data that simply needs to be refreshed.

    If you’re a Google Chrome user, you can do this by clicking on the menu icon in the top-right corner of the browser, and then going to Settings. Under the Privacy and security section, click on Clear browsing data:

    clear browsing data to fix 401 error

    The Clear browsing data section in Google Chrome

    A new window will open. Under the Basic tab, make sure all three boxes are selected, and then select Clear data:

    chrome clear data

    The clear browsing data window in Chrome

    This process will look a little different in other browsers. For example, in Mozilla Firefox, you would click on the library icon in the top-right corner of the browser, followed by History > Clear Recent History:

    firefox clear history

    The ‘clear recent history’ option in Firefox settings

    In the panel that opens next, select Everything in the drop-down menu at the top, make sure “Cache” is selected, and then click on the Clear Now button:

    clear firefox cache

    The ‘Clear History’ panel in Firefox

    If you’re using a different browser, please refer to this guide for clearing the cache

    3. Flush Your DNS

    Another method you can try to resolve the 401 error is flushing your Domain Name Server (DNS). While this is a rarer issue, it can be a possible cause, so it’s worth giving it a try if the first two solutions don’t work.

    To do this in Windows, click on the Start button and type cmd into the search bar. Hit Enter, and the Command Prompt will open. Copy and paste the command ipconfig/flushdns, and then hit Enter again:

    command prompt

    The Command Prompt interface in Windows

    On a Mac, you can do this by going to Finder > Applications > Utilities > Terminal:

    The Terminal application on Mac

    The Terminal application on Mac

    Input the command line sudo killall -HUP mDNSResponder and press Enter. Then, you can try refreshing the page you were trying to visit, to see if the 401 error has been resolved.

    4. Deactivate Your WordPress Plugins

    The problem causing your 401 error might not be due to your browser. If you’re having trouble accessing your WordPress site, it’s also possible that one or more plugins are to blame.

    Some plugins, especially security-focused plugins, are configured to show a 401 error when they suspect suspicious login activity that might indicate an attack. Others might just be suffering from compatibility issues. Therefore, it’s a good idea to deactivate all of your WordPress plugins and see if that resolves the issue.

    You can deactivate your plugins all at the same time in your dashboard, by going to Plugins > Installed Plugins. Check the box at the top to select all of them. Then under the Bulk Actions drop-down menu, select Deactivate and click on the Apply button:

    The plugin deactivation setting in the WordPress dashboard

    The plugin deactivation setting in the WordPress dashboard

    After that, try reloading the page that returned the 401 error to see if this has resolved the issue. If it has, you can manually activate each plugin one at a time, in order to determine which one is causing the problem.

    Then you can remove that plugin, replace it with a new one, or contact its developer for assistance.

    5. Check the WWW-Authenticate Header Response

    At this point, if the issue hasn’t been fixed, it may be caused by a server-side problem. This means our last fix will be a bit more involved.

    As we saw earlier, the 401 response is sent through the WWW-Authenticate header, which appears as “WWW-Authenticate: <type> realm=<realm>”. It includes ‘challenges’, or strings of data that indicate what type of authentication is required in order for access to be granted.

    In a nutshell, you’ll want to check and see if the header response was sent, and more specifically, what authentication scheme was used. At the very least, this can help narrow down the cause of the problem, and bring you one step closer to a solution.

    To do this, go to the web page that’s displaying the 401 error, and access the developer console in Chrome. You can right-click on the page and select Inspect, or use Ctrl+Shift+J.

    Next, click on the Network tab and reload the page. This will generate a list of resources. Select the Status header to sort the table and locate the 401 status code:

    network status 401 error

    The 401 status code in the developer console in Chrome

    Select that entry, and then click on the Headers tab. Under Response Headers, locate the WWW-Authenticate header:

    www authenticate header

    The Response Headers section of the developer console

    The information that is present in the response header, particularly the authentication schemes, can give you more information about what’s happening and point you towards a solution. It can help you understand what type of authentication the server is expecting.

    For example, in the above example, we can see that the authentication scheme is “Basic”. This means the authentication request should only require an ID and password. For more detailed information and instructions on how to use this information, we recommend referring to the HTTP Authentication Scheme Registry.

    HTTP 401 errors, begone! 🧙‍♂️ 5 ways to stop those pesky messages (no magic required) ✨Click to Tweet

    Summary

    When your browser and server have trouble communicating or authenticating requests, you’re sometimes forced to deal with errors such as the 401 error. While this problem is irritating, the message is usually temporary and fixable.

    Here are five methods you can use to fix the 401 error:

    1. Look for errors in the URL.
    2. Clear your browser’s cache.
    3. Flush your DNS.
    4. Deactivate your WordPress plugins.
    5. Check the WWW-Authenticate header response.

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

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

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

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

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