Status code 401
Status code 401
How to Fix a 401 Unauthorized Error
Methods to fix a 401 Unauthorized error
The 401 Unauthorized error is an HTTP status code that means the page you were trying to access cannot be loaded until you first log in with a valid user ID and password.
If you’ve just logged in and received the 401 Unauthorized error, it means that the credentials you entered were invalid for some reason.
401 Unauthorized error messages are often customized by each website, especially very large ones, so keep in mind that this error may present itself in more ways than these common ones:
The 401 Unauthorized error displays inside the web browser window, just as web pages do. Like most errors like these, you can find them in all browsers that run on any operating system.
How to Fix the 401 Unauthorized Error
Check for errors in the URL. It’s possible that the 401 Unauthorized error appeared because the URL was typed incorrectly or the link that was selected points to the wrong URL—one that is for authorized users only.
If you’re sure the URL is valid, visit the website’s main page and look for a link that says Login or Secure Access. Enter your credentials here and then try the page again.
If you don’t have credentials or have forgotten yours, follow the instructions provided on the website for setting up an account or resetting your password.
Do you usually struggle to remember your passwords? Consider keeping them in a password manager so that you only have to remember one password.
Reload the page. As simple as it might seem, closing down the page and reopening it might be enough to fix the 401 error, but only if it’s caused by a misloaded page.
Delete your browser’s cache. There might be invalid login information stored locally in your browser that’s disrupting the login process and throwing the 401 error. Clearing the cache will remove any problems in those files and give the page an opportunity to download fresh files directly from the server.
If you’re sure the page you’re trying to reach shouldn’t need authorization, the 401 Unauthorized error message may be a mistake. At that point, it’s probably best to contact the website owner or other website contact and inform them of the problem.
The web site owner of some websites can be reached via email at webmaster@website.com, replacing website.com with the actual website name. Otherwise, find a Contact page for specific contact instructions.
Other Ways You Might See 401 Errors
Web servers running Microsoft IIS might give more information about the 401 Unauthorized error, such as the following:
Microsoft IIS 401 Error Codes | |
---|---|
Error | Explanation |
401.1 | Logon failed. |
401.2 | Logon failed due to server configuration. |
401.3 | Unauthorized due to ACL on resource. |
401.4 | Authorization failed by filter. |
401.5 | Authorization failed by ISAPI/CGI application. |
401.501 | Access Denied: Too many requests from the same client IP; Dynamic IP Restriction Concurrent request rate limit reached. |
401.502 | Forbidden: Too many requests from the same client IP; Dynamic IP Restriction Maximum request rate limit reached. |
401.503 | Access Denied: the IP address is included in the Deny list of IP Restriction |
401.504 | Access Denied: the host name is included in the Deny list of IP Restriction |
You can learn more about IIS-specific codes on Microsoft’s the HTTP status code in IIS 7 and later versions page.
Errors Like 401 Unauthorized
The following messages are also client-side errors and so are related to the 401 Unauthorized error: 400 Bad Request, 403 Forbidden, 404 Not Found, and 408 Request Timeout.
A number of server-side HTTP status codes also exist, like the often-seen 500 Internal Server Error.
Friendly HTTP 401 Status Code Message?
I’m a developer not a wordsmith and as such I’m stuck.
We have a subscription based site whereby users may well come across our 401 page.
We’ve decided that the IIS 401;2 page needs replacing.
Does anyone have any examples or advise about writing a good non offensive 401 page?
4 Answers 4
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
Through a series of highly sophisticated and complex algorithms, this system has determined that you are not presently authorized to use this system function. It could be that you simply mistyped a password, or, it could be that you are some sort of interplanetary alien-being that has no hands and, thus, cannot type. If I were a gambler, I would bet that a cat (an orange tabby named Sierra or Harley) somehow jumped onto your keyboard and forgot some of the more important pointers from those typing lessons you paid for. Based on the actual error encountered, I would guess that the feline in question simply forgot to place one or both paws on the appropriate home keys before starting. Then again, I suppose it could have been a keyboard error caused by some form of cosmic radiation; this would fit nicely with my interplanetary alien-being theory. If you think this might be the cause, perhaps you could create some sort of underground bunker to help shield yourself from it. I don’t know that it will work, but, you will probably feel better if you try something.
And don’t get me started on all the cool 404 pages out there.
How to Quickly Fix the 401 Unauthorized Error (5 Methods)
Trying to access a WordPress 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:
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:
Nginx 401 Authorization Required error message
Other variations include:
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.
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 (5 Methods)
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).
Sign Up For the Newsletter
Want to know how we increased our traffic over 1000%?
Join 20,000+ others who get our weekly newsletter with insider WordPress tips!
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:
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:
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:
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:
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.
Tired of subpar level 1 WordPress hosting support without the answers? Try our world-class support team! Check out our plans
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
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
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: 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:
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:
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.
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:
Save time, costs and maximize site performance with:
All of that and much more, in one plan with no long-term contracts, assisted migrations, and a 30-day-money-back-guarantee. Check out our plans or talk to sales to find the plan that’s right for you.
Error 401: Unauthorized – No access to the website
Anyone who searches the internet will encounter not only interesting content, but occasionally also error messages. For many, this can be frustrating: Not only can you not visit the requested page, but you also don’t know what the displayed status code actually means. The meaning of the 401 error is quickly clarified, though: You don’t have access rights to the requested page. The source of this error is usually found rather quickly. Here we explain how you can avoid the problem and how this error occurs.
Why wait? Grab your favorite domain name today!
What does status 401 mean?
When you surf the internet, communication takes place between the client (your web browser) and the web server. Using HTTP, the underlying internet protocol, the browser, and client exchange status codes with one another. A large part of these status messages isn’t seen when you’re surfing the net, since as long as everything is running smoothly they aren’t displayed.
The HTTP status codes are divided into groups: The first three groups are those that generally aren’t displayed to you in the browser. All codes in the 100s range describe ongoing requests. The codes 200 to 226 indicate that the browser’s request was successfully performed. The messages given in the 300s, though, refer to redirections. What is displayed to you from time to time, though, are the error messages: All status messages from the 500s range describe errors on the server side. The errors 400 to 499 note problems related to the client.
So with a 401 there is also an HTTP code that indicates an error in the client. In this sense, “client” can have very different meanings for the error message, since it just means the instance of communication with the webserver. This could be the browser, but could also be the router or even the internet provider used to make the connection. In many cases, however, the internet user has caused the error themselves.
Sometimes, instead of “401 Unauthorized” you could also get the message “401 Authorization Required.” Both basically mean that you don’t have permission for the requested website and must log in first. If the webserver runs with Microsoft IIS, even more specific status codes are often displayed:
In the best-case scenario, you land on a specially designed error page that describes directly what you have to do.
How can you correct the 401 error?
In most situations, you can correct the 401 error pretty easily: The affected internet page has a section that is only released following authorization. So to access the desired web page, you need to enter your log-in data in the corresponding area. If you don’t have an account on the website yet, you need to create one and register with it. You will most likely find hyperlinks for this on the start page or in a section of the header. The error page is then displayed if you try to skip such a login step and enter the link to the blocked page directly in your web browser.
This is why you can also get an error message if you follow an external link. If the page hidden behind the link is located in a password-protected area, then it’s highly likely that your browser will display a 401 error. Then, it’s best to either go directly to the home page or try to reach the next-highest level within the folder structure of the website. In the example example.com/folder1/folder2/folder3 you could try out example.com/folder1/folder2 next. Maybe the upstream file is already accessible to you.
In case you’ve generated the error by typing it in your browser, you should check the URL again: You may have swapped just one letter or one digit, and therefore entered the password-protected area.
But the error can even be encountered when you’ve already tried to login. Some websites display the 401 status code if you’ve simply entered the wrong login information. You may have mistyped your password, username, or e-mail address. Go back a page and enter your data once again.
To make mistakes is human: So it can definitely occur that you’ve forgotten your login data. In this case, you have to contact the website operator. This can tell you your username or reset your password. Many websites have an automatic application set up for this. It will send you a link via e-mail where you can create a new password.
If you regularly have trouble remembering your passwords, you should consider using a password manager. This allows you to keep track of even the most complex passwords.
Sometimes, it could be the case that you’ve done everything right: You logged in properly using the correct form, the data entered was correct, and yet you’re still greeted with a 401 error code. It’s probably an error with the server then, which the system has just interpreted as a 401 error. In such situations, which can also occur in the course of other error codes, two solutions have proven themselves as promising in the past:
If you were able to access the page in question in the past and there was no password protection, you can still access the content of the website despite the error by using a small detour. Google creates a cache for websites that internally saves a temporary copy of the site. In the Google search bar, simply enter cache:http://example.com/ and instead of “example.com” and enter the URL in question to access the saved version. This can also be a subpage. A header back informs you of when the copy is from. Remember that you won’t find any current information there, and instead only see the copy of a previous page version. If you want to go further back into the past of the website, you can access the archive of the Wayback Machine. There, you’ll find some decades-old versions of websites.
401 vs. 403: What’s the difference?
The two status codes have very different causes: While 401 means “Authorization Required,” the 403 status message usually contains the addition “Forbidden”: Access is not allowed. As we noted, with the 401 error the system is informing you that you have to log on to view the page. As such, there should be a login for you on a higher level. This is not provided with a 403 error. The website operator forbids access to this area of the website, and offers no possibility to register for it. These pages or directories are for internal use only and shouldn’t be accessed by external internet users.
401 Unauthorized vs 403 Forbidden: Which is the right status code for when the user has not logged in? [duplicate]
After lots of Googling and Stackoverflowing, it still isn’t clear to me because many articles and questions/answers were too general (including 403 Forbidden vs 401 Unauthorized HTTP responses which was not specifically for my use-case).
Question: What’s the proper HTTP Status Code when the user has not logged in and requests to see some pages that should be shown only to logged-in users?
3 Answers 3
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
The exact satisfying one-time-for-all answer I found is:
401 Unauthorized
While we know first is authentication (has the user logged-in or not?) and then we will go into authorization (does he have the needed privilege or not?), but here’s the key that makes us mistake:
But isn’t “401 Unauthorized” about authorization, not authentication?
Back when the HTTP spec (RFC 2616) was written, the two words may not have been as widely understood to be distinct. It’s clear from the description and other supporting texts that 401 is about authentication.
So maybe, if we want to rewrite the standards! focusing enough on each words, we may refer to the following table:
It depends on the mechanism you use to perform the login.
The spec for 403 Forbidden says:
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.
While 401 Unauthorized is not defined in the main HTTP status codes spec but is in the HTTP Authentication spec and says:
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.
So if you are using WWW-Authenticate and Authorization headers as your authentication mechanism, use 401. If you are using any other method, then use 403.
What is 401 Unauthorized Error? How to Fix it? (4 Easy Fixes)
Facing 401 Unauthorized Error?
Here’s the fix. But first, listen to this:
Тем не менее, эти неудобства выдерживают и продолжают беспокоить людей даже сегодня.
Но что именно эти коды ошибок появляются из ниоткуда и не объясняют, почему они появились в первую очередь?
Проще говоря, Интернет или Всемирная паутина функционируют на основе прикладного протокола, предназначенного для распределенных и совместных гипермедиа информационных систем, иначе называемых HTTP или протокол передачи гипертекста.
Другими словами, HTTP обеспечивает связь между клиентами и серверами, что позволяет беспрепятственно передавать данные между ними.
Типы ошибок 4xx
Ошибки или коды состояния, начинающиеся с цифры 4, часто относятся к ошибкам клиента. Другими словами, проблемы имеют отношение к клиентским запросам или напрямую связаны с клиентами.
Более того, эти ошибки могут указывать на временную или постоянную ситуацию. Вот несколько примеров 400 кодов ошибок.
Теперь, когда мы лучше понимаем эти надоедливые коды ошибок, пришло время сосредоточиться на 401 и как избавиться от него.
Исправление кода ошибки 401: точка зрения пользователя
Как упоминалось ранее, если вы сталкиваетесь с ошибкой 401, это обычно означает, что вы указали неверные учетные данные для входа, которые сервер не смог распознать.
Тем не менее, что происходит, когда вы фактически предоставляете правильные учетные данные для входа, но сервер по-прежнему предоставляет вам неавторизованное сообщение?
Это указывает на более глубокую проблему, чем простая опечатка. Это означает, что веб-сервер, возможно, не получил ваши учетные данные из-за проблемы с браузером, поэтому он решил немного больше с вами связываться.
Есть несколько способов решить эту проблему, и вот примеры каждого из них.
1. Проверьте URL
2. Проверьте свои учетные данные
3. Очистить историю просмотров и куки
4. Флеш DNS
Исправление ошибки 401: взгляд веб-мастера
Теперь, когда мы рассмотрели, что такое неавторизованная ошибка 401 и как ее исправить на стороне клиента, давайте посмотрим, что могут сделать веб-мастера, чтобы избавиться от этих ошибок.
Откат к предыдущей версии
Влияние ошибок на пользователей
Тем не менее, страница ошибки и сообщение могут быть сделаны интересными и даже интересными, чтобы минимизировать и смягчить разочарование пользователей.
Вот почему разработчики создают собственные страницы для сообщений об ошибках. Например, вы можете изменить метаописания для страниц с ошибками, чтобы предоставить пользователям контекст для этой ошибки, а также инструкции для возможных решений данной проблемы.
But where’s the fun in that? Indeed, a dull message describing a solution to the error may be off-putting, to say the least. That’s why developers oftentimes go a step further to ease the users’ pain.
В любом случае, даже неудобство может стать возможностью изменить ситуацию и превратить разочарование пользователей в не слишком большое разочарование.
Заключение
В конце концов, все сводится к тому, насколько вы креативны и как вы планируете подходить ко всем ошибкам. Ошибки будут существовать независимо от того, как сильно вы пытаетесь их избежать.
Само собой разумеется, что по крайней мере вы можете сделать все возможное, чтобы исправить их, прежде чем пользователи прибегнут к факелам и вилам.
Несанкционированная ошибка 401 встречается довольно часто и в основном является результатом неспособности пользователя терпеливо вводить свои учетные данные для входа. Тем не менее, эта ошибка может произойти и по другим причинам.
Вот почему важно понимать, как подойти к проблеме, а также понять, как правильно ее решить.
HTTP Status Code 401: What Is the 401 «Unauthorized» Error?
Status Code 401: «Unauthorized» Error
HTTP Status Code 401: «Unauthorized» Error
Usually, this means the user’s login credentials aren’t working. The user entered an incorrect password, or the server doesn’t know who the user is, and is asking them to try and log in again.
You’ll often see this error on membership sites or communities that require a username and password, or some other type of login or authentication. When this happens, giving the client a 401 response is totally fine.
The HTTP Protocol
Let’s talk about how the HTTP protocol works.
At its very foundation, the Internet is made up of two core things: clients and servers.
Any time you click on your browser, you are accessing the Internet through a web client. It may be Chrome, Firefox, Safari or Internet Explorer.
When you visit a website, you are making a request to a web server.
Facebook.com, ClickMinded.com, MarthaStewart.com/1525880/marthas-chocolate-chip-cookies, all of these sites have their own home address. It’s called an IP address.
Your home address might be 123 Main Street, New York, NY 10001, and Facebook’s address happens to be 66.220.144.0.
Whenever you visit a page on the web, you are requesting a whole bunch of documents from that website’s server. Maybe those documents are HTML, CSS, images, a PDF—whatever it is, the basic relationship stays the same: you (the client), make a request, and the website (the server) responds to that request.
The language you are using to make these requests is called the HTTP protocol. These protocols are really just standards that everyone on the web has agreed to. Just like English, Spanish and Chinese are all languages that have an understood protocol, HTTP is just a bunch of standards and an understood protocol.
There are a number of different web protocols out there – and you might be familiar with some of them:
HTTP Status Codes
Now that we understand what the HTTP protocol is, let’s talk about HTTP status codes. Status codes let us know whether the HTTP request was a success, a failure, or something in between.
Let’s take a look at the five core status codes:
Let’s briefly go over each status code block and what they mean.
1xx Status Codes
These are informational requests. The server hasn’t fully completed the request yet and it’s still processing the information. You will not see these codes often. They include:
2xx Status Codes
These are successful requests, which means everything is okay. They include:
3xx Status Codes
These are redirects. These are shown when you request an address, but you are sent somewhere else. These can be good or bad. They include:
4xx Status Codes
These are client errors. That means something went wrong with the request (client/user) and not the response (website/server). They include:
5xx Status Codes
These are server errors. That means something went wrong with the response (website/server) and not the request (client/user). They include:
In Conclusion
Looking for more on a particular status code? We have a series of short guides on every HTTP response, so you can optimize your digital marketing strategy. Grab them here:
401 Unauthorized vs 403 Forbidden: Which is the right status code for when the user has not logged in? [duplicate]
After lots of Googling and Stackoverflowing, it still isn’t clear to me because many articles and questions/answers were too general (including 403 Forbidden vs 401 Unauthorized HTTP responses which was not specifically for my use-case).
Question: What’s the proper HTTP Status Code when the user has not logged in and requests to see some pages that should be shown only to logged-in users?
3 Answers 3
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
The exact satisfying one-time-for-all answer I found is:
401 Unauthorized
While we know first is authentication (has the user logged-in or not?) and then we will go into authorization (does he have the needed privilege or not?), but here’s the key that makes us mistake:
But isn’t “401 Unauthorized” about authorization, not authentication?
Back when the HTTP spec (RFC 2616) was written, the two words may not have been as widely understood to be distinct. It’s clear from the description and other supporting texts that 401 is about authentication.
So maybe, if we want to rewrite the standards! focusing enough on each words, we may refer to the following table:
It depends on the mechanism you use to perform the login.
The spec for 403 Forbidden says:
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.
While 401 Unauthorized is not defined in the main HTTP status codes spec but is in the HTTP Authentication spec and says:
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.
So if you are using WWW-Authenticate and Authorization headers as your authentication mechanism, use 401. If you are using any other method, then use 403.
What causes «HTTP status 401: OK»
I have an ASP.NET Web Service, when I call it occasionally it returns the correct response, other times it is returning the exception The request failed with HTTP status 401: OK. Can someone please provide me with some reasons why this would be occurring? As I can’t seem to find anything on HTTP 401 and a message of OK since 200 is OK and 401 is Unauthorized. Why would my Web Service hosted in IIS6 be returning this?
Here’s the direct exception details:
I will be trying to get a WireShark packet trace for this error when I am provided with it.
Both the client and the Web Service are code that we maintain. The exception only occurs intermittently and not always, the credential details passed through are valid AD user details for an account and IIS site is using Windows Authentication.
3 Answers 3
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
I have found the cause and have an answer.
Due to the multi-threaded nature of the problem we had it occur very intermittently.
Solution was to write a new proxy class that encompass our auto-generated ws proxy class (from the WSDL) and implementing a SYNCLOCK object over every method within this new proxy class.
The problem also seemed to go away when I was using the server name rather than a DNS name because each separate thread call went on a different TCP pipe.
Similar to 403 Forbidden, but specifically for use when authentication is possible but has failed or not yet been provided.
This means you don’t not have permission for the resource you are trying to access, and that authenticating may make a difference. I don’t think the OK is relavent, though it is unusual. Check the actual Http Status code in Fiddler to be sure.
The request was a legal request, but the server is refusing to respond to it. Unlike a 401 Unauthorized response, authenticating will make no difference.
Is the service on a farm? It could be one server is not configured correctly.
Based on your last comment you should check there are no resource leaks causing the unexpected behaviour. If your using a database make sure you are disposing of disposable objects etc, profile the server to monitor memory use. Consider async services to keep the thread pool free if you have long running requests. Check event logs.
I think I may have seen similar behaviour when IIS can’t handle authenticated traffic, it just bombs out with a 401. I never noticed the OK, but could well occur in this scenario.
Разница между кодами ответов 403 и 401
В чём отличия между этими кодами ответов? Оба говорят об отсутствии прав доступа
4 ответа 4
Если запрос уже включал учетные данные авторизации, то ответ 401 указывает, что авторизация для этих учетных данных была отклонена.
Сервер понял запрос, но отказывается его выполнить.
Код ответа на статус ошибки «HTTP 403 Forbidden» указывает, что сервер понял запрос, но отказывается его авторизовать.
Этот статус похож на 401, но в этом случае повторная аутентификация не будет иметь никакого значения. Доступ запрещен и привязан к логике приложения (например, неверный пароль).
Так же, не запрещено ошибки програмно генерировать и светить не в том случае для которого они предназначены, но как правило эти две используются для перечисленных целей.
Всё ещё ищете ответ? Посмотрите другие вопросы с метками http или задайте свой вопрос.
Похожие
Подписаться на ленту
Для подписки на ленту скопируйте и вставьте эту ссылку в вашу программу для чтения RSS.
Нажимая «Принять все файлы cookie» вы соглашаетесь, что Stack Exchange может хранить файлы cookie на вашем устройстве и раскрывать информацию в соответствии с нашей Политикой в отношении файлов cookie.
What is 401 Unauthorized Error? How to Fix it? (4 Easy Fixes)
Facing 401 Unauthorized Error?
Here’s the fix. But first, listen to this:
Undoubtedly, you’ve come across an error or two while browsing your favorite websites online. These errors are a common nuisance that both webmasters and consumers don’t like to see.
Still, these inconveniences manage to endure and continue to bother people even today.
But what exactly are these error codes that keep popping up out of nowhere and without explaining why they’ve appeared in the first place?
Simply put, the Internet or the World Wide Web functions based on the application protocol designed for distributed and collaborative hypermedia information systems, otherwise known as HTTP or Hypertext Transfer Protocol.
In other words, HTTP enables communication between clients and servers thus allowing seamless transfer of data between the two.
However, when there’s a communication issue somewhere along the way, an error occurs marked as a response status code. The most common errors are the 4xx ones that represent an issue or a problem. With that in mind, let’s focus on the 401 unauthorized error and how to fix it.
Types of 4xx errors
Errors or status codes that start with the number 4 oftentimes refer to client errors. In other words, issues have something to do with client requests or are directly caused by the clients themselves.
What’s more, these errors may indicate if the situation is temporary or permanent. Here are a few examples of 400 error codes.
Now that we have a better understanding of these pesky error codes, it’s time to focus on the 401 one and how to get rid of it.
Fixing the 401 error code: The user perspective
As mentioned before, if you experience the 401 error, it usually means that you’ve provided incorrect login credentials that server couldn’t recognize.
However, what happens when you do, in fact, provide correct login credentials but the server still provides you with an unauthorized message?
This indicates a deeper issue than a simple typo. It means that the web server may not have received your credentials due to browser issue so it decides to mess with you a bit more.
There are a few ways you can try to fix this problem and here are examples of each of them.
1. Check the URL
2. Check your login credentials
3. Clear browsing history and cookies
4. Flush DNS
Fixing the 401 error: The webmaster perspective
Now that we covered what a 401 unauthorized error is and how to fix it from a client-side, let’s have a look at what webmasters can do to get rid of these errors.
Roll back to the previous version
The impact of errors on users
Errors are quite an inconvenience, to put it mildly. They can irritate users and have a major negative impact on their satisfaction and overall experience, even though the error occurred because users made a mistake.
However, an error page and message can be made interesting and even entertaining, in order to minimize and mitigate users’ frustration.
That’s why developers create custom pages for error messages. For instance, you can alter the meta descriptions for error pages to give users context behind the error, as well as instructions to possible solutions to the problem at hand.
But where’s the fun in that? Indeed, a dull message describing a solution to the error may be off-putting, to say the least. That’s why developers oftentimes go a step further to ease the users’ pain.
In any event, even an inconvenience can be an opportunity to turn things around and turn user frustration into not-so-much-frustration.
Conclusion
In the end, it comes down to how creative you are and how you plan to approach the entire error thing. Errors will continue to exist no matter how hard you try to avoid them.
It goes without saying that at least you can do is to do your best to fix them before users resort to torches and pitchforks.
The 401 unauthorized error is quite common and mostly a result of a user’s inability to patiently type in their login credentials. Still, this error can happen for other reasons as well.
That’s why it’s important to understand how to approach the problem, as well as understand how to properly solve it.
About
Similar to 403 Forbidden, but specifically for use when authentication is possible but has failed or not yet been provided. The response must include a WWW-Authenticate header field containing a challenge applicable to the requested resource.
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 field1 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 field2. 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.
Repeated status codes «401» and «200» when using MAPI over HTTP
Symptoms
Cause
MAPI over HTTP uses two client-server sessions, one for change notifications that is opened when Outlook starts, and one for sending/receiving data that is established on demand. The MAPI and HTTP sessions are on different layers. When the «send data» or «receive data» MAPI sessions are established, a new HTTP session is created, and authentication occurs at the beginning of the HTTP session.
The HTTP sessions authentication Request for Comment (RFC) describes the expected protocol sequence. This includes sending an empty authentication request so that the server responds by using the authentication protocols that it supports. This lets the client choose the appropriate authentication type. The repeated «401» and «200» status codes are expected as part of this process.
Workaround
You can disable the automatic proxy setting to reduce the number of HTTP «401» responses. To do this, change or add the following registry value:
Key: HKEY_CURRENT_USER\Software\Microsoft\Office\16.0\Common\Internet\
Value name: EnableHttpAccessTypeAutomaticProxy
Type: REG_DWORD
Value data: 0
After you set this registry value, proxy configuration is handled by Outlook instead of Microsoft Windows HTTP Services (WinHTTP). This enables Outlook to retain the server configuration and pre-authenticate future requests.
401 Unauthorized vs 403 Forbidden: Which is the right status code for when the user has not logged in? [duplicate]
After lots of Googling and Stackoverflowing, it still isn’t clear to me because many articles and questions/answers were too general (including 403 Forbidden vs 401 Unauthorized HTTP responses which was not specifically for my use-case).
Question: What’s the proper HTTP Status Code when the user has not logged in and requests to see some pages that should be shown only to logged-in users?
3 Answers 3
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
The exact satisfying one-time-for-all answer I found is:
401 Unauthorized
While we know first is authentication (has the user logged-in or not?) and then we will go into authorization (does he have the needed privilege or not?), but here’s the key that makes us mistake:
But isn’t “401 Unauthorized” about authorization, not authentication?
Back when the HTTP spec (RFC 2616) was written, the two words may not have been as widely understood to be distinct. It’s clear from the description and other supporting texts that 401 is about authentication.
So maybe, if we want to rewrite the standards! focusing enough on each words, we may refer to the following table:
It depends on the mechanism you use to perform the login.
The spec for 403 Forbidden says:
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.
While 401 Unauthorized is not defined in the main HTTP status codes spec but is in the HTTP Authentication spec and says:
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.
So if you are using WWW-Authenticate and Authorization headers as your authentication mechanism, use 401. If you are using any other method, then use 403.
HTTP 401 Error vs HTTP 403 Error – Status Code Responses Explained
We’ve covered the 403 (Forbidden) HTTP Error code in some detail before, but it also has a near identical sibling.
So what exactly is the difference between the 401 (Unauthorized) and 403 (Forbidden) status codes? Surely they mean the same thing? Let’s take a closer look!
RFC Standards
The most up to date RFC Standard defining 401 (Unauthorized) is RFC 7235
The 401 (Unauthorized) status code indicates that the request has not been applied because it lacks valid authentication credentials for the target resource. The user agent MAY repeat the request with a new or replaced Authorization header field.
Whereas 403 (Forbidden) is most recently defined in RFC 7231
The 403 (Forbidden) status code indicates that the server understood the request but refuses to authorize it. If authentication credentials were provided in the request, the server considers them insufficient to grant access.
Common Causes
As mentioned in the previous article, the 403 error can result when a user has logged in but they don’t have sufficient privileges to access the requested resource. For example, a generic user may be attempting to load an ‘admin’ route.
The most obvious time you’d encounter a 401 error, on the other hand, is when you have not logged in at all, or have provided the incorrect password.
These are the two most common causes for this pair of errors.
Less Common Causes
There are some instances where it’s not quite as straightforward as that, though.
403 errors can occur because of restrictions not entirely dependent on the logged in user’s credentials.
For example, a server may have locked down particular resources to only allow access from a predefined range of IP addresses, or may utilize geo-blocking. The latter can be potentially circumvented with a VPN.
401 errors can occur even if the user enters the correct credentials. This is rare, and might be something you only really encounter while developing your own authenticated back ends. But if the authorization header is malformed it will return a 401.
I have run in to this problem myself when testing APIs under development with Postman and forgetting the correct syntax for auth headers!
That’s it
I hope this clears up any confusion surrounding these very similar errors.
If you found this helpful, or wish to challenge or extend anything raised here, feel free to contact me on Twitter @JacksonBates.
Lead Software Engineer and consultant freelancer in Melbourne, Australia. Formerly a teacher. I work at gracepapers.com.au, helping parents juggle their family and work lives!
If you read this far, tweet to the author to show them you care. Tweet a thanks
Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started
freeCodeCamp is a donor-supported tax-exempt 501(c)(3) nonprofit organization (United States Federal Tax Identification Number: 82-0779546)
Donations to freeCodeCamp go toward our education initiatives, and help pay for servers, services, and staff.
Какой http-код использовать для неавторизованного пользователя, 401 или 403?
В чём разница в http-кодах 401 и 403?
1 ответ
Response c кодом 401 или 403 означает, что клиент не может просмотреть страницу, т.к. недостаточно прав для этого.
Переведём официальную документацию, чтобы понять, какой http-код лучше использовать (401 vs 403).
Код 401 Unauthorized
The request requires user authentication. The response MUST include a WWW-Authenticate header field (section 14.47) containing a challenge applicable to the requested resource. The client MAY repeat the request with a suitable Authorization header field (section 14.8). If the request already included Authorization credentials, then the 401 response indicates that authorization has been refused for those credentials. If the 401 response contains the same challenge as the prior response, and the user agent has already attempted authentication at least once, then the user SHOULD be presented the entity that was given in the response, since that entity might include relevant diagnostic information. HTTP access authentication is explained in «HTTP Authentication: Basic and Digest Access Authentication».
Для выполнения запроса пользователь должен быть авторизован. Ответ должен включать заголовок с полем «WWW-Authenticate», где через запятую должны быть перечислены параметры, необходимые для авторизации. При ответе с кодом 401 пользователь может повторить свой запрос. Клиент должен выполнить условия авторизации, после чего сделать повторный запрос.
Код 403 Forbidden.
The server understood the request, but is refusing to fulfill it. Authorization will not help and the request SHOULD NOT be repeated. If the request method was not HEAD and the server wishes to make public why the request has not been fulfilled, it SHOULD describe the reason for the refusal in the entity. If the server does not wish to make this information available to the client, the status code 404 (Not Found) can be used instead.
Сервер понял запрос, но не захотел его выполнять. Нет разрешения на запрос и запрос не должен быть повторён. Сервер должен объяснить клиенту, почему запрос не может быть выполнен (это касается всех методов, кроме HEAD). Если сервер не хочет описывать причину не выполнения запроса клиенту, то сервер должен возвращать http-статус 404 Not Found вместо 403 Forbidden.
Подведём итог, использовать 401 или 403?
Если клиент может получить доступ к странице (например, пройдя авторизацию), то нужно возвращать http-код 401. 401 нужно возвращать при отсутствующей или просроченной авторизации.
Если мы знаем, что доступ к странице для клиента закрыт, не может быть получен, то нужно возвращать http-код 403. Код 403 также следует возвращать, если клиент авторизован, но у него недостаточно прав для просмотра данной страницы.
Т.е. 403 код говорит «Извините, я знаю кто вы (вы авторизованы). Но, к сожалению, у вас нет прав для доступа к данному ресурсу. Возможно, вам нужно обратиться к администратору ресурса за получением разрешений.» Клиенту не имеет смысл повторять запрос.
HTTP authentication
HTTP provides a general framework for access control and authentication. This page is an introduction to the HTTP framework for authentication, and shows how to restrict access to your server using the HTTP «Basic» schema.
The general HTTP authentication framework
RFC 7235 defines the HTTP authentication framework, which can be used by a server to challenge a client request, and by a client to provide authentication information.
The challenge and response flow works like this:
The general message flow above is the same for most (if not all) authentication schemes. The actual information in the headers and the way it is encoded does change!
Warning: The «Basic» authentication scheme used in the diagram above sends the credentials encoded but not encrypted. This would be completely insecure unless the exchange was over a secure connection (HTTPS/TLS).
Proxy authentication
The same challenge and response mechanism can be used for proxy authentication. As both resource authentication and proxy authentication can coexist, a different set of headers and status codes is needed. In the case of proxies, the challenging status code is 407 (Proxy Authentication Required), the Proxy-Authenticate response header contains at least one challenge applicable to the proxy, and the Proxy-Authorization request header is used for providing the credentials to the proxy server.
Access forbidden
In all cases, the server may prefer returning a 404 Not Found status code, to hide the existence of the page to a user without adequate privileges or not correctly authenticated.
Authentication of cross-origin images
A potential security hole (that has since been fixed in browsers) was authentication of cross-site images. From Firefox 59 onwards, image resources loaded from different origins to the current document are no longer able to trigger HTTP authentication dialogs (bug 1423146), preventing user credentials being stolen if attackers were able to embed an arbitrary image into a third-party page.
Character encoding of HTTP authentication
Browsers use utf-8 encoding for usernames and passwords.
WWW-Authenticate and Proxy-Authenticate headers
The WWW-Authenticate and Proxy-Authenticate response headers define the authentication method that should be used to gain access to a resource. They must specify which authentication scheme is used, so that the client that wishes to authorize knows how to provide the credentials.
The syntax for these headers is the following:
Here, is the authentication scheme («Basic» is the most common scheme and introduced below). The realm is used to describe the protected area or to indicate the scope of protection. This could be a message like «Access to the staging site» or similar, so that the user knows to which space they are trying to get access to.
Authorization and Proxy-Authorization headers
The Authorization and Proxy-Authorization request headers contain the credentials to authenticate a user agent with a (proxy) server. Here, the is needed again followed by the credentials, which can be encoded or encrypted depending on which authentication scheme is used.
Authentication schemes
The general HTTP authentication framework is the base for a number of authentication schemes.
IANA maintains a list of authentication schemes, but there are other schemes offered by host services, such as Amazon AWS.
Some common authentication schemes include:
Basic
See RFC 7617, base64-encoded credentials. More information below.
Bearer
See RFC 6750, bearer tokens to access OAuth 2.0-protected resources
Digest
See RFC 7616. Firefox 93 and later support the SHA-256 algorithm. Previous versions only support MD5 hashing (not recommended).
HOBA
See RFC 7486, Section 3, HTTP Origin-Bound Authentication, digital-signature-based
Mutual
Negotiate / NTLM
VAPID
SCRAM
AWS4-HMAC-SHA256
See AWS docs. This scheme is used for AWS3 server authentication.
Schemes can differ in security strength and in their availability in client or server software.
The «Basic» authentication scheme offers very poor security, but is widely supported and easy to set up. It is introduced in more detail below.
Basic authentication scheme
The «Basic» HTTP authentication scheme is defined in RFC 7617, which transmits credentials as user ID/password pairs, encoded using base64.
Security of basic authentication
As the user ID and password are passed over the network as clear text (it is base64 encoded, but base64 is a reversible encoding), the basic authentication scheme is not secure. HTTPS/TLS should be used with basic authentication. Without these additional security enhancements, basic authentication should not be used to protect sensitive or valuable information.
Restricting access with Apache and basic authentication
Restricting access with Nginx and basic authentication
Access using credentials in the URL
Many clients also let you avoid the login prompt by using an encoded URL containing the username and the password like this:
401 Unauthorized vs 403 Forbidden: Which is the right status code for when the user has not logged in? [duplicate]
After lots of Googling and Stackoverflowing, it still isn’t clear to me because many articles and questions/answers were too general (including 403 Forbidden vs 401 Unauthorized HTTP responses which was not specifically for my use-case).
Question: What’s the proper HTTP Status Code when the user has not logged in and requests to see some pages that should be shown only to logged-in users?
3 Answers 3
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
The exact satisfying one-time-for-all answer I found is:
401 Unauthorized
While we know first is authentication (has the user logged-in or not?) and then we will go into authorization (does he have the needed privilege or not?), but here’s the key that makes us mistake:
But isn’t “401 Unauthorized” about authorization, not authentication?
Back when the HTTP spec (RFC 2616) was written, the two words may not have been as widely understood to be distinct. It’s clear from the description and other supporting texts that 401 is about authentication.
So maybe, if we want to rewrite the standards! focusing enough on each words, we may refer to the following table:
It depends on the mechanism you use to perform the login.
The spec for 403 Forbidden says:
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.
While 401 Unauthorized is not defined in the main HTTP status codes spec but is in the HTTP Authentication spec and says:
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.
So if you are using WWW-Authenticate and Authorization headers as your authentication mechanism, use 401. If you are using any other method, then use 403.
Коды ошибок REST API для партнеров
Ошибки в интерфейсах REST API партнеров возвращаются с использованием стандартных кодов состояния HTTP, а также объекта ответа JSON с ошибкой.
Коды состояния HTTP
В представленной ниже таблице перечислены и описаны коды состояния HTTP, которые могут быть возвращены этими интерфейсами.
Код состояния | Сообщение о состоянии | Описание |
---|---|---|
400 | Ошибка запроса | Не удалось обработать запрос, так как он представлен в неправильном формате или является некорректным. |
401 | Не авторизовано | Необходимые данные для проверки подлинности отсутствуют или не являются допустимыми для ресурса. |
403 | Запрещено | Отказано в доступе к запрашиваемому ресурсу. Возможно, у пользователя недостаточно разрешений. Внимание! Код состояния HTTP 403; Forbidden error=insufficent_claims может возвращаться, если к ресурсу применены политики условного доступа. Дополнительные сведения о Microsoft Graph и условном доступе см. в статье Руководство разработчика по условному доступу в Azure Active Directory. |
404 | Не найдено | Запрашиваемый ресурс не существует. |
405 | Метод не разрешен | Метод HTTP в запросе не разрешено использовать для ресурса. |
406 | Недопустимо | Эта служба не поддерживает формат, запрашиваемый в заголовке Accept. |
409 | Conflict | Текущее состояние конфликтует с ожиданиями запроса. Например, указанная родительская папка не существует. |
410 | Потеряно | The requested resource is no longer available at the server. |
411 | Требуется длина | В запросе необходимо указать заголовок Content-Length. |
412 | Необходимое условие не выполнено | Необходимое условие, указанное в запросе (например, заголовок if-match), не соответствует текущему состоянию ресурса. |
413 | Размер запрашиваемой сущности слишком большой | Размер запроса превышает ограничение. |
415 | Неподдерживаемый тип носителя | Тип контента запроса не поддерживается службой. |
416 | Запрошенный диапазон невыполним | Заданный диапазон байтов недопустим или недоступен. |
422 | Необрабатываемый объект | Не удалось обработать запрос, так как он является семантически некорректным. |
423 | Заблокировано | Запрашиваемый ресурс заблокирован. |
429 | Слишком много запросов | Клиентское приложение было отрегулировано, и ему не следует пытаться повторить запрос, пока не пройдет определенное время. |
500 | Внутренняя ошибка сервера | При обработке запроса возникла внутренняя ошибка сервера. |
501 | Не реализовано | Запрашиваемая функция не реализована. |
503 | Служба недоступна | Служба временно недоступна для обслуживания или перегружена. Вы можете повторить запрос по прошествии времени, которое можно указать в заголовке Retry-After. |
504 | Истекло время ожидания шлюза | Сервер, работающий в качестве прокси-сервера, при попытке выполнить запрос не получил своевременный ответ, необходимый для доступа, от сервера, находящегося выше в иерархии. Может возникать вместе с ошибкой 503. |
507 | Недостаточно места в хранилище | Достигнута максимальная квота хранилища. |
509 | Превышен предел пропускной способности | Приложение было отрегулировано из-за превышения максимальной пропускной способности. Приложение может повторить запрос по прошествии дополнительного времени. |
Ответ об ошибке — это отдельный объект JSON, содержащий одно свойство с именем error. Этот объект содержит все сведения об ошибке. Вы можете использовать возвращаемые в нем данные вместо кода состояния HTTP или вместе с ним. Ниже представлен пример полного текста ошибки JSON.
Тип ресурса ошибки
Ответ об ошибке — это отдельный объект JSON, содержащий одно свойство с именем error. Этот объект содержит все сведения об ошибке. Вы можете использовать возвращаемые в нем данные вместо кода состояния HTTP или вместе с ним. Ниже представлен пример полного текста ошибки JSON.
В приведенных ниже таблице и примере кода описывается схема ответа об ошибке.
Имя | Тип | Описание |
---|---|---|
code | строка | Всегда возвращается. Указывает тип возникшей ошибки. Не принимает значение null. |
message | строка | Всегда возвращается. Содержит подробное описание ошибки и дополнительные сведения для отладки. Не принимает значение null, не может быть пустым. Максимальная длина: 1024 символа. |
innerError | объект | Необязательный элемент. Дополнительный объект ошибки, который может быть более подробным, чем ошибка верхнего уровня. |
target | строка | Целевой объект, в котором возникла ошибка. |
Свойство Code
Свойство code содержит одно из перечисленных ниже возможных значений. Приложения должны быть готовы к обработке любой из этих ошибок.
Код | Описание |
---|---|
accessDenied | У вызывающей стороны нет разрешения на выполнение действия. |
generalException | Возникла неопределенная ошибка. |
InvalidRequest | Запрос представлен в неправильном формате или является некорректным. |
itemNotFound | Ресурс не найден. |
preconditionFailed | Необходимое условие, указанное в запросе (например, заголовок if-match), не соответствует текущему состоянию ресурса. |
resourceModified | Обновляемый ресурс изменился с момента последнего считывания. Как правило, это связано с несовпадением eTag. |
serviceNotAvailable | Служба недоступна. Повторите попытку через некоторое время. Возможно, задан заголовок Retry-After. |
unauthenticated | Вызывающий объект не прошел проверку подлинности. |
Свойство Message
Объект InnerError
Объект innererror может рекурсивно содержать другие объекты innererror с дополнительными, более конкретными кодами ошибок. При обработке ошибки приложения должны циклически просматривать все доступные коды ошибок и использовать наиболее подробный из них, который понятен приложению.
Ошибка сервера 401: что это за ошибка и как ее исправить
Вы здесь
Главная Отзыв на госсайт: Федеральная налоговая службане могу войти в личный кабинет. вчера регистрировался, а сейчас при вводе пароля на странице <«status»:0,»error»:»Maintenance. Sorry…»>Дата публикации: 01 марта 2020 г., 00:08Тип отзыва: ПроблемаМодерация: Системный Администратор 01.03.2020 — 08:50 Ответил куратор: Иванова Любовь ЕвгеньевнаДата ответа: 03 марта 2020, 09:56 г. Текущий статус: Обработан
Уважаемый пользователь сайта!
При наличии вопросов по работе интернет-сервисов Вы можете обращаться в службу технической поддержки через сервис «Техническая поддержка сервисов», размещенный в разделе «Все сервисы» (https://www.nalog.ru/rn77/service/service_feedback/). Обращениям присваиваются регистрационные номера, своевременность их исполнения тщательно контролируется. В случае необходимости специалисты службы технической поддержки связываются с налогоплательщиком для мониторинга текущей ситуации и оперативного исправления выявленных сбоев.
Данный виджет разработан с целью предоставления возможности налогоплательщикам оценить работу сайта.
Оказал ли куратор необходимую помощь?
Ваше мнение очень важно при доработке и совершенствовании АИС «Мониторинг Госсайтов»
Большое количество налогоплательщиков сталкивается с ошибкой «Проверка защищенного соединения с сервером личного кабинета индивидуального предпринимателя». В этом случае пользователи не могут попасть в личный кабинет и воспользоваться его функциями. Рассмотрим, что делать в этой ситуации далее в статье.
Антивирус – причина ошибки «Проверка защищенного соединения»
Ошибка возникает при посещении сайтов для оплаты налогов, а также при регистрации на них. С этим вопросом пользователи часто обращаются в техническую поддержку сервиса. В первую очередь в поддержке советуют отключить на время антивирусное программное обеспечение. Это можно сделать на панели быстрого доступа внизу экрана Windows. При установке антивируса в браузер, который используется по умолчанию, добавляется специальное расширение. Оно служит для блокирования подозрительных сайтов, а также тех сайтов, которые занесены в базу данных антивируса.
Расширение отключается достаточно просто, необходимо зайти в настройки браузера, найти пункт с расширением и напротив установить статус «Выключено». После этого попытаться снова зайти на сайт, где возникала ошибка «Проверка защищенного соединения личного кабинета ИП». Сайт, на который вы пытаетесь зайти, должен быть внесен в надежные узлы браузера. Это тоже можно сделать в настройках. Если ошибка возникает при попытке зайти в ЛК на nalog.ru, необходимо:
Для тех, кто использует антивирус ESET, необходимо сделать еще кое-что:
При проверке декларации может возникать ошибки 0000000002 и 0400300003.
Настроить браузер для устранения ошибки «Проверки защищенного соединения»
Чтобы устранить ошибку «Проверка защищённого соединения с сервером личного кабинета юридического лица», необходимо произвести некоторые настройки браузера и операционной системы.
Можно воспользоваться браузером Safari вместо IE. Также, можно использоваться более новую версию КриптоПро 4.0. Скачать ее нужно только с официального сайта. Демо-версией вы сможете пользоваться 3 месяца без ввода лицензионного ключа.
Другие методы устранения дисфункции
Нередко, ошибка возникает не только при соединении с сервером личного кабинета индивидуального предпринимателя, но и с сервером личного кабинета юридического лица. Причиной ошибки «Проверка защищенного соединения» могут являться настройки КриптоПро. Здесь нужно зайти на вкладку «Настройки TLS» и убрать флажок с чек-поинта «Не использовать устаревшие cipher suite».
После этого нужно перезагрузить компьютер. Можно попытаться установить вручную сертификат, для этого:
Следования вышеописанным рекомендациям в большинстве случаев помогут решить ошибку «Проверка защищенного соединения с личным кабинетом на сайте».
Иллюстрация: Ирина Григорьева / Клерк.ру
Заполнение в личном кабинете на сайте налоговой заявления о возврате излишне уплаченного НДФЛ, как налогового агента, ведет к неправильному заполнению. Оказывается, нужно ножками идти в инспекцию.
Поделились в «Красном уголке бухгалтера».
«Отхватил адреналинчику, занесло неправедными путями в налоговую. Основной вопрос был в возврате дважды уплаченного, как налоговый агент НДФЛ. Честно, больше месяца прождал денежек или какой-либо бумажки от налоговиков, вот и дополз до них с распечатанным из ЛК ИП заявлением на возврат и квитанцией о приеме заявления. Все тихо, спокойно, народу практически нет, температуру больше не измеряют, в зал пускают только когда номер талона высветиться и не более 20 человек одновременно. Заявление на возврат заполнял в ЛК ИП, все ставится автоматом: статус плательщика — 4 (налоговый агент), 1 — излишне уплаченный, 1 — налог, номер счета для возврата 4 — налогового агента, получатель — 2 физическое лицо (исходя из 1 — организация (ответственный участник консолидируемой группы налогоплательщиков) и 3 — орган, осуществляющий открытие и ведение лицевых счетов, программа автоматом приравнивает ИП к физлицам. Что здесь неправильно программа заполнила, что они заявление разнесли как заявление на возврат личного НДФЛ физлица (типа по 3-ндфл)? Не видят они в своем заявлении статуса налогового агента, говорят программа в ЛК ИП заполняет неправильно и нужно на бумажке им подавать с другим статусом, которого они не нашли в заявлении из ЛК (то ли 2 то ли 13, запутался). И отказ на возврат, говорят инспектор выгрузил, вот только его нет ни в ЛК ИП, ни в ЛК ФЛ и из ФНС РФ прилетело только сообщение об отправки квитанции, об исполнении ничего не было».
Зачем вообще нужны сервисы, если они заполняют неправильно и все равно нужно идти в инспекцию на прием?
Вот что пишут в комментариях:
«Вечно у них со статусом 2 проблема, подайте на бумаге».
«Есть подозрение что действительно может лучше не с ЛК делать заявления, а просто им письмом. И у юрлиц в ЛК чудеса бывают, а с физиками тем более».
«Так заполнение от этого не изменится, статусы такие же поставлю в заявлении. Кто им мешает снова на физика все отнести? Про 13-й статус в заявлении вообще ничего нет. Не пойму, где по их мнению ошибка в заявлении».
«Ну сделайте им и 2 и 13 в конце концов, пусть выбирают. Но с 2 завернули ведь, нужно тогда пробовать дальше. А что делать?».
«Так куда его сунуть, этот 13? Нет в форме такого статуса. Юридические лица и ИП могут указываться в заявлении коды 01 и 02. Физлицам лучше указать код 02 при возврате налогов. У меня код 2 стоит, в остальных местах налоговый агент указан».
В общем, стоит писать в техподдержку. А если все заполнено правильно, по их мнению, писать жалобу в Управление. Чего автор и хочет сделать.
Записаться 8645 12350 ₽ –30%
Подборка полезных мероприятий
03 авг в 2020 18K
Попробуем разобраться с наиболее распространенными причинами возникновения данной ошибки кода HTTP-соединения и обсудим способы их решения.
Причины появления ошибки сервера 401 и способы ее устранения на стороне пользователя
При доступе к некоторым сайтам (или отдельным страницам этих сайтов), посетитель должен пройти определенные этапы получения прав:
Большинство пользователей сохраняют свои данные по умолчанию в истории браузеров, что позволяет быстро идентифицироваться на наиболее часто посещаемых страницах и синхронизировать настройки между устройствами. Данный способ удобен для серфинга в интернете, но может привести к проблемам с безопасностью доступа к конфиденциальной информации. При наличии большого количества авторизованных регистрационных данных к различным сайтам используйте надежный мастер-пароль, который закрывает доступ к сохраненной в браузере информации.
Наиболее распространенной причиной появления ошибки с кодом 401 для рядового пользователя является ввод неверных данных при посещении определенного ресурса. В этом и других случаях нужно попробовать сделать следующее:
Некоторые крупные интернет-ресурсы с большим количеством подписчиков используют дополнительные настройки для обеспечения безопасности доступа. К примеру, ваш аккаунт может быть заблокирован при многократных попытках неудачной авторизации. Слишком частые попытки законнектиться могут быть восприняты как действия бота. В этом случае вы увидите соответствующее сообщение, но можете быть просто переадресованы на страницу с кодом 401. Свяжитесь с администратором сайта и решите проблему.
Иногда простая перезагрузка проблемной страницы, выход из текущей сессии или использование другого веб-браузера полностью решают проблему с 401 ошибкой авторизации.
Устранение ошибки 401 администратором веб-ресурса
Для владельцев сайтов, столкнувшихся с появлением ошибки отказа доступа 401, решить ее порою намного сложнее, чем обычному посетителю ресурса. Есть несколько рекомендаций, которые помогут в этом:
Где в поле /oldpage.html прописывается адрес проблемной страницы, а в http://site.com/newpage.html адрес страницы авторизации.
Таким образом вы перенаправите пользователей со всех страниц, которые выдают ошибку 401, на страницу начальной авторизации.
Хотя ошибка 401 и является проблемой на стороне клиента, ошибка пользователя на стороне сервера может привести к ложному требованию входа в систему. К примеру, сетевой администратор разрешит аутентификацию входа в систему всем пользователям, даже если это не требуется. В таком случае сообщение о несанкционированном доступе будет отображаться для всех, кто посещает сайт. Баг устраняется внесением соответствующих изменений в настройки.
Дополнительная информация об ошибке с кодом 401
Веб-серверы под управлением Microsoft IIS могут предоставить дополнительные данные об ошибке 401 Unauthorized в виде второго ряда цифр:
Более подробную информацию об ошибке сервера 401 при использовании обычной проверки подлинности для подключения к веб-узлу, который размещен в службе MS IIS, смотрите здесь.
Следующие сообщения также являются ошибками на стороне клиента и относятся к 401 ошибке:
Как видим, появление ошибки авторизации 401 Unauthorized не является критичным для рядового посетителя сайта и чаще всего устраняется самыми простыми способами. В более сложной ситуации оказываются администраторы и владельцы интернет-ресурсов, но и они в 100% случаев разберутся с данным багом путем изменения настроек или корректировки html-кода с привлечением разработчика сайта.
Александр Григорьев +49 Используемые источники:
Correct HTTP status code for login form?
I am implementing the authentication for an app, and I am using a pluggable system with «authentication methods». This allows me to implement both HTTP Basic as well as HTML-based authentication.
With HTTP Basic/Digest auth the server sends a 401 Unauthorized response header. However, according to the HTTP/1.1 RFC:
The response MUST include a WWW-Authenticate header field (section 14.47) containing a challenge applicable to the requested resource.
Since I do not know of any «html» WWW-Authenticate header, sending a 401 with an HTML login form seems inappropriate. Is there any alternative to this? I want to design my app in a RESTful way.
What is the correct HTTP Status code (and headers) for an HTML-based login form? And what is the correct code when the login fails?
Note: I am not interested in Digest Authentication.
4 Answers 4
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
For HTML I think you should respond with a 400.
This may be true for non-HTML requests as well, since 401 is as far as I understand it more designed to respond to a request to content that requires authentication, not to respond to an authentication request.
HTML does not always allow for pure use of RESTful APIs, so it’s ok to cut corners here and there imo, but maybe there is a better way I’m not seeing in this particular case.
When requesting the login form which is a public page, you get what you want, so it’s a 200 status code :
When requesting for a page that needs a http level authentication that you didn’t initiated (basic http, ssl certificate, etc.), the application must tell the browser itself that it needs to initiate this authentication for you :
When the authentication is a cookie-based session, you already have a cookie (if it’s not the case, you will get one with the set-cookie header when requesting the page) but this cookie doesn’t tell that you are allowed to access the /secured uri. So if you try to access this uri, you should get a «403 forbidden» status. Then the «log in» action is no more than just changing the state of the application with a POST request to make the application grant access for this cookie, so.
Log in with bad credentials:
Log in with good credentials but not enough permissions :
Log in with good credentials and enough permissions :
This is a tricky question, largely because the most well-established HTTP clients used by people are browsers. According to the RFC, the WWW-Authenticate header can contain anything. Basic and digest authentication are just two examples of further standardised challenge/response mechanisms. You can simply specify a challenge like html-form > and return the 401 along with an HTML form. Also, recall from the spec that multiple challenges can be specified within the same WWW-Authenticate header, but I don’t have any experience testing browsers extensively with different schemes.
@2016-02-17 Updated
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.
If you want to handle if no permission right, you may need 403 Forbidden [RFC7231]
HTTP 422 is used for WebDAV, but the meaning might fit the needs. (Not suggested for most cases)
For more information, please see the comment of Cássio Mazzochi Molin below.
@2016-02-12 **Updated** *(This is the reference to the accepted answer.)*
HTTP 422 is used for WebDAV, but the meaning might fit the needs. HTTP 401 is for authorization. And is not suitable for authentication.
HTTP 422 is now better choice other than 400 / 401. HTTP 422 is an alternative choice.
How to deal with 401 Unauthorized response i Jmeter V3.0 or lower?
I am trying to login the-internet.herokuapp.com/basic_auth using admin:admin as credentials.
I am using Jmeter v3.0 and I added HTTP Authorization manager, Cookie manager and also added the name and value in header manager as shown in the image, but I am still getting 401 unauthorized response.
I tried the same thing in a different system with Jmeter v3.1 and its working.
Does anyone know how to resolve issue with Jmeter v3.0 or lower?
1 Answer 1
I cannot reproduce your problem using JMeter 3.0 and only having HTTP Authorization Manager added apart from the HTTP Request:
Here is a full Test Plan just in case:
I would recommend removing your Authorization header from the HTTP Header Manager just in case.
See How to Use HTTP Basic Authentication in JMeter article for more details on bypassing basic access authentication in JMeter tests.
It is hightly recommended to use the latest JMeter versions where possible as newer versions normally come with bug fixes, performance improvements and brand new features so consider upgrading to JMeter 3.2 (or whatever is the latest version available at the JMeter Downloads page)
HTTP Status Codes With Explanations
Amir Ghahrai
HTTP Status Codes or Response Codes are grouped into five categories. 1×× Informational, 2×× Success, 3×× Redirection, 4×× Client Error, 5×× Server Error.
This post contains the full list of HTTP status codes with a short description of the most common response codes.
When we do API testing, usually the first thing that we check on the response from an API call is the status code. It is essential that we are familiar with at least the most common status codes so we can identify issues quicker.
1×× Informational
The 1xx (Informational) class of status code indicates an interim response for communicating connection status or request progress prior to completing the requested action and sending a final response.
2×× Success
The 2xx (Successful) class of status code indicates that the client’s request was successfully received, understood, and accepted.
200 OK
The 200 (OK) status code indicates that the request has succeeded. The payload sent in a 200 response depends on the request method.
201 Created
The 201 (Created) status code indicates that the request has been fulfilled and has resulted in one or more new resources being created.
204 No Content
The 204 (No Content) status code indicates that the server has successfully fulfilled the request and that there is no additional content to send in the response payload body.
3×× Redirection
The 3xx (Redirection) class of status code indicates that further action needs to be taken by the user agent in order to fulfill the request.
301 Moved Permanently
The 301 (Moved Permanently) status code indicates that the target resource has been assigned a new permanent URI and any future references to this resource ought to use one of the enclosed URIs.
302 Found
The 302 (Found) status code indicates that the target resource resides temporarily under a different URI.
4×× Client Error
The 4xx (Client Error) class of status code indicates that the client seems to have erred.
400 Bad Request
The 400 (Bad Request) status code indicates that the server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax).
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.
403 Forbidden
The 403 (Forbidden) status code indicates that the server understood the request but refuses to authorize it.
404 Not Found
The 404 (Not Found) status code indicates that the origin server did not find a current representation for the target resource or is not willing to disclose that one exists.
405 Method Not Allowed
The 405 (Method Not Allowed) status code indicates that the method received in the request-line is known by the origin server but not supported by the target resource.
415 Unsupported Media Type
The 415 (Unsupported Media Type) status code indicates that the origin server is refusing to service the request because the payload is in a format not supported by this method on the target resource. The format problem might be due to the request’s indicated Content-Type or Content-Encoding, or as a result of inspecting the data directly.
5×× Server Error
The 5xx (Server Error) class of status code indicates that the server is aware that it has erred or is incapable of performing the requested method.
500 Internal Server Error
The 500 (Internal Server Error) status code indicates that the server encountered an unexpected condition that prevented it from fulfilling the request.
502 Bad Gateway
The 502 (Bad Gateway) status code indicates that the server while acting as a gateway or proxy, received an invalid response from an inbound server it accessed while attempting to fulfill the request.
503 Service Unavailable
The 503 (Service Unavailable) status code indicates that the server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay.
504 Gateway Timeout
The 504 (Gateway Timeout) status code indicates that the server while acting as a gateway or proxy, did not receive a timely response from an upstream server it needed to access in order to complete the request.
How to check for an HTTP status code of 401?
Part of Google Cloud Collective
In one of the answers that I have received here, I encountered a problem of not knowing how to pass automatically through «Google App Engines» my ID and a password to a website, on which I am a registered user and have an account. A suggestion was given to me to «check for an HTTP status code of 401, «authorization required», and provide the kind of HTTP authorization (basic, digest, whatever) that the site is asking for». I don’t know how to check for status code. Can anyone, please, tell me how to do it?
If I use this way in Google App Engine (fetching the url of my eBay summary page):
I always get «200» instead of «401»
4 Answers 4
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
In ordinary Python code, I’d probably use the lower-level httplib, e.g.:
this will show you such codes as 301 (moved permanently) and 302 (moved temporarily); higher level libraries such as urllib2 would handle such things «behind the scenes» for you, which is handy but makes it harder for you to take control with simplicity (you’d have to install your own «url opener» objects, etc).
In App Engine, you’re probably better off using urlfetch, which returns a response object with a status_code attribute. If that attribute is 401, it means that you need to repeat the fetch with the appropriate kind of authorization information in the headers.
However, App Engine now also supports urllib2, so if you’re comfortable with using this higher level of abstraction you could delegate the work to it. See here for a tutorial on how to delegate basic authentication to urllib2, and here for a more general tutorial on how basic authentication works (I believe that understanding what’s going on at the lower layer of abstraction helps you even if you’re using the higher layer!-).
Несанкционированные ошибки (401) при назимении API
Ссылаясь на статью о серии устранения неполадок управления API Azure,это третий сценарий лаборатории. Убедитесь, что вы следовали инструкциям по настройке лаборатории в соответствии с этим, чтобы воссоздать проблему.
Оригинальная версия продукта: Служба управления API
Исходный номер КБ: 4464930
Симптомы
API Echo внезапно начал метать различные типы HTTP 401 — несанкционированные ошибки при наводении операций под ней. Создание ресурсов и извлечение ресурсов показывают это сообщение об ошибке:
<
«statusCode»: 401,
«сообщение»: «Доступ отказано в связи с недействительным ключом подписки. Убедитесь, что для активной подписки необходимо предоставить допустимый ключ».
>
В то время как остальные операции отображаются
<
«statusCode»: 401,
«сообщение»: «Доступ отказано в связи с отсутствием ключа подписки. Обязательно включаем ключ подписки при внесении запросов в API».
>
Ожидаемый код ответа HTTP для всех операций — 200, однако тело отклика будет отличаться, так как API-ответ всегда повторяет все, что вы отправляете в качестве тела запроса в дополнение к заголовщикам.
Действия по устранению неполадок
Чтобы получить доступ к API, разработчики должны сначала подписаться на продукт. Когда они подписываются, они получают ключ подписки, который отправляется в качестве части заголовки запросов, которая хороша для любого API в этом продукте. Ocp-Apim-Subscription-Key — это заголовка запросов, отправленная для ключа подписки продукта, связанного с этим API. Клавиша заполняется автоматически.
Что касается доступа к ошибке, отказано из-за недействительных ключа подписки. Убедитесь, что вы предоставляете допустимый ключ для активной подписки, ясно, что вы отправляете неправильное значение загона запроса Ocp-Apim-Subscription-Key во время запроса На создание ресурсов и извлечение операций ресурсов.
Вы можете проверить ключ подписки для определенного продукта с портала разработчика APIM, переехав на страницу Profile после регистрации, как показано ниже.
Выберите кнопку Показать, чтобы увидеть ключи подписки для соответствующих продуктов, на которые вы подписаны.
Если вы проверяете отправимые с вкладки Test загонщики, вы заметите, что значение заглавного запроса Ocp-Apim-Subscription-Key неверно. Возможно, вам будет интересно, как это возможно, так как AIM автоматически заполняет этот заглавный элемент запроса нужным ключом подписки.
Давайте проверим определение Frontend в статье Создание ресурсов и извлечение операций ресурсов в вкладке Design. При тщательном осмотре вы заметите, что эти операции получили неправильное кодовое значение заглавного заглавного запроса Ocp-Apim-Subscription-Key, добавленного в вкладке Headers.
Вы можете удалить его, это должно решить проблему ключа недействительной подписки, но все равно вы получите недостающую ошибку ключа подписки.
Вы можете получить следующее сообщение об ошибке:
Длина контента: 152
Content-Type: application/json
Date: Sun, 29 Jul 2018 14:29:50 GMT
Vary: Origin WWW-Authenticate: AzureApiManagementKey realm=» https://pratyay.azure-api.net/echo «,name=»Ocp-Apim-Subscription-Key», type=»header» <
«statusCode»: 401,
«сообщение»: «Доступ отказано в связи с отсутствием ключа подписки. Обязательно включаем ключ подписки при внесении запросов в API». >
Перейдите к APiettings Echo и проверьте, связан ли он с любым из доступных продуктов. Если нет, необходимо связать этот API с продуктом, чтобы получить ключ подписки.
Сначала разработчики должны подписаться на продукт, чтобы получить доступ к API. Когда они подписываются, они получают ключ подписки, который хорошо для любого API в этом продукте. Если вы создали экземпляр AIM, вы уже администратор, поэтому вы подписаны на каждый продукт по умолчанию.
Server returned HTTP response code: 401 for URL: https
I’m using Java to access a HTTPS site which returns the display in an XML format. I pass the login credentials in the URL itself. Here is the code snippet:
I’m creating a trust manager in the program which does not validate signed/unsigned certificates. But, on running the above program, I get the error Server returned HTTP response code: 401 for URL: https://Administrator:Password@localhost:8443/abcd
I can use the same url on my browser and it displays the xml correctly. Kindly let me know how to make this work within the Java program.
2 Answers 2
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
401 means «Unauthorized», so there must be something with your credentials.
I think that java URL does not support the syntax you are showing. You could use an Authenticator instead.
and then simply invoking the regular url, without the credentials.
The other option is to provide the credentials in a Header:
PS: It is not recommended to use that Base64Encoder but this is only to show a quick solution. If you want to keep that solution, look for a library that does. There are plenty.
customerrors for 401.2 in ASP.NET
I successfully implemented role based authorization in ASP.NET. When a person does not have the needed role he gets to see an error page for 401.2 not authorized.
What I would like to accomplish now is to have a custom 401 page in my application and have it redirected there via settings in the web.config. I tried this:
But this does not get caught. Do I have to override it in IIS instead? I hope not as that would make getting things deployed harder.
4 Answers 4
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
I ran into the same problem recently and it turns out that this is one of the quirks when using Windows Authentication.
Joshua Flanagan created a nice HttpModule a while ago that will respect the customErrors section in your web.config and redirect to the 401 error page.
The key to the solution is to intercept the EndRequest event of the page lifecycle, check for a 401 status code, and then execute your custom page.
Hands off that resource, HTTP status code 401 vs 403 vs 404
By Arnaud Lauret, May 5, 2021
Choosing HTTP status codes Series
When designing APIs, choosing HTTP status codes is not always that obvious and prone to errors, I hope this post series will help you to avoid common mistakes and choose an adapted one according to the context.
The context
But what happens if some curious and maybe malicious user scan network traffic coming out of the application? This hacker will easily understand how this “not so private” API works. With very little effort, they will succeed to generate phone numbers that actually exist in the underlying system so send GET /users/
In either case, the API should prevent accessing resources that don’t belong to the caller and signify there’s a problem with caller’s request. Note that if that sounds like a no-brainer for many people, that is actually not always the case and some APIs may return a 200 OK along with the requested data. Regularly, stories such as this one (which inspired the above use case) come out. Never forget that when creating APIs and never refrain from double check that your colleagues are also aware of that. And note also that using PII (Personnally Identifiable Information) or other sensitive data as ids can be very convenient but raises security concerns, especially if they appear in URLs as they can be logged almost everywhere. I should write a post series about API security one day ( POST /writing-ideas done!).
Use 404 when resource is none of consumer’s business (and never will)
The 404 (Not Found) status code indicates that the origin server did not find a current representation for the target resource or is not willing to disclose that one exists.
Returning a 404 Not Found means “the requested resource does not exists”. Actually, there’s a subtlety, it could mean “the requested resource actually exists but it’s none of your business, you’re not allowed to access it and never will; actually, it does not exist for you” or “the requested resource does not exist at all” but the consumer will never know what is the true reason behind this HTTP status code.
That response is the best one for the introduction’s use case, granted that users want to use this application without sharing anything with others. In that case, given that John and Emma use the application, if Emma “hacks” the API, we will never ever want her to know that /users/
But if 404 Not Found is usually my first idea when a consumer tries to access to a /resources/1234 they shouldn’t (I admit I’m a little obsess with security and prone to not show what is not needed to be shown), there are cases where it could be interesting to let them know the target resource exists.
Use 403 when consumer can do something about it
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).
Returning a 403 Forbidden signifies “the requested resource actually MAY exists but you cannot access it. You MAY access it by requesting adequate rights to someone, maybe an administrator for instance”.
Never ever use 401 (don’t be fooled by its reason)
The 401 (Unauthorized) status code indicates that the request has not been applied because it lacks valid authentication credentials for the target resource.
There are only two hard things in Computer Science: cache invalidation and naming things.
A 401 signifies there’s a problem with your credentials which usually are provided in an Authorization header (still wrong name, but at least it’s consistent with the reason). This status is made to signify “you forgot to provide an Authorization header with some credentials” or “your credentials provided in the Authorization header are invalid/expired”. In the API world, it basically says “You can’t use the API at all, come back with a valid access token”.
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.
To be even more sure that 403 Forbidden is the right answer, let’s talk about Oauth 2 scopes. Indeed, dealing with resource rights access is not always, let’s say “internal business rule” driven (checking in users table that the identified user has the requested phone number for example). When consumers request an access token using the Oauth 2 framework (the token that goes into the not so well named Authorization header), they may request a token restricted to given elements thanks to scopes. For instance, when using the Github API, you may request access to public repo only or to user data only. What should happen when a consumer requests access to a resource without adapted scopes? Section 3.1 of RFC 6750 The OAuth 2.0 Authorization Framework: Bearer Token Usage is quite clear:
The request requires higher privileges than provided by the access token. The resource server SHOULD respond with the HTTP 403 (Forbidden) status code and MAY include the «scope» attribute with the scope necessary to access the protected resource.
HTTP Status code is not enough
That means two things. First 401 Unauthorized is definitely not an option in the case we are studying today. Second, HTTP status code is not enough. Indeed, 403 Forbidden could be returned because consumer lacks some scope to GET /resources/
Don’t forget DX and context
Respecting HTTP and other RFCs is important to avoid surprising developers with behaviors that are against common practices, but most important, whatever the HTTP status code you’ll choose to return, what matters above all is providing the response the most adapted for the context that will actually help the developer (and the consumer and even the end user) to know what is actually happening and help them solve the problem if they can.
Непредвиденное состояние 401.1 возвращается при использовании заголовков предварительной проверки подлинности с Internet Explorer и IIS.
В этой статье устранена проблема, из-за которой возвращается непредвиденное состояние 401.1 с заголовками предварительной проверки подлинности. Это происходит при использовании Internet Explorer для браузера в веб-приложении, размещенном в службы IIS (IIS).
Исходная версия продукта: Режим IE для Edge, службы IIS, Internet Explorer 11, 10, 9
Исходный номер базы знаний: 2749007
Симптомы
Рассмотрим следующий сценарий.
В этом сценарии службы IIS могут возвращать ответ http (HTTP) 401.1 в Internet Explorer в ответ на запрос браузера. Веб-браузер может предложить ввести имя пользователя и пароль. Кроме того, в окне браузера может отображаться сообщение об ошибке HTTP 401.1.
Причина
Такое поведение является особенностью данного продукта. Ответ 401.1 будет получен, если первый запрос веб-браузера, отправляемый в приложение IIS, содержит один из следующих заголовков:
Обходной путь
Чтобы обойти это поведение, отключите предварительную проверку подлинности в Internet Explorer или отключите проверку подлинности в режиме ядра для веб-приложения IIS.
При неправильном использовании редактора реестра могут возникнуть серьезные проблемы, которые могут потребовать переустановки операционной системы. Корпорация Майкрософт не может гарантировать, что вы сможете решить проблемы, возникающие в результате неправильного использования редактора реестра. Используйте редактор реестра на свой риск.
Чтобы изменить это поведение в Internet Explorer, используйте редактор реестра ( Regedt32.exe ), чтобы добавить значение в следующий раздел реестра:
HKEY_CURRENT_USER/Software/Microsoft/Windows/CurrentVersion/Internet Settings/
Указанный выше раздел реестра является одним путем. он был заключен в оболочку для удобочитаемости.
Добавьте следующее значение реестра:
Чтобы изменить это поведение в IIS, отключите проверку подлинности в режиме ядра для веб-приложения IIS.
Откройте службы IIS (IIS), выполнив следующую команду из командной строки администратора:
В области « Подключения» разверните имя сервера, разверните узел, а затем сайт, приложение или веб-службу, для которых требуется отключить проверку подлинности в режиме ядра.
Прокрутите страницу до раздела «Безопасность» на панели « Главная» и дважды щелкните » Проверка подлинности».
В области проверки подлинности выберите Windows проверку подлинности.
На панели «Параметры действий» выберите «Дополнительные параметры».
Когда появится диалоговое Параметры Advanced Параметры, снимите флажок «Включить проверку подлинности в режиме ядра«.
Нажмите кнопку « ОК», чтобы закрыть диалоговое Параметры advanced Параметры.
Отключение проверки подлинности в режиме ядра может привести к сбою веб-приложений, для которых требуется проверка подлинности и делегирование Kerberos.
Дополнительные сведения
Чтобы определить, вызван ли запрос проблемой, описанной в этой статье, используйте средство Fiddler. С помощью этого средства можно просмотреть трафик HTTP-запросов и ответов для запроса, что приводит к появлению запроса в Internet Explorer. Кроме того, вам потребуются журналы IIS с сервера IIS для подтверждения состояния HTTP и кодов вложенного состояния. В следующем примере для иллюстрации этого поведения используется Internet Explorer 9:
Запустите средство Fiddler и включите запись трафика.
Перейдите к веб-приложению IIS, чтобы оно привело к появлению запроса учетных данных.
В Fiddler найдите запрос, который привело к 401. Просмотрев необработанные представления запросов и ответов, вы увидите записи, аналогичные следующим:
Исходный запрос к веб-приложению уже содержит Authorization заголовок, что приводит к ответу 401. В соответствующем журнале IIS должна отображаться запись, аналогичная следующей:
Состояние HTTP и вложенное состояние — 401.1, что сопоставляется с состоянием «Отказано в доступе » из-за недопустимых учетных данных.
Дополнительные сведения см. в следующей документации:
HTTP аутентификация
HTTP предоставляет набор инструментов для котнроля доступа к ресурсам и аутентификации. Самой распространённой схемой HTTP аутентификации является «Базовая» (Basic) аутентификация. Данное руководство описывает основные возможности HTTP аутентификации и показывает способы ограничения доступа к вашему серверу с её использованием.
Общий механизм HTTP аутентификации
В случае базовой авторизации как на иллюстрации выше, обмен должен вестись через HTTPS (TLS) соединение, чтобы обеспечить защищённость.
Прокси-аутентификация
Этот же механизм запроса и ответа может быть использован для прокси-аутентификации. В таком случае ответ посылает промежуточный прокси-сервер, который требует авторизации. Поскольку обе формы аутентификации могут сосуществовать, для них используются разные заголовки и коды статуса ответа. В случае с прокси, статус-код запроса 407 (Proxy Authentication Required) и заголовок Proxy-Authenticate (en-US), который содержит хотя бы один запрос, относящийся к прокси, а для передачи учётных данных прокси-серверу используется заголовок Proxy-Authorization (en-US).
Доступ запрещён
Аутентификация cross-origin изображений
Аутентификация с помощью изображений, загружаемых из разных источников, была до недавнего времени потенциальной дырой в безопасности. Начиная с Firefox 59, изображения, загружаемые из разных источников в текущий документ, больше не запускают диалог HTTP-аутентификации баг 1423146, предотвращая тем самым кражу пользовательских данных (если нарушители смогли встроить это изображение в страницу).
Кодировка символов HTTP аутентификации
заголовки WWW-Aутентификации и Прокси-Аутентификации
WWW-Authenticate (en-US) и Proxy-Authenticate (en-US) заголовки ответа которые определяют методы, что следует использовать для получения доступа к ресурсу. Они должны указывать, какую схему аутентификации использовать, чтобы клиент, желающий авторизоваться, знал, какие данные предоставить. Синтаксис для этих заголовков следующий:
заголовки Авторизации и Прокси-Авторизации
Заголовки запросов Authorization и Proxy-Authorization (en-US) содержат учётные данные для аутентификации агента пользователя (User Agent) на (прокси) сервере. Здесь снова требуется за которым следуют учётные данные, которые могут быть закодированы или зашифрованы в зависимости от того, какая схема аутентификации используется.
Схемы Аутентификации
Общая структура HTTP аутентификации является основной для ряда схем аутентификации. Schemes can differ in security strength and in their availability in client or server software.
IANA поддерживат список схем аутентификации, однако существуют и другие схемы предлагаемые хост-сервисами, например, Amazon AWS.
Некоторые распространенные схемы аутентификации включают:
AWS4-HMAC-SHA256 (смотреть AWS документацию).
Схемы могут различаться по степени безопасности и по их доступности в клиентском или серверном программном обеспечении.
«Базовая» (Basic) схема аутентификации обеспечивает очень низкую безопасность, но широко поддерживается и проста в настройке. Более подробно она представлена ниже.
Базовая (Basic) схема аутентификации
«Базовая» схема HTTP-аутентификации определена в RFC 7617, которая передаёт учётные данные в виде пар пользователь ID/пароль (user ID/password), закодированных с использованием base64.
Безопасность базовой аутентификации
Ограничение доступа с помощью Apache и базовой аутентификации
Ограничение доступа с помощью nginx и базовой аутентификации
Доступ используя учётные данные в URL-адресе
Многие клиенты также позволяют избежать запроса на вход в систему, используя закодированный URL, содержащий имя пользователя и пароль, как показано ниже:
Как исправить ошибку HTTP 401 неавторизованного запроса?
Вся сеть работает на основе протокола связи между браузером и веб-сервером. Когда что-то пойдет не так, вы можете увидеть в браузере различные типы кодов ошибок HTTP. Ошибка HTTP или код состояния 4xx указывает на то, что браузер отправил на сервер неправильную информацию. Веб-серверы вернут код 401, если они не могут обработать запрос из-за неправильной аутентификации.
Связанный: Исправить ошибку HTTP 400 неверного запроса.
Как исправить ошибку HTTP 401 неавторизованного запроса?
Эта проблема чаще встречается на веб-сайтах, которые предлагают вход в систему и специальный контент по подписке. Хотя в большинстве случаев причиной является неправильный вход в систему, в некоторых случаях может произойти ошибка 401 Несанкционированный запрос, даже если у вас есть действительные учетные данные для входа. В этом случае веб-сервер мог не получить ваши данные для входа из-за проблемы на стороне браузера и вернуть ошибку 401.
Если вы видите ошибку 401, выполните следующие действия, чтобы устранить ошибку. Большинство решений довольно легко исправить. Мы также отдельно сгруппировали возможные исправления для обычных пользователей и владельцев веб-сайтов. Вы можете опробовать подходящий случай.
Для обычных пользователей
1. Проверьте URL
Это наиболее частая причина ошибки 401 неавторизованный запрос. Это могло произойти, когда вы вводите URL вручную. В противном случае вы можете щелкнуть устаревший URL-адрес, отмеченный закладкой в вашем браузере. Ошибка может появиться, если страница больше не существует. Итак, проверьте URL-адрес и убедитесь, что нет орфографических ошибок и веб-страница все еще доступна.
Связанный: Исправить ошибку HTTP 404, не найденную.
2. Очистить DNS
В некоторых случаях ошибки DNS также могут вызывать ошибку 401 неавторизованный запрос. Вы можете исправить ошибку, очистив DNS.
Следуйте инструкциям в Windows:
Если вы используете macOS, очистка DNS немного отличается.
3. Очистить файлы cookie браузера.
Файлы cookie — это фрагменты информации, которые используются веб-сайтами для запоминания вашей уникальной личной информации. Во многих случаях файлы cookie также хранят информацию об аутентификации пользователя и напоминают веб-серверу об уровне авторизации, который может быть предоставлен пользователю. К сожалению, это не всегда работает гладко, и может произойти неправильная аутентификация сервера. Ошибка 401 может произойти, если веб-сервер не может распознать токен сеанса, отправленный вашим веб-браузером. Когда сервер считает, что ваш токен недействителен, вы можете получить ошибку 401 Unauthorized Request.
Гораздо проще удалить все файлы cookie полностью или только для определенных веб-сайтов. Когда вы очищаете файлы cookie, вам придется повторно ввести данные для входа в электронную почту, социальные сети и другие веб-сайты, требующие входа в систему. После очистки кеша попробуйте войти на веб-сайт и проверьте, можете ли вы получить полный доступ на этот раз без проблем.
4. Проверьте свои права доступа.
Ошибка 401 может произойти из-за неправильного входа в систему или разрешения. Например, ссылка может быть зарезервирована только для участников, и при нажатии на нее вы получите ошибку 401 неавторизованный запрос. В этом случае вам может потребоваться связаться с владельцем сайта для получения надлежащего доступа.
В других случаях вы могли вводить неверные учетные данные для входа на веб-сайт. Если вы знаете, что учетные данные верны, очистите файлы cookie и очистите DNS, как описано в предыдущих разделах. Теперь попробуйте еще раз войти на сайт.
Если вы действительно забыли пароль, найдите на сайте ссылку для сброса пароля. Обычно веб-сайт запрашивает адрес электронной почты, который вы использовали для создания учетной записи в прошлом. В некоторых случаях по ошибке включается неправильное требование аутентификации, и веб-сайт становится недоступным для пользователей, которые вошли в систему. Эту проблему может решить только администратор веб-сайта.
5. Выйдите из системы и войдите снова.
Большинству веб-сайтов требуются регулярные простои для обслуживания. Также есть вероятность, что владелец веб-сайта может вносить некоторые изменения в серверную часть, вызывая временные проблемы. Если вы столкнулись с проблемами со статусом входа в систему, выйдите из системы и войдите снова. Во многих случаях веб-сайт может снова работать нормально.
Владельцам веб-сайтов
6. Откат к предыдущей версии CMS
Большинство систем управления контентом обновляются довольно регулярно. Иногда при незначительном обновлении случайно появляются новые ошибки, в том числе необъяснимое появление ошибки 401 Unauthorized Request. Если ваши пользователи сообщают об этой проблеме после недавнего обновления CMS, вам следует рассмотреть возможность отката к предыдущей версии.
К сожалению, некоторые CMS не позволяют выполнить откат. В таком случае вам может потребоваться официальная поддержка поставщика услуг.
7. Удалите ваши изменения.
Некоторые системы управления контентом, такие как WordPress, предлагают плагины, темы, модули, виджеты и расширения. Вы можете использовать эти функции для добавления новых функций и изменения внешнего вида очень универсально. К сожалению, некоторые плагины, темы, модули, виджеты и расширения находятся в плохом состоянии. Некоторые расширения также могут привести к внесению большего количества изменений, чем необходимо.
Когда вы видите ошибку 401 после любого обновления, первое, что вы можете сделать, это удалить последний обновленный плагин и проверить результат. Следует отметить, что проблема может быть решена не сразу после удаления или перехода на более раннюю версию плагина. Это могло произойти, если плагин изменил данные в серверной базе данных или файлах PHP. Таким образом, после удаления плагина любые изменения в базе данных или файлах PHP не могут быть отменены. В таком случае вам может потребоваться вернуть содержимое к ранее работающей версии из резервной копии.
Вывод
Во многих случаях ошибка 401 Unauthorized Request возникает, когда вы пытаетесь войти в систему с неправильными учетными данными. Некоторые веб-сайты, такие как банковские сайты, могут заблокировать вашу учетную запись, если вы несколько раз попытаетесь ввести неправильный пароль. Поэтому убедитесь, что вы указали правильные данные для входа, иначе обратитесь в службу поддержки веб-сайта, чтобы решить вашу проблему. С другой стороны, если вы являетесь владельцем веб-сайта, попробуйте вернуться к своим предыдущим действиям, чтобы восстановить доступ к сайту.
Axios login request: Unauthorized, request status code 401
I’m trying to get an authorization token by making a request to an api using axios:
I’m getting always status code 401(Unauthorized):
Where I’m doing wrong?
The fact is that making the same request using python works fine:
1 Answer 1
By sending username and password in auth: <> in axios, you are doing the basic-authentication, basically sending Authorization: basic header.
As per working python program, you need to send the username and password as part of the request body. You need to serialize the body params for url-encoded content type as well.
Not the answer you’re looking for? Browse other questions tagged node.js authentication axios http-status-code-401 or ask your own question.
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
Friendly HTTP 401 Status Code Message?
I’m a developer not a wordsmith and as such I’m stuck.
We have a subscription based site whereby users may well come across our 401 page.
We’ve decided that the IIS 401;2 page needs replacing.
Does anyone have any examples or advise about writing a good non offensive 401 page?
4 Answers 4
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
Through a series of highly sophisticated and complex algorithms, this system has determined that you are not presently authorized to use this system function. It could be that you simply mistyped a password, or, it could be that you are some sort of interplanetary alien-being that has no hands and, thus, cannot type. If I were a gambler, I would bet that a cat (an orange tabby named Sierra or Harley) somehow jumped onto your keyboard and forgot some of the more important pointers from those typing lessons you paid for. Based on the actual error encountered, I would guess that the feline in question simply forgot to place one or both paws on the appropriate home keys before starting. Then again, I suppose it could have been a keyboard error caused by some form of cosmic radiation; this would fit nicely with my interplanetary alien-being theory. If you think this might be the cause, perhaps you could create some sort of underground bunker to help shield yourself from it. I don’t know that it will work, but, you will probably feel better if you try something.
And don’t get me started on all the cool 404 pages out there.
The request failed with HTTP status 401: Unauthorized
The request failed with HTTP status 401: Unauthorized.
How do I get around this?
5 Answers 5
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
You need to set the credentials in you application when you initialise the webService object.
Something like webService.UseDefaultCredentials = true
This will set the credentials of the request to the current user executing the application.
you can use this:
if does not work, use the below code instead of the code above
note: the username Password and domain is the user credential of the user that access to webservice
so make sure that user have permission to access to web service
maybe the user is the windows user
and you can get the domain from: right click in «MyComputer» and properties the domain is the Computer name or Workgroup
«HTTP 401» error message when you try to access web resources that require Kerberos authentication on a computer that is running Windows 7 or Windows Server 2008 R2
Symptoms
Consider the following scenario:
You have a computer that is running Windows 7 or Windows Server 2008 R2.
You configure the FEATURE_USE_CNAME_FOR_SPN_KB911149 registry subkey according to the description in the following Microsoft Knowledge Base article:
You try to access a webpage or a web application that requires Kerberos authentication by using the alias (CNAME) resource record. A service principal name (SPN) is configured for the CNAME that is related to the web resource.
In this scenario, you cannot access these web resources, and you receive an error message that resembles the following:
HTTP 401
Kerberos authentication failed: gss_accept_sec_context failed: Unspecified GSS failure. Minor code may provide more information, Wrong principal in request
Cause
This issue occurs because the SPN for the web resources is only registered with the CNAME.
A Windows 7-based or Windows Server 2008 R2-based client computer requests a Kerberos ticket for the fully qualified domain name (FQDN) of the web resources. This means that the client computer requests the host (A) resource record that corresponds to the CNAME for Kerberos authentication. If the SPN is only registered with the CNAME, access to the web resources fails.
Resolution
Hotfix information
A supported hotfix is available from Microsoft. However, this hotfix is intended to correct only the problem that is described in this article. Apply this hotfix only to systems that are experiencing the problem described in this article. This hotfix might receive additional testing. Therefore, if you are not severely affected by this problem, we recommend that you wait for the next software update that contains this hotfix.
If the hotfix is available for download, there is a «Hotfix download available» section at the top of this Knowledge Base article. If this section does not appear, contact Microsoft Customer Service and Support to obtain the hotfix.
Note If additional issues occur or if any troubleshooting is required, you might have to create a separate service request. The usual support costs will apply to additional support questions and issues that do not qualify for this specific hotfix. For a complete list of Microsoft Customer Service and Support telephone numbers or to create a separate service request, visit the following Microsoft Web site:
http://support.microsoft.com/contactus/?ws=supportNote The «Hotfix download available» form displays the languages for which the hotfix is available. If you do not see your language, it is because a hotfix is not available for that language.
Prerequisites
There are no prerequisites to apply this hotfix.
Registry information
To use the hotfix in this package, you do not have to make any changes to the registry.
Restart requirement
You may have to restart the computer after you apply this hotfix.
Hotfix replacement information
This hotfix does not replace a previously released hotfix.
File information
The global version of this hotfix installs files that have the attributes that are listed in the following tables. The dates and the times for these files are listed in Coordinated Universal Time (UTC). The dates and the times for these files on your local computer are displayed in your local time together with your current daylight saving time (DST) bias. Additionally, the dates and the times may change when you perform certain operations on the files.
Windows 7 and Windows Server 2008 R2 file information notes
Important Windows 7 hotfixes and Windows Server 2008 R2 hotfixes are included in the same packages. However, hotfixes on the Hotfix Request page are listed under both operating systems. To request the hotfix package that applies to one or both operating systems, select the hotfix that is listed under «Windows 7/Windows Server 2008 R2» on the page. Always refer to the «Applies To» section in articles to determine the actual operating system that each hotfix applies to.
The MANIFEST files (.manifest) that are installed for each environment are listed separately in the «Additional file information for Windows Server 2008 R2 and for Windows 7» section. MANIFEST files and the associated security catalog (.cat) files, are extremely important to maintain the state of the updated components. The security catalog files, for which the attributes are not listed, are signed with a Microsoft digital signature.
Список кодов состояния HTTP
Клиент узнаёт по коду ответа о результатах его запроса и определяет, какие действия ему предпринимать дальше. Набор кодов состояния является стандартом, и они описаны в соответствующих документах RFC. Введение новых кодов должно производиться только после согласования с IETF. Тем не менее, известно о двух используемых кодах, не упомянутых в RFC: 449 Retry With [прим 1] (введён Microsoft) и 509 Bandwidth Limit Exceeded (введён в cPanel).
Клиент может не знать все коды состояния, но он обязан отреагировать в соответствии с классом кода. В настоящее время выделено пять классов кодов состояния.
Веб-сервер Microsoft Internet Information Services в своих файлах журналов кроме стандартных кодов состояния использует подкоды записывая их через точку после основного. При этом в ответах от сервера данный субкод не размещается — он нужен администратору сервера чтобы тот мог более точно определять источники проблем. Со списком подкодов IIS можно ознакомиться в документе «Коды состояния служб IIS» в Базе знаний Microsoft.
Обзорный список
Ниже представлен обзорный список всех описанных в данной статье кодов ответа:
1xx: Informational (Информационные)
В этот класс выделены коды, информирующие о процессе передачи. В HTTP/1.0 сообщения с такими кодами должны игнорироваться. В HTTP/1.1 клиент должен быть готов принять этот класс сообщений как обычный ответ, но ничего серверу отправлять не нужно. Сами сообщения от сервера содержат только стартовую строку ответа и, если требуется, несколько специфичных для ответа полей заголовка. Прокси-сервера подобные сообщения должны отправлять дальше от сервера к клиенту.
100 Continue (Продолжать)
Появился в HTTP/1.1.
Сервер удовлетворён начальными сведениями о запросе. Клиент может продолжать пересылать заголовки.
101 Switching Protocols (Переключение протоколов)
Появился в HTTP/1.1.
Сервер предлагает перейти на более подходящий для указанного ресурса протокол. Список предлагаемых протоколов сервер обязательно указывает в поле заголовка Update. Если клиента это заинтересует, то он посылает новый запрос с указанием другого протокола.
102 Processing (Идёт обработка)
Запрос принят, но на его обработку понадобится длительное время. Используется сервером, чтобы клиент не разорвал соединение из-за превышения времени ожидания. Клиент при получении такого ответа должен сбросить таймер и дожидаться следующей команды в обычном режиме.
2xx: Success (Успешно)
Сообщения данного класса информируют о случаях успешного принятия и обработки запроса клиента. В зависимости от статуса сервер может ещё передать заголовки и тело сообщения.
200 OK (Хорошо)
Появился в HTTP/1.0.
Успешный запрос ресурса. Если клиентом были запрошены какие-либо данные, то они находятся в заголовке и/или теле сообщения.
201 Created (Создано)
Появился в HTTP/1.0.
В результате успешного выполнения запроса был создан новый ресурс. Сервер должен указать его местоположение в заголовке Location. Серверу рекомендуется ещё указывать в заголовке характеристики созданного ресурса (например, в поле Content-Type). Если сервер не уверен, что ресурс действительно будет существовать к моменту получения данного сообщения клиентом, то лучше использовать ответ 202.
202 Accepted (Принято)
Появился в HTTP/1.0.
Запрос был принят на обработку, но обработка не завершена. Клиенту не обязательно дожидаться окончательной передачи сообщения, так как может быть начат очень долгий процесс.
203 Non-Authoritative Information (Неавторитетная информация)
Появился в HTTP/1.1.
Аналогично ответу 200, но в этом случае передаваемая информация была взята не из первичного источника (резервной копии, другого сервера и т. д.) и поэтому может быть неактуальной.
204 No Content (Нет содержимого)
Появился в HTTP/1.0.
Сервер успешно обработал запрос, но в ответе были переданы только заголовки без тела сообщения. Клиент не должен обновлять содержимое документа, но может применить к нему полученные метаданные.
205 Reset Content (Сбросить содержимое)
Появился в HTTP/1.1.
Сервер обязывает клиента сбросить введённые пользователем данные. Тела сообщения сервер при этом не передаёт и документ обновлять не обязательно.
206 Partial Content (Частичное содержимое)
Появился в HTTP/1.1.
Сервер удачно выполнил частичный GET возвратив только часть. В заголовке Content-Range сервер указывает байтовые диапазоны содержимого. Особое внимание при работе с подобными ответами следует уделить кэшированию.
207 Multi-Status (Многостатусный)
Сервер передаёт результаты выполнения сразу нескольких независимых операций. Они помещаются в само тело сообщения в виде XML-документа с объектом multistatus. Не рекомендуется размещать в этом объекте статусы из серии 1xx из-за бессмысленности и избыточности.
226 IM Used (IM использовано)
Введено в RFC 3229 для дополнения протокола HTTP поддержкой дельта-кодирования.
Заголовок A-IM от клиента был успешно принят и сервер возвращает содержимое с учётом указанных параметров.
3xx: Redirection (Перенаправление)
Коды класса 3xx сообщают клиенту что для успешного выполнения операции необходимо сделать другой запрос (как правило по другому URI). Из данного класса пять кодов 301, 302, 303, 305 и 307 относятся непосредственно к перенаправлениям (жарг. редирект). Адрес, по которому клиенту следует произвести запрос, сервер указывает в заголовке Location. При этом допускается использование фрагментов в целевом URI.
Поведение клиентов при различных перенаправлениях описано в таблице:
Статус ответа | Кэширование | Если метод не GET или HEAD |
---|---|---|
301 Moved Permanently | Можно как обычно. | Спросить у пользователя подтверждения и запросить другой ресурс исходным методом. |
307 Temporary Redirect | Можно только если указан заголовок Cache-Control или Expires. | |
302 Found | ||
303 See Other | Никогда нельзя. | Перейти автоматически, но уже методом GET. |
См. так же пример перенаправлений в статье по HTTP.
300 Multiple Choices (Множество выборов)
Появился в HTTP/1.0.
По указанному URI существует несколько вариантов предоставления ресурса по типу MIME, по языку или по другим характеристикам. Сервер передаёт с сообщением список альтернатив, давая возможность сделать выбор клиенту (автоматически) или пользователю.
301 Moved Permanently (Перемещено окончательно)
Появился в HTTP/1.0.
Запрошенный документ был окончательно перенесен на новый URI, указанный в поле Location заголовка. Учтите что некоторые клиенты некорректно ведут себя при обработке данного кода (см. описание ко всему классу 3xx).
302 Found (Найдено)
Введено в HTTP/1.0.
Запрошенный документ временно доступен по другому URI, указанному в заголовке в поле Location. Этот код может быть использован, например, при управляемом сервером согласовании содержимого. Учтите что некоторые клиенты некорректно ведут себя при обработке данного кода (см. описание ко всему классу 3xx).
303 See Other (Смотреть другое)
Введено в HTTP/1.1.
Документ по запрошенному URI нужно запросить по адресу в поле Location заголовка с использованием метода GET несмотря даже на то, что первый запрашивался иным методом. Этот код был введён вместе с 307-ым для избежания неоднозначности, чтобы сервер был уверен, что следующий ресурс будет запрошен методом GET (см. описание ко всему классу 3xx).
304 Not Modified (Не изменялось)
Появился в HTTP/1.0.
Сервер возвращает такой код, если клиент запросил документ методом GET, использовал заголовок If-Modified-Since или If-None-Match и документ не изменился с указанного момента. При этом сообщение сервера не должно содержать тела.
305 Use Proxy (Использовать прокси)
Введено в HTTP/1.1.
Запрос к запрашиваемому ресурсу должен осуществляться через прокси-сервер, URI которого указан в поле Location заголовка. Данный код ответа могут использовать только исходные HTTP-сервера (не прокси).
306 (зарезервировано)
Упомянуто в RFC 2616 (обновление HTTP/1.1).
Использовалось раньше, в настоящий момент зарезервировано.
307 Temporary Redirect (Временное перенаправление)
Введено в RFC 2616 (обновление HTTP/1.1).
Запрашиваемый ресурс короткое время доступен по другому URI (указывается в поле Location заголовка). Этот код был введён вместе с 303 вместо 302-ого для избежания неоднозначности (см. описание ко всему классу 3xx).
4xx: Client Error (Ошибка клиента)
Класс кодов 4xx предназначен для указания ошибок со стороны клиента. При использовании всех методов, кроме HEAD, сервер должен вернуть в теле сообщения гипертекстовое пояснение для пользователя.
400 Bad Request (Плохой запрос)
Появился в HTTP/1.0.
Запрос не понят сервером из-за наличия синтаксической ошибки. Клиенту следует повторно обратиться к ресурсу с изменённым запросом.
401 Unauthorized (Не авторизован)
Появился в HTTP/1.0.
Запрос требует идентификации пользователя. Сервер должен запросить имя и пароль у пользователя, а тот передаст их в заголовке WWW-Authenticate в следующем запросе. Если были указаны неверные данные, то сервер снова вернёт этот же статус.
402 Payment Required (Необходима оплата)
Зарезервирован начиная с HTTP/1.1.
Предполагается использовать в будущем. В настоящий момент не используется.
Обратите внимание что этот код предусмотрен для платных пользовательских сервисов, а не для хостинговых компаний. Если не оплачена услуга хостинга сайта, то логичней возвращать клиенту ответ из класса 5xx. Например, как cPanel возвращает ответ 509 (Bandwidth Limit Exceeded) когда площадкой превышен лимит на потребление трафика.
403 Forbidden (Запрещено)
Появился в HTTP/1.0.
Сервер понял запрос, но он отказывается его выполнять из-за ограничений в доступе со стороны клиента к указанному ресурсу.
Если для доступа к ресурсу требуется аутентификация средствами HTTP, то сервер вернёт ответ 401 (или 407 для прокси). В противном случае ограничения были заданы администратором сервера или разработчиком веб-приложения и могут быть любыми в зависимости от возможностей используемого ПО.
В любом случае клиенту следует сообщить причины отказа в обработке запроса.
Наиболее вероятными причинами ограничения могут послужить:
404 Not Found (Не найдено)
Появился в HTTP/1.0.
Сервер понял запрос, но не нашёл соответствующего ресурса по указанному URI. Если серверу известно, что по этому адресу был документ, то ему желательно использовать код 410. Ответ 404 может использоваться вместо 403, если требуется тщательно скрыть от посторонних глаз определённые ресурсы.
405 Method Not Allowed (Метод не применим)
Появился в HTTP/1.1.
Указанный клиентом метод нельзя применить к текущему ресурсу. В ответе сервер должен указать доступные методы в заголовке Allow разделив их запятой.
Обратите внимание что эту ошибку сервер должен возвращать если метод ему известен, но он не применим именно к указанному в запросе ресурсу. Если же указанный метод не применим на всём сервере, то клиенту нужно вернуть ответ 501 (Not Implemented).
406 Not Acceptable (Не приемлемо)
Появился в HTTP/1.1.
Запрошенный URI не может удовлетворить переданным в заголовке характеристикам. Если метод был не HEAD, то сервер должен вернуть список допустимых характеристик для данного ресурса.
407 Proxy Authentication Required (Необходима авторизация прокси)
Появился в HTTP/1.1.
Ответ аналогичен коду 401 за исключением того, что аутентификация производится для прокси-сервера. Механизм аналогичен идентификации на исходном сервере.
408 Request Timeout (Время ожидания истекло)
Появился в HTTP/1.1.
Время ожидания сервером передачи от клиента истекло. Клиент может повторить аналогичный предыдущему запрос в любое время.
Например, такая ситуация может возникнуть при загрузке на сервер объёмного файла методом POST или PUT. В какой-то момент передачи источник данных перестал отвечать (например, из-за повреждёния компакт-диска или потеря связи с другим компьютером в локальной сети). Пока клиент ничего не передаёт, ожидая от него ответа, соединение с сервером держится. Через некоторое время сервер может закрыть соединение со своей стороны чтобы дать возможность другим клиентам сделать запрос.
Разумеется, этот ответ не возвращается когда клиент принудительно остановил передачу по команде пользователя или соединение прервалось по каким-то иным причинам, так как ответ уже послать не возможно.
409 Conflict (Конфликт)
Появился в HTTP/1.1.
Запрос не может быть выполнен из-за конфликтного обращения к ресурсу. Такое возможно, например, когда два клиента пытаются изменить ресурс с помощью метода PUT.
410 Gone (Удалён)
Появился в HTTP/1.1.
Такой ответ сервер посылает, когда ресурс раньше был по указанному URI, но был удалён и теперь недоступен. Серверу в этом случае не известно и местоположение альтернативного документа (например, копии). Если у сервера есть подозрение, что документ в ближайшее время может быть восстановлен, то лучше клиенту передать код 404.
411 Length Required (Необходима длина)
Появился в HTTP/1.1.
Для указанного ресурса клиент должен указать Content-Length в заголовке запроса. Без указания этого поля не стоит делать повторную попытку запроса к серверу по данному URI.
Такой ответ вполне естественнен для запросов типа POST и PUT. Например, если по указанному URI производится загрузка файлов, а на сервере стоит ограничение на их объём. Тогда разумней будет проверить в самом начале заголовок Content-Length и сразу отказать в загрузке, чем провоцировать бессмысленную нагрузку разрывая соединение когда клиент действительно пришлёт слишком объёмное сообщение.
412 Precondition Failed (Условие «ложно»)
Появился в HTTP/1.1.
Возвращается, если ни одно из условных полей заголовка запроса не было выполнено.
413 Request Entity Too Large (Запрашиваемые данные слишком большие)
Появился в HTTP/1.1.
Возвращается если сервер по каким-то причинам не может передать запрашиваемый объём информации. Если проблема временная, то сервер может в ответе указать в поле Retry-After время, по истечении которого можно повторить аналогичный запрос.
414 Request-URI Too Long (Запрашиваемый URI слишком длинный)
Появился в HTTP/1.1.
Сервер не может обработать запрос из-за слишком длинного указанного URI. Такую ошибку можно спровоцировать, например, когда клиент пытается передать длинные параметры через метод GET, а не POST.
415 Unsupported Media Type (Неподдерживаемый тип данных)
Появился в HTTP/1.1.
По каким-то причинам сервер отказывается работать с указанным типом данных при данном методе.
416 Requested Range Not Satisfiable (Запрашиваемый диапазон не достижим)
Введено в RFC 2616 (обновление HTTP/1.1).
В поле Range заголовка запроса был указан диапазон за пределами ресурса и отсутствует поле If-Range. Если клиент передал байтовый диапазон, то сервер может вернуть реальный размер в поле Content-Range заголовка. Данный ответ не следует использовать при передаче типа multipart/byteranges.
417 Expectation Failed (Ожидаемое не приемлемо)
Введено в RFC 2616 (обновление HTTP/1.1).
По каким-то причинам сервер не может удовлетворить значению поля Expect заголовка запроса.
422 Unprocessable Entity (Необрабатываемый экземпляр)
Сервер успешно принял запрос, может работать с указанным видом данных, в теле запроса XML-документ имеет верный синтаксис, но имеется какая-то логическая ошибка из-за которой невозможно произвести операцию над ресурсом.
423 Locked (Заблокировано)
Целевой ресурс из запроса заблокирован от применения к нему указанного метода.
424 Failed Dependency (Невыполненная зависимость)
Реализация текущего запроса может зависеть от успешности выполнения другой операции. Если она не выполнена и из-за этого нельзя выполнить текущий запрос, то сервер вернёт код 424.
425 Unordered Collection (Неупорядоченный набор)
Данный ответ посылается если клиент послал запрос обозначив положение в неотсортированной коллекции или используя порядок следования элементов отличный от серверного.
426 Upgrade Required (Необходимо обновление)
Введено в RFC 2817 для возможности перехода к TLS посредством HTTP.
Сервер указывает клиенту на необходимость обновить протокол. Заголовок ответа должен содержать правильно сформированные поля Upgrade и Connection.
449 Retry With (Повторить с. )
Возвращается сервером если для обработки запроса от клиента поступило не достаточно информации. При этом в заголовок ответа помещается поле Ms-Echo-Request.
В настоящий момент как минимум используется программой Microsoft Money. Более подробную информацию по данному коду ответа можно получить в библиотеке MSDN.
5xx: Server Error (Ошибка сервера)
Коды 5xx выделены под случаи неудачного выполнения операции по вине сервера. Для всех ситуаций, кроме использования метода HEAD, сервер должен включать в тело сообщения объяснение, которое клиент отобразит пользователю.
500 Internal Server Error (Внутренняя ошибка сервера)
Появился в HTTP/1.0.
Любая внутренняя ошибка сервера, которая не входит в рамки остальных ошибок класса 5xx.
501 Not Implemented (Не реализовано)
Появился в HTTP/1.0.
Сервер не поддерживает возможностей, необходимых для обработки запроса.
Типичный ответ для случаев, когда сервер не понимает указанный в запросе метод. Если же метод серверу известен, но он не применим только к данному ресурсу, то нужно вернуть ответ 405 (Method Not Allowed).
502 Bad Gateway (Плохой шлюз)
Появился в HTTP/1.0.
Сервер в роли шлюза или прокси получил сообщение о неудачном выполнении промежуточной операции.
503 Service Unavailable (Сервис недоступен)
Появился в HTTP/1.0.
Сервер временно не имеет возможности обрабатывать запросы по техническим причинам (обслуживание, перегрузка и прочее). В поле Retry-After заголовка сервер может указать время, через которое клиенту рекомендуется повторить запрос. Хотя во время перегрузки очевидным является сразу разрывать соединение, эффективней может оказаться установка большого значения поля Retry-After для уменьшения частоты избыточных запросов.
504 Gateway Timeout (Шлюз не отвечает)
Появился в HTTP/1.1.
Сервер в роли шлюза или прокси не дождался ответа от вышестоящего сервера для завершения текущего запроса.
505 HTTP Version Not Supported (Версия HTTP не поддерживается)
Появился в HTTP/1.1.
Сервер не поддерживает или отказывается поддерживать указанную в запросе версию протокола HTTP.
506 Variant Also Negotiates (Вариант тоже согласован)
Экспериментальное. Введено в RFC 2295 для дополнения протокола HTTP технологией Transparent Content Negotiation.
В результате ошибочной конфигурации выбранный вариант указывает сам на себя из-за чего процесс связывания прерывается.
507 Insufficient Storage (Переполнение хранилища)
Не хватает места для выполнения текущего запроса. Проблема может быть временной.
509 Bandwidth Limit Exceeded (Исчерпана пропускная ширина канала)
Введено в расширении bw/limited (mod_bwlimited) к Apache для cPanel.
Используется при превышении веб-площадкой отведённого ей ограничения на потребление трафика. В данном случае владельцу площадки следует обратиться к своему хостинг-провайдеру. В настоящий момент данный код не описан ни в одном RFC и используется только модулем bw/limited, входящем в панель управления хостингом cPanel.
510 Not Extended (Не расширено)
Введено в RFC 2774 для дополнения протокола HTTP поддержкой расширений.
На сервере отсутствует расширение, которое планирует использовать клиент. Сервер может дополнительно передать информацию о доступных ему расширениях.
Интересные факты
Примечания
Источники
См. также
Ссылки
Основные документы по протоколу HTTP (по убыванию даты публикации):
Документы по расширениям и обновлениям протокола HTTP (по убыванию даты публикации):
401 seems to be used to indicate an authentication failure whereas 403 for an authorization failure (which means authentication succeeded?) In case of an oauth flow if I try to authenticate with an expired token what is the right error code that prompts the client to refresh the token and try again?
3 Answers 3
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
A 401. The 401 vs 403 confusion is not new. See some discussion in a w3.org email here: https://lists.w3.org/Archives/Public/ietf-http-wg/2008AprJun/0418.html, though the cited RFC 2616 has been obsoleted.
From the 401 description, though «valid» is up for interpretation:
The 401 (Unauthorized) status code indicates that the request has not been applied because it lacks valid authentication credentials for the target resource.
But even more relevant, see RFC 6750 regarding Bearer Token authentication, Section 3, last paragraph. https://www.rfc-editor.org/rfc/rfc6750#section-3
And in response to a protected resource request with an authentication attempt using an expired access token:
Think about the boarding process in an airport. They check 2 things:
They check your identity card. This is authentication. Online, any token or user/password couple stands for your identity card.
They check you are in the passenger list for that plane (the plane is the resource you are trying to access). This is authorization. Online, the page the user is trying to access stands for the resource.
So now when you think about an access problem (token expired, token parsing failed, invalid password, user is not allowed) and which HTTP code you should return, you just have to think «if this issue was transposed into an airport scenario and I was denied access to the plane, would this have anything to do with the identity card check step?» If yes, this is 401. If not, this is 403.
Missing token Missing identity card Rejected because of identity card check 401
Expired token Expired identity card Rejected because of identity card check 401
Malformed token Unreadable/damaged identity card Rejected because of identity card check => 401
User doesn’t have privilege for the resource Passenger is not allowed to access this plane Not rejected because of identity card check => 403
You banned a user Passenger is blacklisted Not rejected because of identity card check => 403
TL;DR: 401
Long version, in addition to crunk1 (valid) answer:
401 would mean that the token was missing or invalid. In other words, it failed validation or parsing for some reason.
403 would mean that the token was successfully validated/parsed, but then the authorization to perform the action was denied for some reason.
Now, an expired token means that the token was successfully parsed but that the expiration date set in that token is already passed. Which is somewhat in-between if you consider that checking the expiration date is part of the authorization process. Personally I believe that it is part of the token validation, not the authorization, for those reasons:
There are some cases where the resource server (the API that receives and validates the token) would not even be able to know that the token is expired, and would return a 401 instead:
Also, a 403 response would instruct the client that it is an authorization issue, so retrying with an new token carrying the same access rights doesn’t have much chance to succeed, while a 401 would pass the information that the token was not accepted, so maybe retrying with a new fresh token might work.
For those reasons, I chose to return a 401 in my implementations. But TBH this doesn’t matter much, since the token expiration is supposed to be handled by the client, based on the expires_in information returned by the AS at the same time as the token, more than by a return code from the API when the token is expired.
You might have faced below error during replay of your script, though your script has web_set_user() function. In this article we will see how to fix it using various methods.
Basically above error occurs when the application is trying to validate the simulated request with proper credentials and header information. If any critical parameters missing in the header, LoadRunner throws above error.
Table of Contents
Fix 1:
Make sure that you have added valid details in the web_set_user() function. It should have valid user identity, password, and the host & port details. It is good to incorporate the password in the encrypted format using lr_decrypt functions. Below is the perfect example of web_set_user function.
web_set_user(“mydomain\\myuserid”, lr_decrypt(“4042e3e7c8bbbcfde0f737f91f”), ” mydomain:8080″);
Fix 2:
You can try running the script using WinInet replay instead of Sockets. To change the settings, go to Runtime Settings > Preferences, check Use WinInet replay instead of Sockets (Windows only)
Fix 3:
If above two fixes doesn’t work, you need to compare and validate the complete request of LoadRunner and the complete request from Fiddler.
Run the script in LoadRunner by turning on the extended log (preferably with Parameter Substitution and Data returned by server) and capture the request headers, cookies, etc.
Now, open Fiddler and manually navigate the business flow and then compare the request header information with LoadRunner info. If there is a mismatch, you need to incorporate it in the LoadRunner script. E.g. Fiddler request headers had authorization headers, accept encoding etc. You need to use web_add_header function to add the details to the script. If you use any other methods to fix unauthorized error, please let me know in the comments section.
If you like my article, please do share in your favorite social media. Please do not forget to subscribe to my weekly newsletter, it is FREE.
HTTP status code 401 even though I’m sending credentials in the request
Recently i have introduced JWT authentication to my Springboot and Angualr2 based App. In There i tried to do a POST request by passing the JWT token as below in my Angualr code
However in the server side it returns status code 401. The issue is in the Springboot side it checks the authorization header as below and it returns null
Then i had a look at the request header and it has the authorization header under Access-Control-Request-Headers as below. But it is not visible to the server side.
Then i read further and found that this could be an issue with CORS configuration. So i have modified my CORS configuration filter to have addExposedHeader as below
Still the server complains that it can not find the Authorization header. Did i miss any thing here? Appreciate your help
After reading the sideshowbarker’s comment below, i was able to understand the basics behind the issue. In My Project I have a JWT token filter and inside that it always checks the Authorization header. Then i have modified it as below and now it works as expected
1 Answer 1
You need to configure the server to not require authorization for OPTIONS requests (that is, the server the request is being sent to — not the one serving your frontend code).
That’s because what’s happening is this:
The Access-Control-Request-Headers and Access-Control-Request-Method request headers show in the question indicate the browser’s doing a CORS preflight OPTIONS request.
So you must figure out what part of the server-side code on the server the request is being sent to causes it to require authorization for OPTIONS requests, and change that so it instead responds to OPTIONS with a 200 or 204 success response without requiring authorization.
an unexpected status code ‘401 Unauthorized’ #318
Comments
ukomiljon commented Nov 24, 2017
Severity Code Description Project File Line Suppression State
Error CS0006 Metadata file ‘E:\Grial-marketezi\Grial\starter\marketezi\bin\Debug\marketezi.dll’ could not be found marketezi.iOS E:\Grial-marketezi\Grial\starter\marketezi.iOS\CSC 1 Active
Error NuGet Package restore failed for project marketezi.Droid: Unable to find version ‘2.5.2’ of package ‘UXDivers.Artina.Shared’.
C:\Program Files (x86)\Microsoft SDKs\NuGetPackages: Package ‘UXDivers.Artina.Shared.2.5.2’ is not found on source ‘C:\Program Files (x86)\Microsoft SDKs\NuGetPackages’.
https://api.nuget.org/v3/index.json: Package ‘UXDivers.Artina.Shared.2.5.2’ is not found on source ‘https://api.nuget.org/v3/index.json’.
http://nuget.uxdivers.com/grial: The V2 feed at ‘http://nuget.uxdivers.com/grial/Packages(Id=’UXDivers.Artina.Shared’,Version=’2.5.2′)’ returned an unexpected status code ‘401 Unauthorized’.
.
Error NuGet Package restore failed for project marketezi.Droid: Unable to find version ‘2.5.2’ of package ‘UXDivers.Artina.Shared.Base’.
C:\Program Files (x86)\Microsoft SDKs\NuGetPackages: Package ‘UXDivers.Artina.Shared.Base.2.5.2’ is not found on source ‘C:\Program Files (x86)\Microsoft SDKs\NuGetPackages’.
https://api.nuget.org/v3/index.json: Package ‘UXDivers.Artina.Shared.Base.2.5.2’ is not found on source ‘https://api.nuget.org/v3/index.json’.
http://nuget.uxdivers.com/grial: The V2 feed at ‘http://nuget.uxdivers.com/grial/Packages(Id=’UXDivers.Artina.Shared.Base’,Version=’2.5.2′)’ returned an unexpected status code ‘401 Unauthorized’.
.
Error NuGet Package restore failed for project marketezi.iOS: Unable to find version ‘2.5.2’ of package ‘UXDivers.Artina.Shared’.
C:\Program Files (x86)\Microsoft SDKs\NuGetPackages: Package ‘UXDivers.Artina.Shared.2.5.2’ is not found on source ‘C:\Program Files (x86)\Microsoft SDKs\NuGetPackages’.
https://api.nuget.org/v3/index.json: Package ‘UXDivers.Artina.Shared.2.5.2’ is not found on source ‘https://api.nuget.org/v3/index.json’.
http://nuget.uxdivers.com/grial: The V2 feed at ‘http://nuget.uxdivers.com/grial/Packages(Id=’UXDivers.Artina.Shared’,Version=’2.5.2′)’ returned an unexpected status code ‘401 Unauthorized’.
.
Error NuGet Package restore failed for project marketezi.iOS: Unable to find version ‘2.5.2’ of package ‘UXDivers.Artina.Shared.Base’.
C:\Program Files (x86)\Microsoft SDKs\NuGetPackages: Package ‘UXDivers.Artina.Shared.Base.2.5.2’ is not found on source ‘C:\Program Files (x86)\Microsoft SDKs\NuGetPackages’.
https://api.nuget.org/v3/index.json: Package ‘UXDivers.Artina.Shared.Base.2.5.2’ is not found on source ‘https://api.nuget.org/v3/index.json’.
http://nuget.uxdivers.com/grial: The V2 feed at ‘http://nuget.uxdivers.com/grial/Packages(Id=’UXDivers.Artina.Shared.Base’,Version=’2.5.2′)’ returned an unexpected status code ‘401 Unauthorized’.
.
Error NuGet Package restore failed for project marketezi: Unable to find version ‘2.5.2’ of package ‘UXDivers.Artina.Controls.Repeater’.
C:\Program Files (x86)\Microsoft SDKs\NuGetPackages: Package ‘UXDivers.Artina.Controls.Repeater.2.5.2’ is not found on source ‘C:\Program Files (x86)\Microsoft SDKs\NuGetPackages’.
https://api.nuget.org/v3/index.json: Package ‘UXDivers.Artina.Controls.Repeater.2.5.2’ is not found on source ‘https://api.nuget.org/v3/index.json’.
http://nuget.uxdivers.com/grial: The V2 feed at ‘http://nuget.uxdivers.com/grial/Packages(Id=’UXDivers.Artina.Controls.Repeater’,Version=’2.5.2′)’ returned an unexpected status code ‘401 Unauthorized’.
.
Error NuGet Package restore failed for project marketezi: Unable to find version ‘2.5.2’ of package ‘UXDivers.Artina.Controls.Tab’.
C:\Program Files (x86)\Microsoft SDKs\NuGetPackages: Package ‘UXDivers.Artina.Controls.Tab.2.5.2’ is not found on source ‘C:\Program Files (x86)\Microsoft SDKs\NuGetPackages’.
https://api.nuget.org/v3/index.json: Package ‘UXDivers.Artina.Controls.Tab.2.5.2’ is not found on source ‘https://api.nuget.org/v3/index.json’.
http://nuget.uxdivers.com/grial: The V2 feed at ‘http://nuget.uxdivers.com/grial/Packages(Id=’UXDivers.Artina.Controls.Tab’,Version=’2.5.2′)’ returned an unexpected status code ‘401 Unauthorized’.
.
Error NuGet Package restore failed for project marketezi: Unable to find version ‘2.5.2’ of package ‘UXDivers.Artina.Shared’.
C:\Program Files (x86)\Microsoft SDKs\NuGetPackages: Package ‘UXDivers.Artina.Shared.2.5.2’ is not found on source ‘C:\Program Files (x86)\Microsoft SDKs\NuGetPackages’.
https://api.nuget.org/v3/index.json: Package ‘UXDivers.Artina.Shared.2.5.2’ is not found on source ‘https://api.nuget.org/v3/index.json’.
http://nuget.uxdivers.com/grial: The V2 feed at ‘http://nuget.uxdivers.com/grial/Packages(Id=’UXDivers.Artina.Shared’,Version=’2.5.2′)’ returned an unexpected status code ‘401 Unauthorized’.
.
Error NuGet Package restore failed for project marketezi: Unable to find version ‘2.5.2’ of package ‘UXDivers.Artina.Shared.Base’.
C:\Program Files (x86)\Microsoft SDKs\NuGetPackages: Package ‘UXDivers.Artina.Shared.Base.2.5.2’ is not found on source ‘C:\Program Files (x86)\Microsoft SDKs\NuGetPackages’.
https://api.nuget.org/v3/index.json: Package ‘UXDivers.Artina.Shared.Base.2.5.2’ is not found on source ‘https://api.nuget.org/v3/index.json’.
http://nuget.uxdivers.com/grial: The V2 feed at ‘http://nuget.uxdivers.com/grial/Packages(Id=’UXDivers.Artina.Shared.Base’,Version=’2.5.2′)’ returned an unexpected status code ‘401 Unauthorized’.
.
Error The «ResolveLibraryProjectImports» task failed unexpectedly.
System.IO.FileNotFoundException: Could not load assembly ‘marketezi, Version=0.0.0.0, Culture=neutral, PublicKeyToken=’. Perhaps it doesn’t exist in the Mono for Android profile?
File name: ‘marketezi.dll’
at Java.Interop.Tools.Cecil.DirectoryAssemblyResolver.Resolve(AssemblyNameReference reference, ReaderParameters parameters)
at Java.Interop.Tools.Cecil.DirectoryAssemblyResolver.Resolve(String fullName)
at Xamarin.Android.Tasks.ResolveLibraryProjectImports.Extract(DirectoryAssemblyResolver res, ICollection 1 jars, ICollection 1 resolvedResourceDirectories, ICollection 1 resolvedAssetDirectories, ICollection 1 resolvedEnvironments)
at Xamarin.Android.Tasks.ResolveLibraryProjectImports.Execute()
at Microsoft.Build.BackEnd.TaskExecutionHost.Microsoft.Build.BackEnd.ITaskExecutionHost.Execute()
at Microsoft.Build.BackEnd.TaskBuilder.d__26.MoveNext() marketezi.Droid
Error CS0234 The type or namespace name ‘Artina’ does not exist in the namespace ‘UXDivers’ (are you missing an assembly reference?) marketezi E:\Grial-marketezi\Grial\starter\marketezi\App.xaml.cs 8 Active
Error CS0234 The type or namespace name ‘Artina’ does not exist in the namespace ‘UXDivers’ (are you missing an assembly reference?) marketezi E:\Grial-marketezi\Grial\starter\marketezi\Helpers\Settings.cs 6 Active
Error CS0234 The type or namespace name ‘Artina’ does not exist in the namespace ‘UXDivers’ (are you missing an assembly reference?) marketezi E:\Grial-marketezi\Grial\starter\marketezi\Properties\AssemblyInfo.cs 14 Active
The text was updated successfully, but these errors were encountered:
LeoHere commented Nov 24, 2017
Looks like it failed authenticating against our nuget package source. Please double check your credentials by visiting this in your browser.
ukomiljon commented Nov 25, 2017
I can go in Grial Admin with user name and password.
But http://nuget.uxdivers.com/grial/
displays after login:
This XML file does not appear to have any style information associated with it. The document tree is shown below.
LeoHere commented Nov 27, 2017
The fact that displays the XML means you successfully authenticate, so your credentials are fine.
The problem seems to be in VS side. VS should ask you for your credentials when you try to access the Nuget package. Not sure why that is not the case in your setup.
Another option you have is to set your credentials in the NuGet.config file in the root directory (where the sln file resides).
Something like this:
Read this for more information.
ukomiljon commented Nov 28, 2017
We are using VS2017 community edition.
is it any issue with VS2017 community edition?
I checked there is no any NuGet.config file.
UXDivers.Artina.Shared,UXDivers.Artina.Shared.Base, UXDivers.Artina.Shared.Repeater and UXDivers.Artina.Shared.Tab are issue,
but UXDivers.Effects is not issue
LeoHere commented Nov 28, 2017
VS2017 Community is not an issue.
If there is no Nuget.config (which is the most common case) you will need to create it.
UXDivers.Effects is a public Nuget package, so it make sense.
ukomiljon commented Nov 29, 2017
I created Nuget.config:
But not working.
ukomiljon commented Nov 29, 2017
ukomiljon commented Nov 30, 2017
Could you give me sample Nuget.config complete package?
ukomiljon commented Nov 30, 2017
LeoHere commented Nov 30, 2017
@ukomiljon the Nuget.Config you specified looks just fine.
May be the name used in the Nuget.Config is the same as the one defined in Tools->Options->Nuget and is somehow confusing VS.
Please set the Nuget.Config to something like this.
so we are sure there is no naming conflict. Remember to set your user name and password.
An unexpected 401.1 status is returned when you use Pre-Authentication headers with Internet Explorer and IIS
This article resolves the problem where an unexpected 401.1 status is returned with Pre-Authentication headers. It occurs when you use Internet Explorer to browser to a web application hosted on Internet Information Services (IIS).
Original product version:В IE mode for Edge, Internet Information Services, Internet Explorer 11, 10, 9
Original KB number:В 2749007
Symptoms
Consider the following scenario:
In this scenario, IIS may return an HyperText Transfer Protocol (HTTP) 401.1 response to Internet Explorer in response to the browser’s request. The web browser may prompt you to enter your username and password. Or, the HTTP 401.1 error message may be displayed in the browser window.
Cause
This behavior is by design. The 401.1 response will occur if the web browser’s first request that’s sent to the IIS application contains one of the following headers:
There are many reasons a user may be prompted for credentials in Internet Explorer that are outside the scope of this article. See the More information section below to learn how to determine if the cause of the prompt is from the issue described here.
Workaround
To work around this behavior, disable Pre-Authentication in Internet Explorer, or turn off Kernel Mode Authentication for the IIS Web application.
If you use Registry Editor incorrectly, you may cause serious problems that may require you to reinstall your operating system. Microsoft can’t guarantee that you can solve problems that result from using Registry Editor incorrectly. Use Registry Editor at your own risk.
To modify this behavior in Internet Explorer, use Registry Editor ( Regedt32.exe ) to add a value to the following registry key:
HKEY_CURRENT_USER/Software/Microsoft/Windows/CurrentVersion/Internet Settings/
The above registry key is one path; it has been wrapped for readability.
Add the following registry value:
To modify this behavior in IIS, disable Kernel Mode Authentication for the IIS web application.
Open Internet Information Services (IIS) Manager by running the following command from an administrative command prompt:
In the Connections pane, expand the server name, expand Sites, and then the site, application, or Web service for which you want to disable Kernel Mode Authentication.
Scroll to the Security section in the Home pane, and then double-click Authentication.
In the Authentication pane, select Windows Authentication.
Select Advanced Settings in the Actions pane.
When the Advanced Settings dialog box appears, clear the Enable Kernel-mode authentication checkbox.
Select OK to close the Advanced Settings dialog box.
Disabling Kernel Mode Authentication may cause web applications that require Kerberos authentication and delegation to fail.
More information
To determine if the prompt is caused by the issue described in this article, use the Fiddler tool. Use the tool to view the HTTP request/response traffic for the request resulting in the prompt in Internet Explorer. You’ll also need the IIS logs from the IIS Server to confirm the HTTP status and sub status codes. The following example uses Internet Explorer 9 to illustrate this behavior:
Start the Fiddler Tool and enable traffic capture.
Browse to the IIS web application such that it will result in the prompt for credentials.
In Fiddler, look for the request that resulted in the 401. Looking at the raw request and response views, you’ll see entries similar to the following ones:
The initial request to the web application already contains the Authorization header, which then results in the 401 response. The corresponding IIS log should show an entry similar to the following one:
The HTTP status and sub status are 401.1, which maps to Access Denied due to Invalid credentials.
For more information, see the following documentation:
HTTP Status Code: 401 in GCMDemo
Part of Google Cloud Collective
Server 401 when trying to send a message to my android device.
Could anybody tell me how to solve?Thank you!
1 Answer 1
You should take a look at the GCM docs where it explains the GCM response: http://developer.android.com/google/gcm/gcm.html#response and troubleshooting the 401 error code: http://developer.android.com/google/gcm/gcm.html#auth_error
Description from the docs:
Authentication Error The sender account that you’re trying to use to send a message couldn’t be authenticated. Possible causes are:
Authorization header missing or with invalid syntax.
Invalid project number sent as key.
Key valid but with GCM service disabled.
Request originated from a server not whitelisted in the Server Key IPs.
So I would check to make sure that you are setting you authorization header properly and that you Google Project number is properly setup with GCM and accepting your servers IP.
Friendly HTTP 401 Status Code Message?
I’m a developer not a wordsmith and as such I’m stuck.
We have a subscription based site whereby users may well come across our 401 page.
We’ve decided that the IIS 401;2 page needs replacing.
Does anyone have any examples or advise about writing a good non offensive 401 page?
4 Answers 4
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
Through a series of highly sophisticated and complex algorithms, this system has determined that you are not presently authorized to use this system function. It could be that you simply mistyped a password, or, it could be that you are some sort of interplanetary alien-being that has no hands and, thus, cannot type. If I were a gambler, I would bet that a cat (an orange tabby named Sierra or Harley) somehow jumped onto your keyboard and forgot some of the more important pointers from those typing lessons you paid for. Based on the actual error encountered, I would guess that the feline in question simply forgot to place one or both paws on the appropriate home keys before starting. Then again, I suppose it could have been a keyboard error caused by some form of cosmic radiation; this would fit nicely with my interplanetary alien-being theory. If you think this might be the cause, perhaps you could create some sort of underground bunker to help shield yourself from it. I don’t know that it will work, but, you will probably feel better if you try something.
And don’t get me started on all the cool 404 pages out there.
Коды ошибок HTTP – список ошибок сервера и клиента
Практически каждый сталкивался с ситуацией, когда в ответ на попытку открыть сайт, загрузить файл или приложение браузер выдает ошибку, например, 404 – Not Found. Каждая ошибка имеет свой код – трехзначное число, по которому можно определить, что именно произошло с запросом.
На самом деле веб-сервер высылает трехзначные коды в ответ на любое обращение браузера к нему, даже если запрос обработан успешно. Но обычный пользователь сталкивается только с кодами, обозначающими ошибку обработки запроса, а успешные и информационные ответы сервера остаются для него невидимыми.
В этой статье мы разберем, какие виды ошибок зашифрованы в ответах и почему эти ошибки возникают.
Ошибки 4xx (400-414)
Ответы с кодами от 400 до 414 называют «ошибками на стороне клиента». Сервер дает понять, что что-то не так с самим запросом. Несмотря на классификацию, такие ошибки часто необходимо исправлять вебмастеру, а не пользователю. Их причиной могу быть неправильные настройки веб-сервера, скриптов сайта и т. п.
Ошибка 400
Расшифровывается как «неверный запрос». Код ошибки 400 говорит о том, что запрос составлен неправильно, и сервер не может его понять. Если вы формируете запрос вручную, то, возможно, указали неверный URL. Но чаще всего запрос повреждается в результате технического сбоя или искажения данных при передаче. Это может произойти по нескольким причинам:
Ошибка 401
Пояснение – «не авторизовано». Код ошибки 401 означает, что запрос направлен к защищенным ресурсам, для которых требуется аутентификация. Сервер ожидает получить логин и пароль, но в запросе их нет.
Ошибка 403
Ответ означает «Запрещено». У пользователя нет прав на доступ к файлам или папкам по ссылке. Чаще всего вебмастеру исправлять ничего не нужно, все настроено верно. А вот пользователю необходимо проверить, правильно ли он указал адрес страницы. Иногда из-за опечатки ссылка ведет в запрещенную для просмотра папку, а не на страницу сайта.
Если же пользователь не может попасть на страницу, которая должна быть разрешена к просмотру, то, возможно, в настройках сайта или внутренних ссылках есть ошибки, которые нужно исправить разработчику.
Ошибка 404
Самый популярный код ошибки – 404. Переводится как «не найдено». Такой ответ сервер отсылает, если не находит документ, файл или страницу по указанному пользователем адресу. Возможные причины:
Страницу, на которой посетитель видит код ошибки 404, рекомендуется оформить с пользой: дать ссылки на главную страницу сайта и популярные разделы, объяснить, почему пользователь видит эту ошибку. На многих сайтах на 404 странице можно увидеть креативное оформление, забавные анимации и т. п.
Ошибка 405
Расшифровка – «метод не поддерживается». Для каждого типа операций (загрузка, передача данных) http-протокол предусматривает использование своего метода (GET, POST и т. д.). Ошибка означает, что запрос на сервер выполнен с использованием неправильного метода. От клиента здесь мало что зависит, причины – в настройках веб-сервера. Например:
Ошибка 406
Расшифровывается как «неприемлемо». Достаточно редкий ответ. Возникает, если сервер отдает информацию в виде, который не может распознать клиент (ваш браузер, или поисковый робот – если ошибка появляется при индексации страниц сайта). Чаще всего контент не распознается из-за сжатия или неподдерживаемого формата, иногда – неправильной кодировки.
Причина может быть в:
Ошибка 407
Пояснение переводится как «нужна аутентификация прокси». Возникает, если доступ в сеть или к определенным сайтам осуществляется через прокси-сервер, но в запросе нет данных для авторизации на нем. Пользователю нужно пройти аутентификацию. Обычно в тексте ответа с кодом 407 содержатся подсказки – как это сделать.
Ошибка 408
Переводится как «истекло время запроса». Может возникнуть при передаче больших файлов, временного сбоя интернет-подключения, перегрузке сервера в данный момент и т. д. Чаще всего никаких действий от вебмастера не требуется, за исключением случаев, когда 408 ошибка появляется часто и есть подозрение, что сервер не справляется с текущей нагрузкой. Тогда стоит подумать об аренде дополнительных ресурсов хостинга или переходе на более подходящий тарифный план.
Со стороны пользователя чаще всего устранить проблему можно простой перезагрузкой страницы. Также можно попробовать зайти на сайт позже или проверить стабильность интернет-соединения.
Ошибка 409
Произошел конфликт запроса и данных на сервере. Например, пользователь загружает файл устаревшей версии, в то время как аналогичный файл на сервере – более новый.
В некоторых случаях причиной может быть:
Чаще всего ошибку можно устранить, просто загрузив корректный файл.
Ошибка 410
Страница или документ, к которому обращается запрос, недоступен. Ошибка 410 похожа на 404 с той лишь разницей, что она выдается, если данные по ссылке удалены навсегда.
Исправлять чаще всего ничего не нужно. Наоборот, рекомендуется прописывать код ответа 410 для документов или страниц, которые были удалены, чтобы поисковые роботы не тратили на них лимит сканирования при переобходе сайта.
Ошибка 411
Расшифровывается как «требуется длина». Такая ситуация может возникнуть при передаче файлов определенными методами и выставленных ограничениях на передаваемый объем. В этих случаях серверу нужен параметр Content-Length, и он ожидает увидеть его в запросе.
Ошибка 412
Расшифровывается как «предварительное условие не выполнено». Причину ошибки нужно искать в заголовках запроса. Иногда там прописываются различные условия, и сервер обязан проверить их соблюдение перед обработкой запроса. Если при проверке сервер выявляет, что условия не могут быть выполнены, не соблюдаются, он отклоняет запрос и высылает ответ с кодом 412.
Самая простая причина – проблема в браузере пользователя. Достаточно почистить кеш и куки, чтобы ошибка исчезла.
Также проблема может возникнуть после установки на сайте новых тем, плагинов или некорректного изменения кода.
Ошибка 413
Если ограничения выставлены корректно, то пользователю нужно порекомендовать:
Ошибка 414
Перевод пояснения – «URL слишком длинный». Сервер не может взять в обработку слишком длинный веб-адрес, и поэтому отклоняет запрос.
Ошибка может возникнуть, например, при некорректно настроенном коде CMS, когда при каждом переходе со страницы на страницу в административной панели сайта к URL дописывается фрагмент с параметрами. Таким образом ссылка становится все длиннее и длиннее, пока не превышает лимит.
Часто наличие таких ошибок и переходов по длинным URL свидетельствуют о попытках взломать сайт.
Ошибки на стороне сервера 5xx
Следующая категория ошибок – на стороне сервера (с 500 по 560). Ответ с таким кодом говорит, что запрос корректный, и отвечает всем требованиям сервера, но сам сервер по своим причинам не может его обработать. Разберем коротко каждую из ошибок.
Ошибка 500
Ошибка 501
Означает «не реализовано». Сервер не понимает метод запроса, или не имеет функциональности для его обработки. Не стоит путать с 405 ошибкой – в ее случае метод просто используется неправильно (не к тем данным или неправильным способом), однако сервер его знает.
Ошибка 502
Означает «ошибка шлюза». Если запрос проходит через несколько серверов (через прокси), и какой-то из них не может обработать запрос, то первый сервер отдает такую ошибку. Возможные причины:
Ошибка 503
Пояснение переводится как как «сервис недоступен». Возможные причины:
Ошибка 503 может быть связана с DDoS-атакой или просто перегрузкой сервера из-за несоответствия нагрузки на сайт и выделенных под него на хостинге мощностей. В последнем случае, возможно, стоит перейти на тарифный план уровнем выше.
Ошибка 504
Означает, что «время прохождения через шлюз истекло». Возникает, если запрос проходит через один или несколько шлюзов-серверов, и один из них не укладывается в отведенный таймаут. Причинами могут быть слишком короткий таймаут в настройках, перегрузка сервера запросами, медленное или нестабильное интернет-соединение между серверами и т. п.
Ошибка 505
Означает «версия http не поддерживается». Здесь причина понятна из названия ошибки. Такой ответ можно получить, если на сервере или клиенте работает устаревшее программное обеспечение, а также из-за некорректных настроек обработки запросов на стороне сервера.
Ошибка 506
Можно расшифровать как «сервер подвергается цензуре». Сервер, к которому отправлен запрос, запрещен для доступа из-за цензурных ограничений.
Cтатус HTTP ответа веб сервера
Код состояния HTTP — это часть строки заголовка, ответа веб сервера на запрос клиента, информирующая о результате запроса и о том, что клиент должен предпринять далее
Код состояния HTTP — это часть строки заголовка, ответа веб сервера на запрос клиента, информирующая о результате запроса и о том, что клиент должен предпринять далее. Думаю не все знают как выглядит заголовок ответа сервера, зато уверен, каждый, пользующийся интернетом, не раз сталкивались, со страницей 404 Not Found или 403 Forbadden. Это и есть, видимый пользователю результат, выдачи сервером, того или иного кода статуса в строке заголовке.
Коды состояния HTTP, разделены на 5 категорий. Клиент может быть не знаком с тем или иным кодом ответа HTTP, однако он должен отреагировать согласно категории кода. Итак протокол HTTP поддерживает следующие коды статуса, разделенные по категориям:
1xx: Information — информационные
2xx: Success — Успешное завершение
3xx: Redirection — Редирект ( перенаправление )
Коды данной категории, сообщают клиенту, что для завершения запроса, ему необходимо выполнить дополнительный запрос, как правило по другому URI, соответствующий адрес указывается в строке Location, ответа сервера. Программа — клиент может совершать дополнительные запросы без участия пользователя, при условии что дополнительный запрос делается методами GET или HEAD.
Некоторые клиенты некорректно работают с редиректами 301 и 302, применяя в запросе ко второму ресурсу метод GET, несмотря на то, что первый запрос был сделан с использованием другого метода. В протоколеHTTP версии 1.1, вместо ответа статуса 302, были введены дополнительные коды ответов, 303 и 307. Изменять метод, необходимо только в случает ответа сервера со статусом 303, в остальных случаях использовать исходный метод.
300 Multiple Choices — Несколько вариантов выбора. По запрошенному URI, существует несколько вариантов ресурса, различных по MIME типу. языку или другим признакам. В ответе сервера, передается список альтернатив, выбираемый клиентским приложением автоматически или самим пользователем. Появился в протоколе версии HTTP/1.0. 301 Moved Permanently — Перемещёно окончательно. Запрошенный ресурс был окончательно перемещен на URI, указанный в строке заголовка Location, ответа сервера. Некоторые клиенты, при обработке данного кода, ведут себя некорректно, см. выше. Появился в протоколе версии HTTP/1.0. 302 Found — Найдено ( Moved Temporarily ) Данный код статуса сообщает клиенту, что ресурс временно доступен по другому URI, указанному в строке заголовка Location, заголовка ответа сервера. Данный код используется например, при согласовании содержимого ( Content Negotiation ), выполняемого сервером. Появился в протоколе версии HTTP/1.0. 303 See Other — Смотреть другое. Документ из запрошенного URI, нужно запросить по адресу, указанному в строке заголовка Location, заголовка ответа сервера, используя метод GET, невзирая на то, каким методом был сделан первый запрос. Появился в протоколе версии HTTP/1.1. 304 Not Modified — Не изменялось. Данный код выдается в случае запроса документа, методом GET, с использованием заголовков If-Modified-Since или If-None-Match, и документ не был изменен с указанного момента времени. Появился в протоколе версии HTTP/1.0. 305 Use Proxy — Использовать прокси сервер. Запрос к ресурсу, должен выполняться через прокси-сервер., адрес которого, указан в строке заголовка Location, заголовка ответа сервера. Появился в протоколе версии HTTP/1.1. 307 Temporary Redirect — Временное перенаправление Запрошенный ресурс временно доступен по URI, указанному в строке заголовка Location, заголовка ответа сервера. Появился в протоколе версии HTTP/1.1.
4xx: Client Error — Ошибка клиента
Коды данной категории служат для указание на ошибку со стороны клиента. При использовании любых методов запроса, кроме HEAD, сервера возвращает пользователю гипертекстовое пояснение по данной ошибке.
400 Bad Request — Плохой запрос. Из-за синтаксической ошибки, запрос не был понят сервером. Появился в протоколе версии HTTP/1.0. 401 Unauthorized — Не авторизован. Ресурс требует идентификации пользователя. Клиентское приложение запрашивает у пользователя данные для аутентификации ( имя, пароль ) и передает их на сервер в заголовке WWW-Authenticate. Если данные указаны не правильно, будет снова выдан этот-же код статуса. Появился в протоколе версии HTTP/1.0. 402 Payment Required — Необходима оплата. Пока не используется. Появился в протоколе версии HTTP/1.1. 403 Forbidden — Запрещено. Сервер отказал в доступе к запрошенному ресурсу ввиду ограничений. Ограничения могут быть любыми, установленными администратором сервера, или определенным веб приложением. Например, в целях безопасности, закрыт доступ к файлу, .htacces или .htpasswd или к закрытой директории сайта, или в случае, когда аутентификация должна производится через веб приложение ( например сайтовый движок ), ну или блокировка по IP адресу, в случае слишком частых обращений. Появился в протоколе версии HTTP/1.0. 404 Not Found — Не найдено. Сервер не нашел запрошенный ресурс по указанному адресу. Кроме того данный код ответа можно использовать вместо 403, с целью, скрыть расположение документа, доступ к которому запрещен. Появился в протоколе версии HTTP/1.0. 405 Method Not Allowed — Метод не поддерживается. Клиент попытался использовать метод, недопустимый для данного ресурса. Сервер передает в заголовке, строку Allow, содержащую список допустимых методов. Появился в протоколе версии HTTP/1.1. 406 Not Acceptable — Не приемлемо. Запрошенный ресурс, не удовлетворяет, запрошенные характеристики. В случае, если запрос был сделан не методом HEAD, сервер вернет список допустимых характеристик запрошенного ресурса. Появился в протоколе версии HTTP/1.1. 407 Proxy Authentication Required — Необходима прокси авторизация. Данный код статуса, аналогичен коду 401 за исключением того, что аутентификация производится для прокси-сервера. Появился в протоколе версии HTTP/1.1. 408 Request Timeout — Время ожидания истекло. Истек таймаут ожидания передачи данных, между сервером и клиентом. Появился в протоколе версии HTTP/1.1. 409 Conflict — Конфликт. Конфликтная ситуация при обращении к ресурсу. Такое может произойти, например, при попытке одновременного изменения файла, методом PUT, несколькими клиентами. Появился в протоколе версииHTTP/1.1. 410 Gone — Удалён. Данный ответ выдается в случае, если документ был по указанному URI, но в данный момент удален. Появился в протоколе версии HTTP/1.1. 411 Length Required — Необходима длина. Этот код статуса говорит о том, что для данного URI, в заголовке запроса, должно быть указано значение в поле Content-Length. Появился в протоколе версии HTTP/1.1. 412 Precondition Failed — Условие «ложно. Данный код выдается в случае, если ни одно из условных полей заголовка не было удовлетворено. Появился в протоколе версии HTTP/1.1. 413 Request Entity Too Large — Запрошены слишком большие данные. Данный код выдается, если сервер по каким-либо причинам, не может передать, требуемый объем данных. Если это временная проблема, сервер может указать время, по истечении которого можно будет попробовать повторно запросить ресурс, в строке заголовка, Retry-After. Появился в протоколе версии HTTP/1.1. 414 Request-URI Too Long — Запрашиваемый URI слишком длинный. Слишком длинная строка запроса. Такая ситуация может произойти, например в случае попытки, передать данные методом GET, вместо использования POST. Появился в протоколе версии HTTP/1.1. 415 Unsupported Media Type — Неподдерживаемый тип данных. Сервер, по какой-то причине, отказался обрабатывать запрошенные данные, используемым методом. Появился в протоколе версии HTTP/1.1. 416 Requested Range Not Satisfiable — Запрашиваемый диапазон не достижим. В строке заголовка запроса Range, установлен диапазон, выходящий за рамки запрошенного ресурса и отсутствует строка If-Range. Появился в протоколе версии HTTP/1.1. 417 Expectation Failed — Ожидаемое не приемлемо. Сервер не может обработать строку заголовка запроса Expect. Появился в протоколе версии HTTP/1.1. 422 Unprocessable Entity — Необрабатываемый экземпляр. Запрос принят, тип данных может быть обработан, синтаксис XML данных в теле запроса верен, но имеет место логическая ошибка, не позволяющая обработать запрос к ресурсу. Используется в протоколеWebDAV. 423 Locked — Заблокировано. Запрошенный ресурс заблокирован от данного метода. Используется в протоколе WebDAV. 424 Failed Dependency — Невыполненная зависимость. Выполнение запроса, может зависеть от результата выполнения, какой-либо другой операции, при невыполнении данного условия, будет выдан этот код статуса. Используется в протоколе WebDAV. 425 Unordered Collection — Беспорядочный набор. Этот код статуса будет выдан в случае, если клиент отправил запрос обозначив положение в неотсортированной коллекции или используя порядок следования элементов отличный от серверного. Введено в черновике по WebDAV Advanced Collections Protocol. 426 Upgrade Required — Требуется обновление. Указание сервера, клиенту, обновить протокол. Заголовок ответа, должен содержать правильно составленные поля Upgrade и Connection. Введено в RFC 2817 для возможности перехода к TLS посредствомHTTP. 449 Retry With — Повторить с… Выдается в случае поступления не достаточного количества информации для обработки запроса. В заголовок ответа сервера, помещается строка Ms-Echo-Request. Введено корпорацией Microsoft дляWebDAV.
5xx: Server Error — Ошибка на стороне сервера
Коды данной категории, предназначены для ситуаций, когда обработка запроса не возможна по вине сервера. Во всех случаях, кроме использования метода HEAD, сервер должен включать в тело ответа, объяснение для пользователя.
500 Internal Server Error — Внутренняя ошибка сервера. Любая внутренняя ошибка на стороне сервера не подпадающая под остальные ошибки из категории 5хх. Появился в протоколе версии HTTP/1.0. 501 Not Implemented — Не реализовано. Сервер не поддерживает, необходимых для обработки запроса, возможностей. ( например не поддерживается необходимый метод обработки ). Появился в протоколе версии HTTP/1.0. 502 Bad Gateway — Плохой шлюз. Сервер, работающий в качестве прокси или шлюза, получил сообщение о неудачное в промежуточной операции. Появился в протоколе версии HTTP/1.0. 503 Service Unavailable — Сервис недоступен. Сервер не в состоянии обрабатывать запросы клиентов по техническим причинам. Появился в протоколе версии HTTP/1.0. 504 Gateway Timeout — Истек таймаут ожидания ответа шлюза. Проксирующий сервер или шлюз, не дождался ответа от вышестоящего сервера для завершения обработки запроса. Появился в протоколе версии HTTP/1.0. 505 HTTP Version Not Supported — Версия HTTP протокола не поддерживается. Сервер не поддерживает, или не может обработать, указанную в заголовке версию HTTP протокола. Появился в протоколе версии HTTP/1.0. 506 Variant Also Negotiates — Вариант тоже согласован. Из-за не верной конфигурации, выбранный вариант указывает сам на себя, в следствии чего, связывание прерывается. Добавлено в RFC 2295 для дополнения протокола HTTP технологией Transparent Content Negotiation. 507 Insufficient Storage — Переполнение хранилища. Недостаточно места для обработки текущего запроса. Возможно временная проблема. Используется в протоколе WebDAV. 509 Bandwidth Limit Exceeded — Пропускная возможность канала исчерпана. Данный код статуса, используется в случае превышения веб площадкой, отведенного ей лимита, на потребляемый трафик. Данный код не описан ни одним RFC и используется только модулем bw/limited, панели веб-хостинга cPanel. 510 Not Extended — Нет расширения. У сервера отсутствует расширение, которое пытается использовать клиентом. Сервер может передавать информацию, об имеющихся у него расширениях. Введено в RFC 2774 для дополнения протокола HTTPподдержкой расширений.
Методы обработки запросов HTTP
HTTP метод — это основная операция, которую необходимо выполнить над ресурсом. В названии могут использоваться любые символы, кроме управляющих последовательностей и разделителей, как правило это короткое слово на английском языке. Имена методов HTTP зависимы от регистра.
Любой веб сервер обязан работать, по крайней мере с двумя методами GET и HEAD. Если сервер не смог определить метод, указанный в заголовке запроса клиента, он должен вернуть код статуса 501 (Not Implemented), если-же метод серверу известен, но неприменим к данному ресурсу, будет возвращен код статуса 405 (Method Not Allowed). Как в первом, так и во втором случае, сервер должен включить в свой ответ, заголовок Allow со списком методов, которые он поддерживает.
Метод OPTIONS
Данный метод используется для выяснения поддерживаемых веб-сервером возможностей или параметров соединения с конкретным ресурсом. Сервер включает в ответный запрос заголовок Allow, со списком поддерживаемых методов и возможно информацию о поддерживаемых расширениях. Тело запроса клиента, содержит информацию об интересующих его данных, но на данном этапе формат тела и порядок работы с ним, не определен, пока, сервер должен его игнорировать. С ответным запросом сервера, происходит аналогичная ситуация.
Что-бы выяснить возможности сервера, клиент должен указать в запросе URI, символ — «*«, то есть данный запрос к серверу выглядит как: OPTIONS * HTTP/1.1. Кроме прочего, данный запрос может быть использован для проверки работоспособности сервера и поддержки им протокола HTTP, версии 1.1. Результаты данного запроса не кэшируются.
Метод GET
Метод GET, применяется для запроса конкретного ресурса. Так-же с помощью GET, может быть инициирован некий процесс, при этом, в тело ответа, включается информация о ходе выполнения инициированного запросом действия.
Параметры для выполнения запроса, передаются в URI запрашиваемого ресурса, после символа «?«. Запрос в таком случае выглядит примерно так: GET /some/resource?param1=val1¶m2=val2 HTTP/1.1.
Как установлено в стандарте HTTP, запросы методом GET, являются идемпотентными, то есть, повторная отправка одного и того-же запроса, методом GET, должна приводить к одному и тому-же результату, в случае, если сам ресурс, в промежутках между запросами, изменен не был, что позволяет кэшировать результаты, выдаваемые на запрос методом GET.
Кроме вышесказанного, существуют еще два вида метода GET, это:
условный GET, содержащий заголовки If-Modified-Since, If-Match, If-Range и им подобные,
Частичный GET, содержащий заголовок Range с указанием байтового диапазона данных, которые сервер должен отдать. Данный вид запроса используется для докачки и организации многопоточных закачек.
Порядок работы с этими подвидами запроса GET, стандартами определен отдельно.
Метод HEAD
Данный метод, аналогичен методу GET, с той лишь разницей, что сервер не отправляет тело ответа. Метод HEAD, как правило используется для получения метаданных ресурса, проверки URL ( есть-ли указанный ресурс на самом деле ) и для выяснения факта изменения ресурса с момента последнего обращения к нему.
Заголовки ответа могут быть закэшированы, при несоответствии метаданных и информации в кэше, копия ресурса помечается как устаревшая.
Метод POST
Метод POST, используется для передачи пользовательских данных на сервер, указанному ресурсу. Примером может послужить HTML форма с указанным атрибутом Method=»POST», для отправки комментария к статье. После заполнения необходимых полей формы, пользователь жмет кнопку «Отправить» и данные, методом POST, передаются серверному сценарию, который в свою очередь выводит их на странице комментариев. Таким-же образом, с помощью метода POST, можно передавать файлы.
В отличии от GET, метод POST, не является идемпотентным, то есть неоднократное повторение запроса POST, может выдавать разные результаты. В нашем случае, будет появляться новая копия комментария при каждом запросе.
Если в результате запроса методом POST, возвращается код 200 (Ok) или 204 (No Content), в тело ответа сервера, добавляется сообщение о результате выполнения запроса. Например, если был создан ресурс, сервер вернет 201 (Created), указав при этом URI созданного ресурса в заголовке Location.
Ответы сервера, на выполнение метода POST, не кэшируются.
Метод PUT
Используется для загрузки данных запроса на указанный URI. В случае отсутствия ресурса по указанному в заголовке URI, сервер создает его и возвращает код статуса 201 (Created), если ресурс присутствовал и был изменен в результате запроса PUT, выдается код статуса 200 (Ok) или 204 (No Content). Если какой-то из переданных серверу заголовков Content-*, не опознан или не может быть использован в данной ситуации, сервер возвращает статус ошибки 501 (Not Implemented).
Главное различие методов PUT и POST в том, что при методе POST, предполагается, что по указанному URI, будет производиться обработка, передаваемых клиентом данных, а при методе PUT, клиент подразумевает, что загружаемые данные уже соответствуют ресурсу, расположенному по данному URI.
Ответы сервера при методе PUT не кэшируются.
Метод PATCH
Работает аналогично методу PUT, но применяется только к определенному фрагменту ресурса.
Метод DELETE
Удаляет ресурс, расположенный по заданному URI.
Метод TRACE
При запросе методом TRACE, клиент может увидеть, какие изменения были сделаны в запросе, промежуточными серверами.
Метод LINK
Связывает указанный ресурс с другим ресурсом.
The Status-Code element in a server response, is a 3-digit integer where the first digit of the Status-Code defines the class of response and the last two digits do not have any categorization role. There are 5 values for the first digit:
S.N. | Code and Description | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1 | 1xx: Informational It means the request has been received and the process is continuing. | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
2 | 2xx: Success It means the action was successfully received, understood, and accepted. | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
3 | 3xx: Redirection It means further action must be taken in order to complete the request. | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
4 | 4xx: Client Error It means the request contains incorrect syntax or cannot be fulfilled. | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
5 | 5xx: Server Error It means the server failed to fulfill an apparently valid request. HTTP status codes are extensible and HTTP applications are not required to understand the meaning of all the registered status codes. Given below is a list of all the status codes. Сообщения HTTPСообщения HTTP состоят из текстовой информации в кодировке ASCII, записанной в несколько строк. В HTTP/1.1 и более ранних версиях они пересылались в качестве обычного текста. В HTTP/2 текстовое сообщение разделяется на фреймы, что позволяет выполнить оптимизацию и повысить производительность. Механизм бинарного фрагментирования в HTTP/2 разработан так, чтобы не потребовалось вносить изменения в имеющиеся APIs и конфигурационные файлы: он вполне прозрачен для пользователя. HTTP запросы и ответы имеют близкую структуру. Они состоят из: Запросы HTTPСтартовая строкаЗаголовкиЗаголовки запроса HTTP имеют стандартную для заголовка HTTP структуру: не зависящая от регистра строка, завершаемая ( ‘:’ ) и значение, структура которого определяется заголовком. Весь заголовок, включая значение, представляет собой одну строку, которая может быть довольно длинной. Существует множество заголовков запроса. Их можно разделить на несколько групп: Тела можно грубо разделить на две категории: Ответы HTTPСтрока статуса (Status line)Стартовая строка ответа HTTP, называемая строкой статуса, содержит следующую информацию: Пример строки статуса: HTTP/1.1 404 Not Found. ЗаголовкиЗаголовки ответов HTTP имеют ту же структуру, что и все остальные заголовки: не зависящая от регистра строка, завершаемая двоеточием ( ‘:’ ) и значение, структура которого определяется типом заголовка. Весь заголовок, включая значение, представляет собой одну строку. Существует множество заголовков ответов. Их можно разделить на несколько групп: Тела можно разделить на три категории: Фреймы HTTP/2Сообщения HTTP/1.x имеют несколько недостатков в отношении производительности: Фреймы HTTP сейчас прозрачны для веб-разработчиков. Это дополнительный шаг, который HTTP/2 делает по отношению к сообщениям HTTP/1.1 и лежащему в основе транспортному протоколу. Для реализации фреймов HTTP веб-разработчикам не требуется вносить изменения в имеющиеся APIs; если HTTP/2 доступен и на сервере, и на клиенте, он включается и используется. ЗаключениеСообщения HTTP играют ключевую роль в использовании HTTP; они имеют простую структуру и хорошо расширяемы. Механизм фреймов в HTTP/2 добавляет ещё один промежуточный уровень между синтаксисом HTTP/1.x и используемым им транспортным протоколом, не проводя фундаментальных изменений: создаётся надстройка над уже зарекомендовавшими себя методами. 403 Forbidden vs 401 Unauthorized HTTP responsesFor a web page that exists, but for which a user does not have sufficient privileges (they are not logged in or do not belong to the proper user group), what is the proper HTTP response to serve? What I’ve read on each so far isn’t very clear on the difference between the two. What use cases are appropriate for each response? 21 Answers 21Trending sortTrending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers. It falls back to sorting by highest score if no posts are trending. Switch to Trending sort
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.
From your use case, it appears that the user is not authenticated. I would return 401. 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 TerseUnauthorized 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-DepthThe 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).
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. Checks are usually done in this order: 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): According to RFC 2616 (HTTP/1.1) 403 is sent when:
In other words, if the client CAN get access to the resource by authenticating, 401 should be sent. 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. 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): 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. 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. ez codeПросто о сложном. Описание кодов состояния HTTPКод состояния HTTP — часть первой строки ответа сервера при запросах по протоколу HTTP. Он представляет собой целое число из трёх арабских цифр. Первая цифра указывает на класс состояния. За кодом ответа обычно следует отделённая пробелом поясняющая фраза на английском языке, которая разъясняет человеку причину именно такого ответа. Клиент узнаёт по коду ответа о результатах его запроса и определяет какие действия ему предпринимать дальше. Набор кодов состояния является стандартом, и они описаны в соответствующих документах. В этой статье представлен список и описание кодов состояния HTTP. Коды 3xx (перенаправление)Перечень кодов статуса HTTP, использующихся при перенаправлении запроса (коды 3xx).
Коды 4xx (ошибка клиента)Содержит перечень кодов статуса HTTP, использующихся для обозначения возможных ошибок в клиентском запросе (коды 4xx).
Коды 5xx (ошибка сервера)Перечень кодов статуса HTTP, использующихся для обозначения возможных ошибок сервера (коды 5xx). Pusher LogoShow navigation menu In this tutorial, we will explore what status code means and how to use them. We will build a simple Node.js backend to simulate all the most common status codes of all we will cover. This will help us in two ways: HTTP status codes are the defacto language for describing results of the requests browsers (clients) make to servers. Browsers know what the status codes mean, so they know how to present information to you after you make a request. When you think about it, it makes sense to have defined ways for the server to tell the browser the outcome of a request it made. There are different kinds of browser and different kinds of server configurations to suit specific application needs. If there was no standard communication pattern… anarchy! PrequisitesHow the browser and server talk to each otherBefore you ask “Really? This? Am I three years old?”, I’d urge you to pay attention here, especially if you have not had to build APIs before. Understanding how the browser talks to the server (client-server relationship) in a network will help you make sense of why each status code is important. Servers are like a central location for data (say a restaurant) and clients are the computers that consistently interact with that data (say hungry customers). Different clients, something in thousands or hundreds of thousands, make requests to the server for data. The server does a number of things: The server has to do all of that in split seconds so it can respond to other users who are waiting. The client on the other hand sends a request along with appropriate headers to properly identify who it is and how it wants to receive the information it has requested. If it is trying to request gated information, it has to present some form of access token/key or be able to show it has authorization to access the data it is requesting. The client is usually not very patient as it is pressed for time and resources. If it does not hear from the server after some time, it closes the connection (just like a hungry customer walks away when they have waited too long to be served). However, when the server responds, it sends some code to inform the client of the status of its request. Was it successful? Should the client give it more time? Did it fail? Could it not understand the request? Did the client make a mistake in the request it sent? These are the things the server clarifies with status codes. Of course, client server communication is a lot more complex than that, and there are different tools and protocols that come into play, but that is beyond the scope of this article. What we have looked at now is sufficient to understand the basic status codes we will encounter more frequently when we interact with public APIs.
The informational status codes — 1xxWhat do they do? Short answer — provide information to the browser. They communicate that the request was received and understood, and in most cases, the browser should wait a little as the server processes the information. 100 Continue101 Switching ProtocolsA client can send a request to the server to switch the communication protocol using the Upgrade header. This can be say switching from HTTP/1.1 to HTTP/2 or switching to WebSocket. The server will response with a response code 101 and an Upgrade response header with information on the protocol it upgraded to. The success status codes — 2xxThese are the status codes we encounter every single day. You load a website and it comes up? One of these status codes was used. You submit a form and get the congratulations message? One of these status codes was used. They are used to indicate that our request was successful 200 OkThis response status code indicates that our request was successful. This is used mostly when we request for data from the server and it responds with the data. When you visit the link to a webpage, the browser sends a request to the server to give it the contents of that webpage.
201 CreatedThis is the response code the client gets after sending resource (data) to the server. This resource is stored by the server and upon successfully storing it, the 201 Created response code is returned with the newly created resource as the request body. It can be form submissions, file uploads or other related activities.
202 AcceptedThis is not a very common response code sent by servers. It is used in cases where a request by the client has been received but the server has sent it in for processing. It is a non-committal response in that when the server eventually comes around to process the request, it may or may not act upon it based on if the client has the right to make that request or if the server has the means to handle it. Also, it means the server will not be sending any response afterwards. This can be used in cases when a request is transferred to another server or when a request is batched to be proceed at another time. In such a scenario, the server ought to return an indicator of the current status of the request and a way for the client to monitor the processing of the request. 203 Non-Authoritative InformationThis is also not a very common response code. It signifies that the response the client is getting is not exactly as it was when sent by the server. It can mean that the response has been modified as it passed through a proxy tunnel or some other related third party. The data eventually returned might be a subset or superset of the data returned from the server. 204 No ContentThis response code tells the client (in the case of a user agent) not to change the current document presented to the user. Header information might be updated, but no new content will be sent along. 205 Reset ContentThis response status tells the client to refresh the document sample. 206 Partial ContentThis response code indicates that the request has succeeded and the response body has the requested ranges of data. The server only sends ranges of data when the client sets the Range header in it’s request. Bear in mind that the client must never request a range if it cannot handle the range. If there is only one range, the Content-Type of the whole response is set to the type of the document, and a Content-Range is provided. If several ranges are sent back, the Content-Type is set to multipart/byteranges and each fragment cover one range, with Content-Range and Content-Type describing it. Redirections — 3xxYou see these response codes, you need to know them very well if Search Engine Optimization (SEO) means anything to you and your product. These status codes deal with redirection when a client tries to access a resource. 300 Multiple ChoicesThis status code means the request has more than one possible response. The client is to choose one of them. There is no standardized way of choosing so this is rarely used. In case you see it, look for the Location header which usually contains the servers preferred choice. 301 Moved PermanentlyThis is arguably the most important of the redirection status codes. When not used properly, it can interfere with your SEO and bury your website forever. It can also created very bad user experience and increase the churn you experience on your website. This tells the client that the resource they seek has been moved permanently, and then presents the URL to the new location of the resource. This does two things: tells the client where to find the resource and also helps the client know where to go the next time they need the resource. The new location for the resource is specified by the Location header.
302 Found303 See Other304 Not ModifiedWhen you have previously fetched a cacheable content, this status code comes in handy. It tells the client that the resource they are trying to fetch has not changed, so they should retain the copy they have. This will come in handy if you are building a system like a newsfeed and you always want to check for new updates. It will prevent you fetching old data and reloading the client browser unnecessarily. 307 Temporary RedirectWe have already talked about this earlier that it will be okay to skip it right? Well, this response code is sent by the server when it intends to explicitly tell the client to maintain the method originally used for the request. It works just like 302 except it adds a very clear directive not to change anything. Best thing to use in case you have stubborn clients who always change request methods on redirect 🙄. 308 Permanent RedirectClient Error — 4xxThese are the status codes used to inform the client that it made a mistake in the request it made. Was a required field not supplied? Did they send the wrong data format? Are they not authorized to access the resource they are looking at? Do they need to confirm their identity? All of these things are handled by these status codes. Now, let’s dig into them. 400 Bad RequestI have to admit, this is my favorite status code 😂. Every time I get slammed with 400 Bad Request red error on my console, I first look up and ask “What kind of life did I choose?” before I proceed to investigate it. Bad requests occur when the client sends a request with either incomplete data, badly constructed data or invalid data. Many times, it could be the fault of the developer who did not specify properly what kind of data they expect. Be that as it may, it happens because the data you sent to a request is incorrect. 401 UnauthorizedThis response in simple terms means the client needs to authenticate itself before it completes the request. Authentication here could be providing access-token in the case of OAuth or Authorization token in the case of jwt based auth system or even API keys. Anything that the server needs to identify who is making a request has to be sent for the request to be completed. 403 ForbiddenThis error occurs when a client tries to access a resource it is not permitted to. This is not the same as 401 Unauthorized (just see them as fraternal twins 😃). An authenticated client can be Forbidden from accessing a resource just as an unauthenticated client can. Many times, the client only gets 403 Forbidden after it has been authenticated, as the system will have to ensure who the client is first before forbidding or granting them access to the resources. 404 Not Found405 Method Not AllowedStandard practice is that when a server sends a 405 response code, it includes a list of methods supported for accessing the resource in question. 406 Not AcceptableThis is a rarely used error code. It indicates that the server cannot produce a response that matches the request the user made, and the server is not willing to send a default response. You can learn more about it on Mozilla Developer Docs. 407 Proxy Authentication Required408 Request TimeoutThis response code is sent by the server when it wants to close an idle connection opened by the client. The client may not have completed its request and may be taking so much time doing it. The standard is that a server will send a close Connection header in the response field along with the response code.
409 ConflictThis response is sent by the server when a request conflicts with the servers internal operations. A good example of such conflict is trying to update a resource on the server with an older version. 410 GoneWe already mentioned that this status code shows that the resource the client wishes to access has been permanently deleted. 411 Length RequiredThe server returns this status code if it requires that Content-Length header is set along with the request, and the client did not set it. 412 Precondition Failed413 Payload Too LargeThe request data is too big for the server to handle 😃. In more technical terms, the size of the payload may have exceeded the limit specified by the server. 414 URI Too LongJust shorten the URL and all will be fine. Realistically, this only occurs when you have a lot of things appended to a URL when constructing a GET request with a lot of parameters. 415 Unsupported Media TypeThis is what it is. The server does not support the media type requested by the client. 416 Range Not SatisfiableThe server can’t fulfill the Range specified in the request header. It could mean the Range is requesting more data than the server can give. Think array index out of bounds and you will get the picture. 417 Expectation FailedWhen the server cannot meet the expectation contained in the Expect request header field, it sends this response. 418 I’m a teapotI honestly do not know why this was ever made, but it is a response code for April Fool’s day prank. It means the server refuses to brew coffee because it is a tea pot 🤣. You can read more about this prank on WikiPedia. 419 Authentication TimeoutAt the moment, this is only obtainable with Laravel applications. It means the csrf token of the application has expired. The csrf token in Laravel is sent with every form submission or request to resources protected by authentication and more. 426 Upgrade RequiredThe server returns this response code when it is unwilling to communicate with the client via a certain protocol, but is willing to continue communication if they change protocols. Yep, I agree… These servers are just full of themselves. The server sends an Upgrade header with this response to provide a list of protocols it is willing to use in continuing communication. 428 Precondition RequiredThis response is sent by the server when it requires a request to be conditional. A conditional request is a request where the result might change based on a validation of the resource requested. Conditional requests are useful in scenarios like downloads where a client can pause and resume at any time. For such requests, a required precondition header like If-Match is required. If the precondition header does not match what the server has, then a 412 Precondition Failed is sent instead. 429 Too Many RequestsThis status code is sent when a user has sent too many requests than allowed in a given period of time. It is common with APIs that limit usage by time period. 431 Request Header Fields Too LargeThe server is just unwilling to process the request because it feels the headers of the request are too large. That is all. The client can reduce the headers and try the request again. 451 Unavailable For Legal ReasonsThe resource the client has requested cannot be served for some legal reasons. Serving it to that user will mean breaking the law. In practice, you will rarely encounter most of the error codes, but it is good you know them. They become more common with increasing complexity of the applications you build. Error — 5xxThese errors occur due to no fault of the client. The servers are to be blamed here and there is nothing the client can do to get their desired response. 500 Internal Server Error501 Not ImplementedThe server sends this code when you have made a request to it with a request method it does not know or have the capacity to resolve. Servers are required to implement only GET and HEAD methods, so you might send a PUT or PATCH request and the server will not be able to handle it. This is not the same as 405 Method Not Allowed because with 405 the server clearly understands the request but cannot respond to it until the method is changed. With 501 the server cannot understand the method used and is therefore incapable of providing any response. 502 Bad GatewayThe server sends this code when it is acting as a proxy server and/or fetching data from an external resource and it gets an invalid response from that external source. 503 Service UnavailableThis is a common server error code that you can get. It means the server might be down and therefore, is not ready handle the request at that time. This might be a result of an ongoing maintenance or an overload on the server. This is a temporal situation, so if you implement caching in your application, you might want to not cache this response. 504 Gateway TimeoutThe direct sibling to 502 😃. The server sends this response code when it is acting as a gateway and the external resource does not provide it with a response in time. 505 HTTP Version Not SupportedThis status code indicates the HTTP version the client used for the request is not supported by the server. Think making a HTTP/1.1 call to a server when the server only deals in HTTP/2 😎. 511 Network Authentication RequiredWhere there is a difference is that 401 tells the client directory it needs to be authenticated but 511 means the proxy network cannot access the external resource because of lack of proper authorization. ConclusionIf you followed this tutortial, then you my friend are more than ready to build very amazing web applications. A proper understanding of these status codes makes all the difference in the user experience of your application. Understanding them means you can efficiently design your application to handle errors or issues that may arise gracefully. If you are a developer building an API, you can more easily send the appropriate responses for the scenarios your users encounter as they use your application. This is equally very important in building useful applications. In the next tutorial, we will look it is consuming APIs and experiencing the status codes we have received. 401 Unauthorized vs 403 Forbidden: Which is the right status code for when the user has not logged in? [duplicate]After lots of Googling and Stackoverflowing, it still isn’t clear to me because many articles and questions/answers were too general (including 403 Forbidden vs 401 Unauthorized HTTP responses which was not specifically for my use-case). Question: What’s the proper HTTP Status Code when the user has not logged in and requests to see some pages that should be shown only to logged-in users? 3 Answers 3Trending sortTrending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers. It falls back to sorting by highest score if no posts are trending. Switch to Trending sort The exact satisfying one-time-for-all answer I found is: 401 UnauthorizedWhile we know first is authentication (has the user logged-in or not?) and then we will go into authorization (does he have the needed privilege or not?), but here’s the key that makes us mistake:
Back when the HTTP spec (RFC 2616) was written, the two words may not have been as widely understood to be distinct. It’s clear from the description and other supporting texts that 401 is about authentication. So maybe, if we want to rewrite the standards! focusing enough on each words, we may refer to the following table: It depends on the mechanism you use to perform the login. The spec for 403 Forbidden says:
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. While 401 Unauthorized is not defined in the main HTTP status codes spec but is in the HTTP Authentication spec and says:
So if you are using WWW-Authenticate and Authorization headers as your authentication mechanism, use 401. If you are using any other method, then use 403. What’s the appropriate HTTP status code to return if a user tries logging in with an incorrect username / password, but correct format?The answer in the thread above states that «For instance if the URI is supposed to have an ISO-8601 date and you find that it’s in the wrong format or refers to February 31st, then you would return an HTTP 400. Ditto if you expect well-formed XML in an entity body and it fails to parse.» However, what happens if the user submitted correctly formatted data? By this I mean, the user submitted a plain alphabetical string / text for the username and password (which is perfectly valid for my application). The only issue is that the password did not match with the username. In this case, 400 will be incorrect because it is perfectly valid syntax and well-formed. A 401 would be incorrect (as suggested here: Which HTTP status code to say username or password were incorrect?) because the user is not trying to access any page, he is simply trying to login and entered data which does not match. If you look back at the first post I linked to, the second answer states that 422 is the correct response (and it looks correct to me), however, I am using Django Rest Framework and 422 is not part of the status codes (a list of the status codes which are part of DRF can be found here: http://www.django-rest-framework.org/api-guide/status-codes/#client-error-4xx) 404 also doesn’t look right because the data is successfully accepted and not refused. With that said, what is the real correct response which should be used? 4 Answers 4Trending sortTrending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers. It falls back to sorting by highest score if no posts are trending. Switch to Trending sort If you are strictly using the HTTP authentication framework provided by RFC 7235 for your REST API, the correct HTTP code would actually be 401. From the RFC:
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). Your REST API should employ an authentication scheme of some sort in order to return a valid 401 response to your client. Another pertinent section from RFC 7235, page 4:
A higher-level response, such as a rendered login page for a visual user (redirected from a protected resource via 302), would be better served with the 200 status code (per @KernelDeimos’ answer, for example). Since login pages are typically their own resource (e.g. /login?redirect=original-resource ), the unauthenticated user is still authorized to see this page, even if they provide an incorrect username/password. Then, you redirect the authenticated user back to the resource, at which point would show 200 if allowed, or 403 if the user is forbidden to view the resource. The area where 401 could come into play with a visual login page is a front-end library that leverages the REST API using XHR requests, then relay the 401 response from the REST API back into a meaningful format on the login page. Коды ответов HTTP и ошибки сервераВсе коды состояния или http-статусы состоят из трех цифр. Они помогают понять, чем в итоге обернулся запрос между пользователем и сервером — успехом или ошибкой. Некоторые из рассматриваемых ниже кодов вам хорошо знакомы, но есть и совсем редкие. Всего существует пять групп серверных ответов, которые определяют класс состояния по первой цифре. Так можно сразу определить формат ответа от информационного до сообщения об ошибке. Информационные кодыДанная группа отвечает за передачу данных. Коды этого типа свидетельствуют о том, что запрос принят сервером и обрабатывается. 100 — Continue — Временный код ответа, означающий начало принятия запроса к его последующей обработке. 101 — Switching Protocols — Сообщает о переключении сервера на протокол, которые был указан в заголовке Upgrade запроса клиента. 102 — Processing — Информация о том, что запрос принят сервером и находится в обработке, но этот процесс еще не завершен. 103 — Early Hints — Используется для предварительной загрузки данных пока сервер формирует полный ответ. Успешная обработка запросаКоды группы сообщают, что запрос не только принят сервером, но и успешно обработан. 200 — OK — Один из самых популярных ответов. Он свидетельствует о том, что обмен данными между клиентом и сервером прошли успешно. Именно код ответа 200 ждут от ресурса, чтобы проверить, что все работает как надо: сайт загружен, файл открывается и т.д. 201 — Created — Информирует об успешном создании нового ресурса в результате выполнения запроса. Например, была создана новая страница. Если сервер по каким-то причинам не смог обработать запрос и ресурс не был создан, то код ответа будет 202. 202 — Accepted — Сообщает, что сервер принял запрос, но не завершил его обработку. 203 — Non-Authoritative Information — Отвечает об успешной обработке запроса с оговоркой на то, что передаваемая информация была предоставлена не из исходного сервера, а другого источника (например, резервной копии) и может быть неактуальной. 204 — No Content — Сообщает об успешном принятии и обработке запроса, а также о том, что у сервера нет содержимого для отправки пользователю. 205 — Reset Content — Сервер передает пользователю ответ в виде требований к сбросу введенных данных. Например, о необходимости очистить форму с заполненными до этого данными. 206 — Partial Content — Свидетельствует о частичном выполнении GET-запроса сервером, возвращая только запрошенную пользователем часть контента. Этот код встречается при использовании кэширования. Коды редиректовДанная группа кодов состояния сообщает о перенаправлении пользователя с его согласием или без него. 300 — Multiple Choices — Ответ срабатывает при условии, что по указанному запросу существует несколько вариантов URL. При таком варианте пользователь или User-agent должен выбрать альтернативный адрес. 301 — Moved Permanently — Свидетельствует о перемещении ранее проиндексированного URL на новый адрес. Это команда роботу индексировать новую страницу вместо старой. 301 редирект также используемся вебмастерами для перенаправления сайта с http://www.mixtelecom.ru на http://mixtelecom.ru. Применяется при переходе на защищенный протокол с HHTP на HTTPS. Используется для защиты доступа к внутренним файлам, например, /index.php переправляется на главный адрес сайта. Некоторые хостинги и CMS автоматически включают данные редиректы при выборе соответствующих опций при настройке сайта. 302 — Found, 302 Moved Temporarily — Сообщает, что ранее проиндексированный URL был временно перемещен по другому адресу. При этом страница остается в индексе, а в ответе указывается новый адрес запрашиваемого URL. 303 — See Other — Указывает пользователю, что запрошенная страница находится по другому адресу с запросом GET. 304 — Not Modified — Показывает, что запрашиваемая страница или объект не были изменены с момента последнего обновления кэша данного документа. 305 — Use Proxy — Сообщает пользователю, что запрашиваемый ресурс доступен только через прокси. Данные по прокси указаны в ответе сервера. 307 — Temporary Redirect — Код схож с 302, сообщая о временном перемещении ресурса на другой адрес. Разница заключается в способе обращения к ресурсу, который должен быть получен тем же методом, что и предыдущий запрос. Ошибки клиентаКоды состояний данной группы сообщают об ошибках клиента, при которых сервер не может вызвать запрашиваемый результат. 400 — Bad Request — Ошибка свидетельствует от том, что сервер не понял запрос пользователя из-за синтаксической ошибки. 401 — Unauthorized — Сообщает о необходимости быть авторизованным для получения запрашиваемого доступа. Возникает при неправильном вводе данных пользователем при авторизации. 403 — Forbidden — Запрет доступа к запрашиваемой странице. Доступ может быть ограничен настройками индексации или запрещен для определенных IP. 404 — Пожалуй, самая распространенная ошибка. Сообщает о том, что запрашиваемая страница не найдена. Самая частая причина — ошибка в написании адреса. Когда что-то пошло не так и пользователь не попал по запрашиваемому адресу куда хотел, позаботьтесь, чтобы на сайте была соответствующая страница для ошибки 404. На ней должна быть ссылка на главную страницу или меню ресурса, находиться поиск по сайту или контакты для связи. Если запрашиваемый URL был изменен, то настройте 301-редирект со старого адрес страницы на обновленный. 405 — Method Not Allowed — Сообщает, что в запросе используется метод, который не поддерживается сервером. 406 — Not Acceptable — Указывает, что запрашиваемый пользователем контент не может быть распознан. Причины могут быть в кодировке, методе сжатия или формате объекта. 407 — Proxy Authentication Required — Сообщает, что доступ может быть предоставлен только при авторизации через прокси-сервер. 408 — Request Timeout — Сервер прервал соединение с пользователем из-за слишком долгого ожидания. Данный ответ не возвращается если пользователь принудительно отменил запрос или соединение прервалось по иным причинам. 409 — Conflict — Посылаемый пользователем запрос вызывает конфликт с сервером или другим обращением. 410 — Gone — Ответ сервера при запросе к странице или объекту, который был удален и более недоступен. 411 — Length Required — Отказ сервера на обработку запроса если в нем не указан Content-Length заголовка. 413 — Request Entity Too Large — Сервер не может обработать обращение из-за слишком большого размера запроса. 414 — Request-URL Too Long — Сервер не может обработать обращение если в запросе указан слишком длинный URL. 415 — Unsupported Media Type — Формат запроса пользователя не может быть обработан. Такое встречается при загрузке данных неподходящего формата. 416 — Requested Range Not Satisfiable — Отказ сервера на выполнение запроса из-за некорректного значения поля Range. 417 — Expectation Failed — Отказ сервера на выполнение запроса из-за некорректного значения поля Expect. 422— Unprocessable Entity — Сервер принял и распознал запрос, но не может его выполнить из-за наличия логической ошибки. 423 — Locked — Запрашиваемая пользователем страница заблокирована. Как правило, это делается для защиты содержимого данной страницы или объекта. 424 — Failed Dependency — Выполнение текущего запроса зависит от исхода других связанных с ней операций. Если условия не будут соблюдены, то соединение будет разорвано. 426 — Upgrade Required — Ошибка указывает на необходимость обновить протокол. Встречается, когда сервер запрашивает https-соединение, которое не может быть предоставлено клиентом. 429 — Too Many Requests — Возникает при превышении лимита отправляемых пользователем запросов за короткий промежуток времени. Часто используется настройками безопасности. Ошибки сервераВ эту группу входят коды ошибок со стороны сервера, когда по тем или иным причинам он не способен обработать запрос или выполнить требуемую операцию. 500 — Internal Server Error — Код оповещает о возникшей внутренней ошибке сервера или его аварийном отказе. 501 — Not Implemented — Сервер столкнулся с запросом, который не смог распознать. Либо запрос не поддерживается и не может быть обработан. 502 — Bad Gateway — Сообщает о неправильном получении ответа вышестоящего сервера. Частая причина — несогласованные протоколов между шлюзом и сервером (ошибки DNS, прокси, хостинга). Если ваш сайт выдает ошибку 502, то вероятнее всего вносились правки или совершались обновления системы. Просмотрите логи для выявления причины. Если на сайте не было никаких работ и апдейтов, то проверьте ресурсы памяти, процессора, php-лимиты сервера. Возможно их недостаточно для корректной обработки запросов. Причинами также могут быть подключенные CDN или anti-DDoS сервисы. Обратитесь в техподдержку. 503 — Service Unavailable — Указывает на временную недоступность сервера. Причиной может быть его перезагрузка, техническое обслуживание, обращение слишком большого количества пользователей при наличии подобных ограничений. Как правило, сообщение об ошибке содержит параметр Retry-After, информирующий о времени восстановления штатной работы ресурса. 504 — Gateway Time-out — Истек срок ожидания ответа от вышестоящего сервера. Возможные причины: недостаток ресурсов, неполадки с сетевым соединением, ошибки HTTP протокола, настроен слишком короткий срок ожидания. 505 — HTTP Version Not Supported — Используемая в запросе версия протокола HTTP не поддерживается сервером. Встречается при использовании устаревшего формата HTTP-протокола. 506 — Variant Also Negotiates — Сервер не может обработать запрос из-за его неправильной настройки. Сервер зацикливает ответ на себя, выдавая ошибку. 507 — Insufficient Storage — Означает нехватку места на сервере для обработки запросов пользователя. Нужно освободить или увеличить память, либо обратиться в техническую поддержку. 508 — Loop Detected — Ошибка возникает в связи с бесконечным перенаправлением. При обработке запроса возникает петля, что приводит к завершению операции. 509 — Bandwidth Limit Exceeded — Превышен установленный лимит потребления трафика. Ошибка актуальная для интернет-каналов с ограничением по трафику. 510 — Not Extended — Сервер не поддерживает и не может отработать запрашиваемое пользователем расширение. В теле ошибки может быть приведен список доступных расширений. 511 — Network Authentication Required — Сообщает о необходимости авторизации для доступа к сети. Например, если пользователь не авторизовался при подключении к Wi-Fi. Благодаря приведенным выше кодам ответов намного легче понимать статус сервера при взаимодействии с ним. На практике большинство из них используются в виде указаний роботам по работе с сайтом и порядку его индексации. Сервисы мониторинга и технического анализа сайтов также ориентируются на коды ответов сервера для определения корректной работы ресурса. Вебмастеры могут опираться на статусы состояния в рамках настройки и поддержания работы сайтов. Системные администраторы могут понимать в чем причина неполадок и быстрее устранять возникшие неполадки. Если у вас возникли сложности, которые не получается решить самостоятельно, — воспользуйтесь услугой системного администрирования. everyone. I’m new to Angular 2 and Spring Framework. I’m trying a simple get request with an authorization header (basic auth). I’m using Spring Boot (1.2.6.RELEASE), which can also be relevant. My CORS configuration looks like this. And here’s what it looks like from the client side
Please help, i don’t know what i’m missing. I checked around a lot of posts already but couldn’t get there. 3 Answers 3Trending sortTrending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers. It falls back to sorting by highest score if no posts are trending. Switch to Trending sort This could be very late but this could solve some ones problem, after long hours i found the answer avoid filtering and set status 200 when http method is OPTIONS If there is anyone getting into the similar situation working around with Spring Boot, Spring Security and clients like angular 2/4, I’ve posted the findings here. For those who are looking for a short answer, you have to configure two things: With Spring Boot, the recommended way to enable global CORS is to declare within Spring MVC and combined with fine-grained @CrossOrigin configuration as: Then, while working with Spring Security, you have to enable CORS at Spring Security level as well to allow it to leverage the configuration defined at Spring MVC level as: Why my httpwebrequest post to myhandler.ashx is rejected with status code 401Application Trace (trace.axd) shows the following as my last 3 entries: Here is a snippet of code from the UploadHandler.ashx file (but this doesn’t appear to be reached): Both default.aspx and UploadHandler.ashx are in the root of a virtual directory on my localhost; the directory security is currently set to «Anonymous access» CHECKED and «Integrated Windows authentication» CHECKED. When I click the «View Details» link on the trace.axd display, I see all the data in the Forms collection that I expect to see and hope to process but this 401 seems to be stopping everything. I could post the code for my little function called BuildFormData() if useful. EDIT: Revised handler as follows (has had no effect; same error occurs): 2 Answers 2Trending sortTrending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers. It falls back to sorting by highest score if no posts are trending. Switch to Trending sort Have you tried turning off Integrated Windows Auth and just leaving anonymous checked? Does it make a difference? My response: This is actually a good thing. This means we’re getting closer to what is going on. If you’re getting that error message and the only thing you have enabled is anonymous authentication via IIS, that means that the ASP.NET impersonation user doesn’t have NTFS permissions on the files in question. I’m not sure if you are on XP or Win 2k3, but now you want to check and make sure that either the ASPNET (XP) or Network Service (Win 2k3) users have at least read access on the files in question. Make sure that user has at least that level of access and then let me know how it goes. Update: I don’t know why I didn’t think of this before. You may need to set credentials on your HttpWebRequest. To use the credentials of the current user, try adding this to your request. If you need to add different credentials you can try Network Credentials Angular 2 REST request HTTP status code 401 changes to 0I’m developing an Angular2 application. It seems when my access-token expires the 401 HTTP Status code gets changed to a value of 0 in the Response object. I’m receiving 401 Unauthorized yet the ERROR Response object has a status of 0. This is preventing me from trapping a 401 error and attempting to refresh the token. What’s causing the 401 HTTP status code to be changed into HTTP status code of 0? Here’s screenshot from Firefox’s console: This code resides in a custom http service that extends Angular2’s HTTP so I can intercept errors in a single location. In Google Chrome, I get this error message: XMLHttpRequest cannot load https://api.cloudcms.com/repositories/XXXXXXXXXXXXXXXX/branches/XXXXXXXXXXXXXXXX/nodesXXXXXXXXXXXXXXXX. No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘http://screwtopmedia.local.solutiaconsulting.com’ is therefore not allowed access. The response had HTTP status code 401. This is confusing because I am including ‘Access-Control-Allow-Origin’ header in request. Here’s a picture of results received in Google Chrome: I’ve tried accessing ‘WWW-Authenticate’ Response Header as a means to trap for 401. However, the following code returns a NULL: It’s puzzling that I’m getting a CORS issue because I’m not getting any CORS errors when a valid access token is provided. How do I trap for 401 HTTP status code? Why is 401 HTTP status code being changed to 0? Thanks for your help. 7 Answers 7Trending sortTrending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers. It falls back to sorting by highest score if no posts are trending. Switch to Trending sort The issue is related to CORS requests, see this github issue
means that ‘Access-Control-Allow-Origin’ is required in the response headers. If cloudcms.com do to not set the Access-Control-Allow-Origin in 401 response, then nothing much you can do. You properly have to open support ticket with them to confirm if that is normal behavior. javascript in browsers(FF, Chrome & Safari) I tested won’t receive any info if CORS error occur, other than status 0. Angular2 has no control of it. I created a simple test and get the same result as yours:
I found the issue for a while now but I forgot post here a reply. EVERY response, even Error 500, must have the CORS headers attached. If the server doesn’t attach the CORS headers to the Error 500 response then the XHR Object won’t parse it, thus the XHR Object won’t have any response body, status, or any other response data inside. Result from Firefox network monitor seems supporting the above reason. Javascript request will receive empty response. Plain url request(copy&paste the link in the address bar) will get response body Javascript use XHRHttpRequest for http communication. When a XHR reply arrive, the browser will process the header, that’s why you will see those 401 network messages. However, if the XHR reply is from a different host then the javascript AND the response header contain no CORS header(eg Access-Control-Allow-Origin: * ), the browser will not pass any info back to the XHR layer. As a result, the reply body will be completely empty with no status(0). I tested with FF 48.0.1, Chrome 52.0.2743.116 and Safari 9.1.2, and they all have the same behavior. Use browser network monitor to check response header for those 401 Unauthorized entries, it is very likely that there is no Access-Control-Allow-Origin header and causing the issue you are facing. This can be a bug or by design on the service provider side. What do the HTTP status codes, such as 403, 404, 500, mean?For every request from a webbrowser the server responds with a status code. If there was a error, you can get additional information about the error. You can find the most frequent error codes and a brief description in the list below. The server can’t process the request due to clientside errors. The 401 status code indicates that the HTTP request has not been applied because it lacks valid authentication credentials (usually username and password) for the target resource. If the request included authentication credentials, the 401 response indicates that authorization has been refused for those credentials. Please check if your username and password are correct. Sometimes user authentication was provided, but the authenticated user is not permitted to view the content of the folder or file. Other times the operation is forbidden to all users. Sometimes this error occurs if there are too many connections at the same time. The easyname support team can explain you this issue in depth. This error message is shown when a site or folder on a server are requested but cannot be found at the given URL. Please check your input. Please note that this error can also appear if there is no start file (index.php or index.html). The IP address is automatically unblocked after some time and access to the web application is then possible again. The time period depends on the severity of the violation. Another possibility to make it accessible again is to deactivate the application firewall. It can be deactivated either for the entire web hosting or only for individual subdomains. For the entire web hosting: Go to the menu item [Web Hosting] then to [Web Server Settings]. In the left-hand panel General, switch off «Mod Security» and click on the «Save» button. This option causes new subdomains to be created without protection by the application firewall. For already existing subdomains, the protection must be removed manually. For individual subdomains: Go to the menu item [Web Hosting] then [Subdomains]. Click on the blue pen symbol (Edit) next to the corresponding subdomain. Then click on the link Advanced Options. A menu will open in which you will see a tick next to «Activate application firewall». Click on the tick to deactivate the application firewall. Save your settings by clicking on the «Save» button. Disabling the Application Firewall will make your web application or website more vulnerable to attackers. It is therefore not recommended to disable it. The server took longer than it’s allocated timeout window. In this case the server terminates the connection. The HTTP 429 Too Many Requests response status code indicates the user has sent too many requests in a given amount of time. A Retry-After header might be included to this response indicating how long to wait before making a new request. For example if more than 50 requests are received from the same IP address (cumulative hits) within the same second, our server will block that IP for the next 10 minutes as a security measure. This HTTP status code indicates, that under the specified URL there’s no content to be displayed. This means, that the server is currently unavailable or the server is overallocated. You can check the file php_error.log as described for the status code 500. Should you not find helpful error messages in the logfile, please try changing the session_cache to the option filesystem, you can do this in the easyname control panel if you navigate to [Web Hosting] → [PHP settings] and click the link «Settings». Please note that this change will take up to 15 minutes to take effect, so please try waiting 15 minutes before trying to call up your site and refresh it. This means, that the server has not responded within the specified time period. Axios post request failed with status code 401Hi so Im trying to pull data from https://opentimetable.dcu.ie/ based on the course code so like CASE3, so im trying to pull the weeks timetable, but im new to axios and my post request is failing because of the headers i believe and im not sure why I thought i was doing it correct? im basically trying to get the course identity in the api in the post request below 1 Answer 1401 error status response code indicates that the request lacks valid authentication credentials. So I was doubtful about your authorization token. However, using postman, I got 200 ok. So the token is fine. So my guess is authorization was failing because of the way you are passing headers. Anyways, Here the code, let me know if it works. I’m trying to return 401 response status in my AngularJS app. But in console that I see, it returns -1 What I use in php: Also in codeigniter: 1 Answer 1You are making a cross origin request from XMLHttpRequest. In a simple case, this means that the server has to grant permissions to the JavaScript before the browser will give the data to the JavaScript. This is not a simple case. You are making a complex request which requires preflight authorisation. Before making the POST request you want to make, the browser is making an OPTIONS request asking for permission. The server is responding to the OPTIONS request with a 401 response. The error message tells you this explicitly:
The browser is then refusing to make the POST request at all. You need to respond to the OPTIONS request with a 200 status (and appropriate CORS permissions headers). Then the browser will make a POST request (which you can reject with a 401 if you like). Is it OK to return a HTTP 401 for a non existent resource instead of 404 to prevent information disclosure?Inspired by a thought while looking at the question «Correct HTTP status code when resource is available but not accessible because of permissions», I will use the same scenario to illustrate my hypothetical question. Imagine I am building a a carpooling web service. Suppose the following retrieves the current position of user «angela». Only angela herself and a possible driver that is going to pick her should be able to know her location, so if the request is not authenticated to an appropriate user, a 401 Unauthorized response is returned. Also consider the request when no user called john has registered with the system. There is no john resource let alone a resource for john’s location, so this obviously returns a 404 Not Found. Or does it? What if I don’t want to reveal whether or not john is registered with the system? (Perhaps the usernames are drawn from a small pool of university logins, and there is a very militant cycling group on campus that takes a very dim view of car usage, even if you are pooling? They could make requests to the URL for every user, and if they receive a 401 instead of 404, infer that the user is a car pooler) Does it make sense to return a 401 Unauthorized for this request, even though the resource does not exist and there is no possible set of credentials that could be supplied in a request to have the server return a 200? 10 Описания кодов состояния (Status Code Definitions).Каждый код состояния, описанный ниже, включает описание метода (или методов), за которым он может следовать и метаинформации, требуемой в ответе. Этот класс кодов состояния указывает предварительный (временный) ответ, состоящий только из строки состояния (Status-Line) и опциональных заголовков, и завершающийся пустой строкой. Так как HTTP/1.0 не определял никаких 1xx кодов состояния, серверы НЕ ДОЛЖНЫ посылать 1xx ответы HTTP/1.0 клиентам, за исключением экспериментальных условий. 10.1.1 100 Продолжать, Continue.Клиент может продолжать запрос. Этот промежуточный ответ используется, для того, чтобы сообщить клиенту, что начальная часть запроса была получена и еще не отвергнута сервером. Клиенту СЛЕДУЕТ продолжить посылку оставшихся данных запроса или, если запрос уже был выполнен, игнорировать этот ответ. Сервер ДОЛЖЕН послать заключительный ответ после того, как запрос будет выполнен. 10.1.2 101 Переключение протоколов, Switching Protocols.Сервер понимает и желает выполнить запрос клиента, если протокол прикладной программы в этом соединении будет изменен на тот, который указан в поле заголовка сообщения Upgrade (раздел 14.41). Сервер переключит протокол на тот, который определен в поле заголовка ответа Upgrade непосредственно после пустой строки, которая завершает ответ с кодом состояния 101. Протокол должен быть переключен только тогда, когда это принесет выгоду. Например, переключение на более новую версию HTTP выгодно по сравнения с использованием более старых версий, а переключение на синхронный протокол реального времени может быть выгодно при предоставлении ресурсов, которые используют такие возможности. Этот класс кодов состояния указывает, что запрос клиента был успешно получен, понят, и принят. 10.2.1 200 OK.Запрос был удачно выполнен. Информация, возвращаемая с ответом зависит от метода, используемого в запросе. Например: GET в ответе представлен объект, соответствующий запрошенному ресурсу; HEAD в ответе представлены поля заголовка объекта (entity-header), соответствующие запрошенному ресурсу. Тело сообщения (message-body) отсутствует; POST в ответе представлено описание объекта или содержится результат действия; TRACE в ответе представлен объект, содержащий сообщение запроса, полученого конечным сервером. 10.2.2 201 Создан, Created.Запрос был выполнен и в результате был создан новый ресурс. Новый созданный ресурс может быть вызван по URI (одному или нескольким), возвращенным в объекте ответа; наиболее специфический URL для ресурса отдается в поле заголовка Location. Первоначальный сервер ДОЛЖЕН создать ресурс перед возвратом кода состояния 201. Если действие не может быть выполнено немедленно, сервер должен возвратить ответ с кодом состояния 202 (Принято, Accepted) вместо 201. 10.2.3 202 Принято, Accepted.Запрос был принят для обработки, но обработка не была завершена. В конечном счете запрос МОЖЕТ быть, а МОЖЕТ и не быть выполнен, поскольку он МОЖЕТ быть отвергнут при фактической обработке. Не имеется никакой возможности вторичной посылки кода состояния от асинхронной операции типа этой. Ответ с кодом состояния 202 преднамеренно уклончив. Цель его состоит в том, чтобы позволить серверу принять запрос для некоторого другого процесса (возможно пакетно-ориентированного процесса, который выполняется только один раз в день) и не требовать при этом, чтобы соединение агента пользователя с сервером сохранялось до завершения процесса. Объекту, возвращенному с этим ответом СЛЕДУЕТ содержать индикатор текущего состояния запроса и либо ссылку на монитор состояния, либо некоторую оценку времени, когда пользователь может ожидать завершения выполнения запроса. 10.2.4 203 Не авторская информация, Non-Authoritative Information.10.2.5 204 Нет содержимого, No Content.Ответ с кодом состояния 204 НЕ ДОЛЖЕН содержать тела сообщения, и, таким образом, всегда завершается первой пустой строкой после полей заголовка. 10.2.6 205 Сбросить содержимое, Reset Content.Сервер выполнил запрос, и агенту пользователя СЛЕДУЕТ отменить просмотр документа, который инициировал запрос. Этот ответ предназначен прежде всего для того, чтобы позволить ввод данных, осуществляемый пользователем, с последующей очисткой формы, в которой сделан ввод, так, чтобы пользователь мог легко инициировать следующее действие ввода. Ответ НЕ ДОЛЖЕН содержать объект. 10.2.7 206 Частичное содержимое, Partial Content.Сервер выполнил частичный GET запрос ресурса. Запрос должен содержать поле заголовка Range (раздел 14.36), указывающее желаемый диапазон. Ответ ДОЛЖЕН содержать либо поле заголовка Content-Range (раздел 14.17), указывающее диапазон, включенный в ответ, либо тип содержимого (Content-Type) должен быть равным «multipart/byteranges», а поля Content-Range должны содержаться в каждой части. Если «multipart/byteranges» не используется, поле заголовка Content-Length в ответе ДОЛЖНО соответствовать фактическому числу октетов (OCTETs), переданных в теле сообщения (message-body). Кэш, который не поддерживает заголовки Range и Content-Range НЕ ДОЛЖЕН кэшировать ответы с кодом состояния 206. Этот класс кодов состояния указывает, что для выполнения запроса агенту пользователя необходимо придпринять дополнительное действие. Требуемое действие МОЖЕТ быть выполнено агентом пользователя без взаимодействия с пользователем, тогда и только тогда, когда во втором запросе используется метод GET или HEAD. Агенту пользователя НЕ СЛЕДУЕТ автоматически перенаправлять запрос более 5 раз, так как такие переадресации обычно указывают бесконечный цикл. 10.3.1 300 Множественный выбор, Multiple Choices.Запрошенный ресурс имеет несколько представлений, и можно использовать любое из перечисленных. Каждое представление имеет свое расположение и информацию для агента по управлению диалогом (раздел 12), представленную таким образом, что пользователь (или агент пользователя) может выбрать наиболее подходящее представление и перенаправить запрос к нему. Если запрос был отличен от HEAD, то ответу СЛЕДУЕТ содержать объект, включающий список характеристик и адресов, из которого пользователь или агент пользователя может выбрать один наиболее подходящий. Формат объекта определяется медиа типом, указанным в поле заголовка Content-Type. В зависимости от формата и возможностей агента пользователя, выбор наиболее подходящего представления может выполняться автоматически. Однако, эта спецификация не определяет какого-либо стандарта для автоматического выбора. Если сервер имеет представление по умолчанию (наиболее предпочтительное), то ему СЛЕДУЕТ включить URL этого представления в поле Location; агенты пользователя МОГУТ использовать значение поля Location для автоматической переадресации. Этот ответ является кэшируемым, если не обозначено иного. 10.3.2 301 Постоянно перенесен, Moved Permanently.Запрошенному ресурсу был назначен новый постоянный URI, и любые будущие ссылки на этот ресурс СЛЕДУЕТ выполнять, используя один из возвращенных URI. Клиентам с возможностями редактирования связей СЛЕДУЕТ автоматически переопределить ссылки на запрашиваемый URI (Request-URI), используя одну или несколько новых ссылок, возвращенных сервером в тех местах, где это возможно. Этот ответ является кэшируемым, если не обозначено иного. Если код состояния 301 был получен в ответ на запрос, отличный от GET или HEAD, агент пользователя НЕ ДОЛЖЕН автоматически переназначать запрос, пока нет подтверждения пользователя, так как иначе условия запроса изменятся. Обратите внимание: При автоматическом переназначении запроса POST после получения кода состояния 301, некоторые существующие HTTP/1.0 агенты пользователя ошибочно изменят метод запроса на GET. 10.3.3 302 Временно перемещен, Moved Temporarily.Запрошенный ресурс временно находится под другим URI. Так как переадресация может быть изменена в любой момент, клиенту СЛЕДУЕТ продолжать использовать запрашиваемый URI (Request-URI) в будущих запросах. Кэшируемость этого ответа зависит только от содержимого полей заголовка Cache-Control или Expires (если этих полей нет, то ответ не кэшируется). Если код состояния 302 был получен в ответ на запрос, отличный от GET или HEAD, агент пользователя НЕ ДОЛЖЕН автоматически переназначать запрос, пока нет подтверждения пользователя, так как иначе условия запроса изменятся. Обратите внимание: При автоматическом переназначении запроса POST после получения кода состояния 302, некоторые существующие HTTP/1.0 агенты пользователя ошибочно изменят метод запроса на GET. 10.3.4 303 Смотреть другой, See Other.10.3.5 304 Не модифицирован, Not Modified.Если клиент выполнил условный GET запрос, и доступ разрешен, но документ не изменился, то серверу СЛЕДУЕТ ответить, используя этот код состояния. Ответ НЕ ДОЛЖЕН содержать тела сообщения. Если условный GET использует строгое сравнение кэша (strong cache validator) (смотреть раздел 13.3.3), ответу НЕ СЛЕДУЕТ содержать других заголовков объекта (entity-headers). Иначе (то есть, если условный GET использует слабое сравнение (weak validator)), ответ НЕ ДОЛЖЕН содержать других заголовков объекта; это предотвращает несогласованности между кэшированными телами объектов (entity-bodies) и модифицированными заголовками. Если ответ с кодом состояния 304 указывает объект, в настоящее время не кэшированный, то кэш ДОЛЖЕН игнорировать ответ и повторить запрос без условного выражения. Если кэш использует полученный ответ с кодом состояния 304 для модифицикации вхождения кэша, кэш ДОЛЖЕН модифицировать вхождение так, чтобы отразить любые новые значения полей, данные в ответе. Ответ с кодом состояния 304 НЕ ДОЛЖЕН включать тела сообщения (message-body), и, таким образом, всегда завершается первой пустой строкой после полей заголовка. 10.3.6 305 Используйте прокси-сервер, Use Proxy.Обращение к запрошенному ресурсу ДОЛЖНО производиться через прокси-сервер, указанный в поле Location. В поле Location указан URL прокси-сервера. Ожидается, что получатель повторит запрос через прокси-сервер. Класс кодов состояния 4xx предназначен для случаев, когда клиент, возможно, допустил ошибку. За исключением ответа на запрос HEAD, серверу СЛЕДУЕТ включить объект, содержащий объяснение ошибочной ситуации, и объяснение, является ли она временной или постоянной. Эти коды состояния применимы к любому методу запроса. Агентам пользователя СЛЕДУЕТ показывать пользователю любой включенный объект. Обратите внимание: Если клиент посылает данные, то реализации сервера, использующей TCP, следует гарантировать, что клиент подтвердил получение пакета(ов), содержащего ответ, прежде чем сервер закроет соединение. Если клиент продолжает посылать данные серверу после закрытия соединения, TCP стек сервера пошлет пакет сброса (RST) клиенту, а TCP стек клиента, в свою очередь, может стереть клиентские неподтвержденные входные буфера прежде, чем они будут прочитаны и интерпретированы приложением HTTP. 10.4.1 400 Испорченный Запрос, Bad Request.Запрос не может быть понят сервером из-за malformed синтаксиса. Клиенту НЕ СЛЕДУЕТ повторять запрос без модификаций. 10.4.2 401 Несанкционированно, Unauthorized.Запрос требует установления подлинности пользователя. Ответ ДОЛЖЕН включать поле заголовка WWW-Authenticate (раздел 14.46), содержащее вызов (challenge), применимый к запрошенному ресурсу. Клиент МОЖЕТ повторить запрос с подходящим полем заголовка Authorization (раздел 14.8). Если запрос уже включает рекомендации установления подлинности (Authorization credentials) в поле Authorization, то ответ с кодом состояния 401 указывает, что в установлении подлинности этим рекомендациям отказано. Если ответ с кодом состояния 401 содержит тот же самый вызов, что и предшествующий ответ, а агент пользователя уже делал попытку установления подлинности по крайней мере один раз, то СЛЕДУЕТ показать пользователю объект, который был дан в ответе, так как этот объект МОЖЕТ включать relevant диагностическую информацию. Установление подлинности доступа в протоколе HTTP описывается в разделе 11. 10.4.3 402 Требуется оплата, Payment Required.Этот код зарезервирован для будущего использования. 10.4.4 403 Запрещено, Forbidden.Сервер понял запрос, но отказывается выполнять его. Установление подлинности (Authorization) не поможет, и запрос НЕ ДОЛЖЕН быть повторен. Если метод запроса не HEAD и сервер желает указать, почему запрос не был выполнен, ему СЛЕДУЕТ описать причину отказа в объекте. Этот код состояния обычно используется, когда сервер не желает указывать точную причину отказа, или когда никакой другой ответ не подходит. 10.4.5 404 Не найден, Not Found.Сервер не нашел ничего, соответствующего данному запрашиваемому URI (Request-URI). Никак не сообщается является ли такое положение временным или постоянным. Если сервер не желает делать данную информацию доступной клиенту, то вместо этого кода состояния может использоваться код состояния 403 (Запрещено, Forbidden). Код состояния 410 (Удален, Gone) СЛЕДУЕТ использовать, если сервер знает через некоторый внутренне конфигурируемый механизм, что старый ресурс более недоступен, но не знает нового адреса для пересылки. 10.4.6 405 Метод не дозволен, Method Not Allowed.Метод, определенный в строке запроса (Request-Line) не дозволено применять для ресурса, идентифицированного запрашиваемым URI (Request-URI). Ответ ДОЛЖЕН включать заголовок Allow, содержащий список допустимых методов для запрошенного ресурса. 10.4.7 406 Не приемлем, Not Acceptable.Ресурс, идентифицируемый запросом, имеет возможности генерации только таких объектов ответа, которые имеют характеристики содержимого (content characteristics), не согласующиеся с заголовками приема (accept headers), представленными в запросе. Если это был не запрос HEAD, то в ответ СЛЕДУЕТ включить объект, содержащий список доступных характеристик объекта и адреса (locations), из которых пользователь или агент пользователя может выбрать наиболее подходящий. Формат объекта определеятся медиа типом, представленным в поле заголовка Content-Type. В зависимости от формата и возможностей агента пользователя, выбор наиболее подходящего варианта может выполняться автоматически. Однако, эта спецификация не определяет никакого стандарта для автоматического выбора. Обратите внимание: HTTP/1.1 серверы позволяют возвращать ответы, которые не приемлемы согласно заголовкам приема (accept headers), представленным в запросе. В некоторых случаях, это может быть даже предпочтительно по сравнению с посылкой ответа с кодом состояния 406. Агентам пользователя неплохо бы рассматривать заголовки поступившего ответа, чтобы определить, является ли он приемлемым. Если ответ недопустим, агенту пользователя СЛЕДУЕТ временно остановиться, чтобы получить больше данных и спросить пользователя о дальнейших действиях. 10.4.8 407 Требуется установление подлинности через прокси-сервер, Proxy Authentication Required.Этот код подобен коду 401 (Несанкционированно, Unauthorized), но указывает, что клиент ДОЛЖЕН сначала установить свою подлинность (authenticate) прокси-серверу. Прокси-сервер ДОЛЖЕН возвратить поле заголовка Proxy-Authenticate (раздел 14.33), содержащее вызов (challenge), применяемый прокси-сервером для запрошенного ресурса. Клиент МОЖЕТ повторить запрос с подходящим полем заголовка Proxy-Authorization (раздел 14.34). Установление подлинности доступа в протоколе HTTP описывается в разделе 11. 10.4.9 408 Истекло время ожидания запроса, Request Timeout.Клиент не произвел запрос в течение времени, которое сервер готов ждать. Клиент МОЖЕТ повторить запрос без модификаций позже. 10.4.10 409 Конфликт, Conflict.Запрос не был выполнен из-за конфликта с текущим состоянием ресурса. Этот код позволяется только в ситуациях, когда ожидается, что пользователь может решить конфликт и повторно передать запрос. Телу ответа СЛЕДУЕТ содержать достаточное количество информации для пользователя, чтобы он мог распознать источник конфликта. В идеале, объект ответа должен включать достаточно информации для пользователя или агента пользователя для решения проблемы; однако это может не быть возможно, да и не требуется. Конфликты, наиболее вероятно, будут возникать в ответ на запрос PUT. Если используется версификация, и объект, который должен быть помещен, включает изменения ресурса, которые находятся в противоречии со сделанными раньше каким-либо запросом (третьей стороны), сервер МОЖЕТ использовать ответ с кодом состояния 409, чтобы показать, что он не может выполнить запрос. В этом случае, объекту ответа СЛЕДУЕТ содержать список отличий двух версий в формате, определенном полем заголовка ответа Content-Type. 10.4.11 410 Удален, Gone.Запрошенный ресурс больше не доступен на сервере, и нет никакого адреса для перенаправления запроса. Такое состояние СЛЕДУЕТ рассматривать как постоянное. Клиентам с возможностями редактирования гиперсвязей СЛЕДУЕТ удалить ссылки на запрашиваемый URI (Request-URI) после одобрения пользователем. Если сервер не знает, или не может определить, является ли такое положение постоянным или нет, то ему СЛЕДУЕТ вместо этого кода использовать код состояния 404 (Не найден, Not Found). Этот ответ является кэшируемым, если не обозначено иного. 10.4.12 411 Требуется длина, Length Required.Сервер отказывается принимать запрос с неопределенным Content-Length. Клиент МОЖЕТ повторить запрос, если добавит допустимое поле заголовка Content-Length, содержащее длину тела сообщения (message-body) в сообщении запроса. 10.4.13 412 Предусловие неверно, Precondition Failed.Предусловие, представленное одним или несколькими полями заголовка запроса (request-header), оказалось ложным при проверке сервером. Этот код ответа позволяет клиенту поместить предусловия на текущую метаинформацию ресурса (данные полей заголовка) и, таким образом, предотвратить применение запрошенного метода к ресурсу, отличному от того, для которого предназначен метод. 10.4.14 413 Объект запроса слишком большой, Request Entity Too Large.Сервер отказывается обрабатывать запрос, потому что объект запроса больше, чем сервер желает или способен обработать. Сервер может закрыть соединение, чтобы не дать клиенту возможность продолжить запрос. Если это временное состояние, то серверу СЛЕДУЕТ включить поле заголовка Retry-After для указания времени, через которое клиент может снова повторить запрос. 10.4.15 414 URI запроса слишком длинный, Request-URI Too Long.Сервер отказывается обслуживать запрос, потому что запрашиваемый URI (Request-URI) длиннее, чем сервер желает интерпретировать. Это редкое состояние, которое, по всей вероятности, происходит только тогда, когда клиент неправильно преобразовал запрос POST к запросу GET с длинной информацией запроса, либо когда клиент попал в «черную дыру» URL перенаправления (например, перенаправленный URL префикс указывает на свой суффикс), или когда на сервер производится нападение клиентом, пытающимся эксплуатировать лазейки в секретности, имеющиеся в некоторых серверах, использующих буфера фиксированной длины для чтения или манипулирования с запрашиваемым URI (Request-URI). 10.4.16 415 Неподдерживаемый медиа тип, Unsupported Media Type.Сервер отказывается обслуживать запрос, потому что объект запроса находится в формате, не поддерживаемом запрошенным ресурсом для запрошенного метода. Коды состояния, начинающиеся с цифры «5» указывают случаи, в которых сервер знает, что допустил ошибку или неспособен выполнить запрос. Отвечая на запрос, за исключением запроса HEAD, серверу СЛЕДУЕТ включить объект, содержащий объяснение ошибочной ситуации и информацию, является ли это положение временным или постоянным. Агентам пользователя СЛЕДУЕТ показывать пользователю любой включенный объект. Эти коды состояния применимы к любому методу запроса. 10.5.1 500 Внутренняя ошибка сервера, Internal Server Error.Сервер столкнулся с непредвиденным условием, которое не позволяет ему выполнить запрос. 10.5.2 501 Не реализовано, Not Implemented.Сервер не поддерживает функциональные возможности, требуемые для выполнения запроса. Этот ответ соответствует состоянию, когда сервер не распознает метод запроса и не способен обеспечитиь его для любого ресурса. 10.5.3 502 Ошибка шлюза, Bad Gateway.Сервер, действуя в качестве шлюза или прокси-сервера, получил недопустимый ответ от следующего сервера в цепочке запросов, к которому обратился при попытке выполнить запрос. 10.5.4 503 Сервис недоступен, Service Unavailable.Сервер в настоящее время не способен обработать запрос из-за временной перегрузки или обслуживания сервера. Это временное условие, которое будет облегчено после некоторой задержки. Если известна продолжительность задержки, она может быть указана в заголовке Retry-After. Если Retry-After не присутствует в ответе, клиенту СЛЕДУЕТ обрабатывать этот ответ как ответ с кодом 500. Обратите внимание: существование кода состояния 503 не подразумевает, что сервер должен использовать его, когда перегружен. Некоторые сервера могут просто закрывать соединение. 10.5.5 504 Истекло время ожидания от шлюза, Gateway Timeout.Сервер, действуя в качестве шлюза или прокси-сервера, не получил своевременного ответа от следующего сервера в цепочке запросов, к которому обратился при попытке выполнить запрос. 10.5.6 505 Не поддерживаемая версия HTTP, HTTP Version Not Supported.Сервер не поддерживает, или отказывается поддерживать, версию HTTP протокола, которая используется в сообщении запроса. Сервер указывает, что не способен или не желает выполнять запрос, используя ту же самую major версию, что и клиент, как описано в разделе 3.1, в других сообщениях. Ответу СЛЕДУЕТ содержать объект, описывающий, почему эта версия не поддерживается, и какие другие протоколы поддерживаются этим сервером. Источники:
|