Появление сообщения об ошибке 401 Unauthorized Error («отказ в доступе») при открытии страницы сайта означает неверную авторизацию или аутентификацию пользователя на стороне сервера при обращении к определенному url-адресу. Чаще всего она возникает при ошибочном вводе имени и/или пароля посетителем ресурса при входе в свой аккаунт. Другой причиной являются неправильные настройки, допущенные при администрировании web-ресурса. Данная ошибка отображается в браузере в виде отдельной страницы с соответствующим описанием. Некоторые разработчики интернет-ресурсов, в особенности крупных порталов, вводят собственную дополнительную кодировку данного сбоя:
- 401 Unauthorized;
- Authorization Required;
- HTTP Error 401 – Ошибка авторизации.
Попробуем разобраться с наиболее распространенными причинами возникновения данной ошибки кода HTTP-соединения и обсудим способы их решения.
Причины появления ошибки сервера 401 и способы ее устранения на стороне пользователя
При доступе к некоторым сайтам (или отдельным страницам этих сайтов), посетитель должен пройти определенные этапы получения прав:
- Идентификация – получение вашей учетной записи («identity») по username/login или email.
- Аутентификация («authentic») – проверка того, что вы знаете пароль от этой учетной записи.
- Авторизация – проверка вашей роли (статуса) в системе и решение о предоставлении доступа к запрошенной странице или ресурсу на определенных условиях.
Большинство пользователей сохраняют свои данные по умолчанию в истории браузеров, что позволяет быстро идентифицироваться на наиболее часто посещаемых страницах и синхронизировать настройки между устройствами. Данный способ удобен для серфинга в интернете, но может привести к проблемам с безопасностью доступа к конфиденциальной информации. При наличии большого количества авторизованных регистрационных данных к различным сайтам используйте надежный мастер-пароль, который закрывает доступ к сохраненной в браузере информации.
Наиболее распространенной причиной появления ошибки с кодом 401 для рядового пользователя является ввод неверных данных при посещении определенного ресурса. В этом и других случаях нужно попробовать сделать следующее:
- Проверьте в адресной строке правильность написания URL. Особенно это касается перехода на подстраницы сайта, требующие авторизации. Введите правильный адрес. Если переход на страницу осуществлялся после входа в аккаунт, разлогинитесь, вернитесь на главную страницу и произведите повторный вход с правильными учетными данными.
- При осуществлении входа с сохраненными данными пользователя и появлении ошибки сервера 401 проверьте их корректность в соответствующих настройках данного браузера. Возможно, авторизационные данные были вами изменены в другом браузере. Также можно очистить кэш, удалить cookies и повторить попытку входа. При удалении истории браузера или очистке кэша потребуется ручное введение логина и пароля для получения доступа. Если вы не помните пароль, пройдите процедуру восстановления, следуя инструкциям.
- Если вы считаете, что вводите правильные регистрационные данные, но не можете получить доступ к сайту, обратитесь к администратору ресурса. В этом случае лучше всего сделать скриншот проблемной страницы.
- Иногда блокировка происходит на стороне провайдера, что тоже приводит к отказу в доступе и появлению сообщения с кодировкой 401. Для проверки можно попробовать авторизоваться на том же ресурсе с альтернативного ip-адреса (например, используя VPN). При подтверждении блокировки трафика свяжитесь с провайдером и следуйте его инструкциям.
Некоторые крупные интернет-ресурсы с большим количеством подписчиков используют дополнительные настройки для обеспечения безопасности доступа. К примеру, ваш аккаунт может быть заблокирован при многократных попытках неудачной авторизации. Слишком частые попытки законнектиться могут быть восприняты как действия бота. В этом случае вы увидите соответствующее сообщение, но можете быть просто переадресованы на страницу с кодом 401. Свяжитесь с администратором сайта и решите проблему.
Иногда простая перезагрузка проблемной страницы, выход из текущей сессии или использование другого веб-браузера полностью решают проблему с 401 ошибкой авторизации.
Устранение ошибки 401 администратором веб-ресурса
Для владельцев сайтов, столкнувшихся с появлением ошибки отказа доступа 401, решить ее порою намного сложнее, чем обычному посетителю ресурса. Есть несколько рекомендаций, которые помогут в этом:
- Обращение в службу поддержки хостинга сайта. Как и в случае возникновения проблем с провайдером, лучше всего подробно описать последовательность действий, приведших к появлению ошибки 401, приложить скриншот.
- При отсутствии проблем на стороне хостинг-провайдера можно внести следующие изменения в настройки сайта с помощью строки Disallow:/адрес проблемной страницы. Запретить индексацию страницам с ошибкой в «rоbоts.txt», после чего добавить в файл «.htассеss» строку такого типа:
Redirect 301 /oldpage.html http://site.com/newpage.html.
Где в поле /oldpage.html прописывается адрес проблемной страницы, а в http://site.com/newpage.html адрес страницы авторизации.
Таким образом вы перенаправите пользователей со всех страниц, которые выдают ошибку 401, на страницу начальной авторизации.
- Если после выполнения предыдущих рекомендаций пользователи при попытках авторизации все равно видят ошибку 401, то найдите на сервере файл «php.ini» и увеличьте время жизни сессии, изменив значения следующих параметров: «session.gc_maxlifetime» и «session.cookie_lifetime» на 1440 и 0 соответственно.
- Разработчики веб-ресурсов могут использовать более сложные методы авторизации и аутентификации доступа для создания дополнительной защиты по протоколу HTTP. Если устранить сбой простыми методами администрирования не удается, следует обратиться к специалистам, создававшим сайт, для внесения соответствующих изменений в код.
Хотя ошибка 401 и является проблемой на стороне клиента, ошибка пользователя на стороне сервера может привести к ложному требованию входа в систему. К примеру, сетевой администратор разрешит аутентификацию входа в систему всем пользователям, даже если это не требуется. В таком случае сообщение о несанкционированном доступе будет отображаться для всех, кто посещает сайт. Баг устраняется внесением соответствующих изменений в настройки.
Дополнительная информация об ошибке с кодом 401
Веб-серверы под управлением Microsoft IIS могут предоставить дополнительные данные об ошибке 401 Unauthorized в виде второго ряда цифр:
- 401, 1 – войти не удалось;
- 401, 2 – ошибка входа в систему из-за конфигурации сервера;
- 401, 3 – несанкционированный доступ из-за ACL на ресурс;
- 401, 501 – доступ запрещен: слишком много запросов с одного и того же клиентского IP; ограничение динамического IP-адреса – достигнут предел одновременных запросов и т.д.
Более подробную информацию об ошибке сервера 401 при использовании обычной проверки подлинности для подключения к веб-узлу, который размещен в службе MS IIS, смотрите здесь.
Следующие сообщения также являются ошибками на стороне клиента и относятся к 401 ошибке:
- 400 Bad Request;
- 403 Forbidden;
- 404 Not Found;
- 408 Request Timeout.
Как видим, появление ошибки авторизации 401 Unauthorized не является критичным для рядового посетителя сайта и чаще всего устраняется самыми простыми способами. В более сложной ситуации оказываются администраторы и владельцы интернет-ресурсов, но и они в 100% случаев разберутся с данным багом путем изменения настроек или корректировки html-кода с привлечением разработчика сайта.
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:
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:
Other variations include:
- “HTTP 401 Error – Unauthorized”
- “401 Unauthorized”
- “Access Denied”
These errors occur on websites that require a login in order to access them. In most cases, it means that something is either wrong with the credentials or with the browser’s ability to read them as valid.
This is similar to HTTP 403 Forbidden Error, in that access isn’t permitted to the user. However, unlike with the 403 error, the 401 error message indicates that the authentication process failed.
The code is sent via the WWW-Authenticate header, which is responsible for identifying the authentication method used for granting access to a web page or resource.
The HTTP 401 error is all too common 🤦♀️ — and this guide will give you everything you need to fix it the next time you see that message showing up ✅Click to Tweet
What Causes a 401 Error?
If you encounter an error code in the 400s, you know you’re dealing with a client-side (or browser-side) issue. While the problem may be happening within your browser, however, it doesn’t necessarily always mean that’s the culprit, which we’ll explain in more detail later.
401 errors occur on restricted resources, such as password-protected pages of your WordPress site. So it’s safe to assume that the cause of the problem has something to do with the authentication credentials.
Outdated Browser Cache and Cookies
One of the most common reasons you might experience a 401 error is that your browser’s cache and cookies are out of date, preventing the authorization from successfully going through. If your browser isn’t using the valid authentication credentials (or any at all), the server will reject the request.
Plugin Incompatibility
At other times, this error is caused by a plugin incompatibility or error. For example, a firewall or security plugin can mistake your login attempt as malicious activity, and return a 401 error to protect the page.
Incorrect URL or Outdated Link
It’s also possible that the source of the problem can be attributed to a minor mistake. Common culprits in this category include an incorrectly-typed URL or an outdated link.
How to Fix the 401 Error (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).
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:
A new window will open. Under the Basic tab, make sure all three boxes are selected, and then select Clear data:
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:
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:
If you’re using a different browser, please refer to this guide for clearing the cache
3. Flush Your DNS
Another method you can try to resolve the 401 error is flushing your Domain Name Server (DNS). While this is a rarer issue, it can be a possible cause, so it’s worth giving it a try if the first two solutions don’t work.
To do this in Windows, click on the Start button and type cmd
into the search bar. Hit Enter, and the Command Prompt will open. Copy and paste the command ipconfig/flushdns
, and then hit Enter again:
On a Mac, you can do this by going to Finder > Applications > Utilities > Terminal:
Input the command line sudo killall -HUP mDNSResponder
and press Enter. Then, you can try refreshing the page you were trying to visit, to see if the 401 error has been resolved.
4. Deactivate Your WordPress Plugins
The problem causing your 401 error might not be due to your browser. If you’re having trouble accessing your WordPress site, it’s also possible that one or more plugins are to blame.
Some plugins, especially security-focused plugins, are configured to show a 401 error when they suspect suspicious login activity that might indicate an attack. Others might just be suffering from compatibility issues. Therefore, it’s a good idea to deactivate all of your WordPress plugins and see if that resolves the issue.
You can deactivate your plugins all at the same time in your dashboard, by going to Plugins > Installed Plugins. Check the box at the top to select all of them. Then under the Bulk Actions drop-down menu, select Deactivate and click on the Apply button:
After that, try reloading the page that returned the 401 error to see if this has resolved the issue. If it has, you can manually activate each plugin one at a time, in order to determine which one is causing the problem.
Then you can remove that plugin, replace it with a new one, or contact its developer for assistance.
5. Check the WWW-Authenticate Header Response
At this point, if the issue hasn’t been fixed, it may be caused by a server-side problem. This means our last fix will be a bit more involved.
As we saw earlier, the 401 response is sent through the WWW-Authenticate header, which appears as “WWW-Authenticate: <type> realm=<realm>”. It includes ‘challenges’, or strings of data that indicate what type of authentication is required in order for access to be granted.
In a nutshell, you’ll want to check and see if the header response was sent, and more specifically, what authentication scheme was used. At the very least, this can help narrow down the cause of the problem, and bring you one step closer to a solution.
To do this, go to the web page that’s displaying the 401 error, and access the developer console in Chrome. You can right-click on the page and select Inspect, or use Ctrl+Shift+J.
Next, click on the Network tab and reload the page. This will generate a list of resources. Select the Status header to sort the table and locate the 401 status code:
Select that entry, and then click on the Headers tab. Under Response Headers, locate the WWW-Authenticate header:
The information that is present in the response header, particularly the authentication schemes, can give you more information about what’s happening and point you towards a solution. It can help you understand what type of authentication the server is expecting.
For example, in the above example, we can see that the authentication scheme is “Basic”. This means the authentication request should only require an ID and password. For more detailed information and instructions on how to use this information, we recommend referring to the HTTP Authentication Scheme Registry.
HTTP 401 errors, begone! 🧙♂️ 5 ways to stop those pesky messages (no magic required) ✨Click to Tweet
Summary
When your browser and server have trouble communicating or authenticating requests, you’re sometimes forced to deal with errors such as the 401 error. While this problem is irritating, the message is usually temporary and fixable.
Here are five methods you can use to fix the 401 error:
- Look for errors in the URL.
- Clear your browser’s cache.
- Flush your DNS.
- Deactivate your WordPress plugins.
- Check the WWW-Authenticate header response.
Get all your applications, databases and WordPress sites online and under one roof. Our feature-packed, high-performance cloud platform includes:
- Easy setup and management in the MyKinsta dashboard
- 24/7 expert support
- The best Google Cloud Platform hardware and network, powered by Kubernetes for maximum scalability
- An enterprise-level Cloudflare integration for speed and security
- Global audience reach with up to 35 data centers and 275 PoPs worldwide
Test it yourself with $20 off your first month of Application Hosting or Database Hosting. Explore our plans or talk to sales to find your best fit.
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:
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:
Other variations include:
- “HTTP 401 Error – Unauthorized”
- “401 Unauthorized”
- “Access Denied”
These errors occur on websites that require a login in order to access them. In most cases, it means that something is either wrong with the credentials or with the browser’s ability to read them as valid.
This is similar to HTTP 403 Forbidden Error, in that access isn’t permitted to the user. However, unlike with the 403 error, the 401 error message indicates that the authentication process failed.
The code is sent via the WWW-Authenticate header, which is responsible for identifying the authentication method used for granting access to a web page or resource.
The HTTP 401 error is all too common 🤦♀️ — and this guide will give you everything you need to fix it the next time you see that message showing up ✅Click to Tweet
What Causes a 401 Error?
If you encounter an error code in the 400s, you know you’re dealing with a client-side (or browser-side) issue. While the problem may be happening within your browser, however, it doesn’t necessarily always mean that’s the culprit, which we’ll explain in more detail later.
401 errors occur on restricted resources, such as password-protected pages of your WordPress site. So it’s safe to assume that the cause of the problem has something to do with the authentication credentials.
Outdated Browser Cache and Cookies
One of the most common reasons you might experience a 401 error is that your browser’s cache and cookies are out of date, preventing the authorization from successfully going through. If your browser isn’t using the valid authentication credentials (or any at all), the server will reject the request.
Plugin Incompatibility
At other times, this error is caused by a plugin incompatibility or error. For example, a firewall or security plugin can mistake your login attempt as malicious activity, and return a 401 error to protect the page.
Incorrect URL or Outdated Link
It’s also possible that the source of the problem can be attributed to a minor mistake. Common culprits in this category include an incorrectly-typed URL or an outdated link.
How to Fix the 401 Error (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).
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:
A new window will open. Under the Basic tab, make sure all three boxes are selected, and then select Clear data:
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:
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:
If you’re using a different browser, please refer to this guide for clearing the cache
3. Flush Your DNS
Another method you can try to resolve the 401 error is flushing your Domain Name Server (DNS). While this is a rarer issue, it can be a possible cause, so it’s worth giving it a try if the first two solutions don’t work.
To do this in Windows, click on the Start button and type cmd
into the search bar. Hit Enter, and the Command Prompt will open. Copy and paste the command ipconfig/flushdns
, and then hit Enter again:
On a Mac, you can do this by going to Finder > Applications > Utilities > Terminal:
Input the command line sudo killall -HUP mDNSResponder
and press Enter. Then, you can try refreshing the page you were trying to visit, to see if the 401 error has been resolved.
4. Deactivate Your WordPress Plugins
The problem causing your 401 error might not be due to your browser. If you’re having trouble accessing your WordPress site, it’s also possible that one or more plugins are to blame.
Some plugins, especially security-focused plugins, are configured to show a 401 error when they suspect suspicious login activity that might indicate an attack. Others might just be suffering from compatibility issues. Therefore, it’s a good idea to deactivate all of your WordPress plugins and see if that resolves the issue.
You can deactivate your plugins all at the same time in your dashboard, by going to Plugins > Installed Plugins. Check the box at the top to select all of them. Then under the Bulk Actions drop-down menu, select Deactivate and click on the Apply button:
After that, try reloading the page that returned the 401 error to see if this has resolved the issue. If it has, you can manually activate each plugin one at a time, in order to determine which one is causing the problem.
Then you can remove that plugin, replace it with a new one, or contact its developer for assistance.
5. Check the WWW-Authenticate Header Response
At this point, if the issue hasn’t been fixed, it may be caused by a server-side problem. This means our last fix will be a bit more involved.
As we saw earlier, the 401 response is sent through the WWW-Authenticate header, which appears as “WWW-Authenticate: <type> realm=<realm>”. It includes ‘challenges’, or strings of data that indicate what type of authentication is required in order for access to be granted.
In a nutshell, you’ll want to check and see if the header response was sent, and more specifically, what authentication scheme was used. At the very least, this can help narrow down the cause of the problem, and bring you one step closer to a solution.
To do this, go to the web page that’s displaying the 401 error, and access the developer console in Chrome. You can right-click on the page and select Inspect, or use Ctrl+Shift+J.
Next, click on the Network tab and reload the page. This will generate a list of resources. Select the Status header to sort the table and locate the 401 status code:
Select that entry, and then click on the Headers tab. Under Response Headers, locate the WWW-Authenticate header:
The information that is present in the response header, particularly the authentication schemes, can give you more information about what’s happening and point you towards a solution. It can help you understand what type of authentication the server is expecting.
For example, in the above example, we can see that the authentication scheme is “Basic”. This means the authentication request should only require an ID and password. For more detailed information and instructions on how to use this information, we recommend referring to the HTTP Authentication Scheme Registry.
HTTP 401 errors, begone! 🧙♂️ 5 ways to stop those pesky messages (no magic required) ✨Click to Tweet
Summary
When your browser and server have trouble communicating or authenticating requests, you’re sometimes forced to deal with errors such as the 401 error. While this problem is irritating, the message is usually temporary and fixable.
Here are five methods you can use to fix the 401 error:
- Look for errors in the URL.
- Clear your browser’s cache.
- Flush your DNS.
- Deactivate your WordPress plugins.
- Check the WWW-Authenticate header response.
Get all your applications, databases and WordPress sites online and under one roof. Our feature-packed, high-performance cloud platform includes:
- Easy setup and management in the MyKinsta dashboard
- 24/7 expert support
- The best Google Cloud Platform hardware and network, powered by Kubernetes for maximum scalability
- An enterprise-level Cloudflare integration for speed and security
- Global audience reach with up to 35 data centers and 275 PoPs worldwide
Test it yourself with $20 off your first month of Application Hosting or Database Hosting. Explore our plans or talk to sales to find your best fit.
A clear explanation from Daniel Irvine [original link]:
There’s a problem with 401 Unauthorized, the HTTP status code for authentication errors. And that’s just it: it’s for authentication, not authorization.
Receiving a 401 response is the server telling you, “you aren’t
authenticated–either not authenticated at all or authenticated
incorrectly–but please reauthenticate and try again.” To help you out,
it will always include a WWW-Authenticate header that describes how
to authenticate.This is a response generally returned by your web server, not your web
application.It’s also something very temporary; the server is asking you to try
again.So, for authorization I use the 403 Forbidden response. It’s
permanent, it’s tied to my application logic, and it’s a more concrete
response than a 401.Receiving a 403 response is the server telling you, “I’m sorry. I know
who you are–I believe who you say you are–but you just don’t have
permission to access this resource. Maybe if you ask the system
administrator nicely, you’ll get permission. But please don’t bother
me again until your predicament changes.”In summary, a 401 Unauthorized response should be used for missing
or bad authentication, and a 403 Forbidden response should be used
afterwards, when the user is authenticated but isn’t authorized to
perform the requested operation on the given resource.
Another nice pictorial format of how http status codes should be used.
Nick T
25.2k11 gold badges79 silver badges120 bronze badges
answered Aug 4, 2011 at 6:24
23
Edit: RFC2616 is obsolete, see RFC9110.
401 Unauthorized:
If the request already included Authorization credentials, then the 401 response indicates that authorization has been refused for those credentials.
403 Forbidden:
The server understood the request, but is refusing to fulfill it.
From your use case, it appears that the user is not authenticated. I would return 401.
emery
8,03510 gold badges42 silver badges49 bronze badges
answered Jul 21, 2010 at 7:28
OdedOded
485k98 gold badges877 silver badges1003 bronze badges
11
Something the other answers are missing is that it must be understood that Authentication and Authorization in the context of RFC 2616 refers ONLY to the HTTP Authentication protocol of RFC 2617. Authentication by schemes outside of RFC2617 is not supported in HTTP status codes and are not considered when deciding whether to use 401 or 403.
Brief and Terse
Unauthorized indicates that the client is not RFC2617 authenticated and the server is initiating the authentication process. Forbidden indicates either that the client is RFC2617 authenticated and does not have authorization or that the server does not support RFC2617 for the requested resource.
Meaning if you have your own roll-your-own login process and never use HTTP Authentication, 403 is always the proper response and 401 should never be used.
Detailed and In-Depth
From RFC2616
10.4.2 401 Unauthorized
The request requires user authentication. The response MUST include a WWW-Authenticate header field (section 14.47) containing a challenge applicable to the requested resource. The client MAY repeat the request with a suitable Authorization header field (section 14.8).
and
10.4.4 403 Forbidden
The server understood the request but is refusing to fulfil it. Authorization will not help and the request SHOULD NOT be repeated.
The first thing to keep in mind is that «Authentication» and «Authorization» in the context of this document refer specifically to the HTTP Authentication protocols from RFC 2617. They do not refer to any roll-your-own authentication protocols you may have created using login pages, etc. I will use «login» to refer to authentication and authorization by methods other than RFC2617
So the real difference is not what the problem is or even if there is a solution. The difference is what the server expects the client to do next.
401 indicates that the resource can not be provided, but the server is REQUESTING that the client log in through HTTP Authentication and has sent reply headers to initiate the process. Possibly there are authorizations that will permit access to the resource, possibly there are not, but let’s give it a try and see what happens.
403 indicates that the resource can not be provided and there is, for the current user, no way to solve this through RFC2617 and no point in trying. This may be because it is known that no level of authentication is sufficient (for instance because of an IP blacklist), but it may be because the user is already authenticated and does not have authority. The RFC2617 model is one-user, one-credentials so the case where the user may have a second set of credentials that could be authorized may be ignored. It neither suggests nor implies that some sort of login page or other non-RFC2617 authentication protocol may or may not help — that is outside the RFC2616 standards and definition.
Edit: RFC2616 is obsolete, see RFC7231 and RFC7235.
answered Feb 5, 2013 at 17:14
ldrutldrut
3,7771 gold badge17 silver badges4 bronze badges
7
+----------------------- | RESOURCE EXISTS ? (if private it is often checked AFTER auth check) +----------------------- | | NO | v YES v +----------------------- 404 | IS LOGGED-IN ? (authenticated, aka user session) or +----------------------- 401 | | 403 NO | | YES 3xx v v 401 +----------------------- (404 no reveal) | CAN ACCESS RESOURCE ? (permission, authorized, ...) or +----------------------- redirect | | to login NO | | YES | | v v 403 OK 200, redirect, ... (or 404: no reveal) (or 404: resource does not exist if private) (or 3xx: redirection)
Checks are usually done in this order:
- 404 if resource is public and does not exist or 3xx redirection
- OTHERWISE:
- 401 if not logged-in or session expired
- 403 if user does not have permission to access resource (file, json, …)
- 404 if resource does not exist or not willing to reveal anything, or 3xx redirection
UNAUTHORIZED: Status code (401) indicating that the request requires authentication, usually this means user needs to be logged-in (session). User/agent unknown by the server. Can repeat with other credentials. NOTE: This is confusing as this should have been named ‘unauthenticated’ instead of ‘unauthorized’. This can also happen after login if session expired.
Special case: Can be used instead of 404 to avoid revealing presence or non-presence of resource (credits @gingerCodeNinja)
FORBIDDEN: Status code (403) indicating the server understood the request but refused to fulfill it. User/agent known by the server but has insufficient credentials. Repeating request will not work, unless credentials changed, which is very unlikely in a short time span.
Special case: Can be used instead of 404 to avoid revealing presence or non-presence of resource (credits @gingerCodeNinja) in the case that revealing the presence of the resource exposes sensitive data or gives an attacker useful information.
NOT FOUND: Status code (404) indicating that the requested resource is not available. User/agent known but server will not reveal anything about the resource, does as if it does not exist. Repeating will not work. This is a special use of 404 (github does it for example).
As mentioned by @ChrisH there are a few options for redirection 3xx (301, 302, 303, 307 or not redirecting at all and using a 401):
- Difference between HTTP redirect codes
- How long do browsers cache HTTP 301s?
- What is correct HTTP status code when redirecting to a login page?
- What’s the difference between a 302 and a 307 redirect?
answered Feb 23, 2015 at 11:00
9
According to RFC 2616 (HTTP/1.1) 403 is sent when:
The server understood the request, but is refusing to fulfill it. Authorization will not help and the request SHOULD NOT be repeated. If the request method was not HEAD and the server wishes to make public why the request has not been fulfilled, it SHOULD describe the reason for the refusal in the entity. If the server does not wish to make this information available to the client, the status code 404 (Not Found) can be used instead
In other words, if the client CAN get access to the resource by authenticating, 401 should be sent.
answered Jul 21, 2010 at 7:26
CumbayahCumbayah
4,3771 gold badge24 silver badges32 bronze badges
6
Assuming HTTP authentication (WWW-Authenticate and Authorization headers) is in use, if authenticating as another user would grant access to the requested resource, then 401 Unauthorized should be returned.
403 Forbidden is used when access to the resource is forbidden to everyone or restricted to a given network or allowed only over SSL, whatever as long as it is no related to HTTP authentication.
If HTTP authentication is not in use and the service has a cookie-based authentication scheme as is the norm nowadays, then a 403 or a 404 should be returned.
Regarding 401, this is from RFC 7235 (Hypertext Transfer Protocol (HTTP/1.1): Authentication):
3.1. 401 Unauthorized
The 401 (Unauthorized) status code indicates that the request has not been applied because it lacks valid authentication credentials for the target resource. The origin server MUST send a WWW-Authenticate header field (Section 4.4) containing at least one challenge applicable to the target resource. If the request included authentication credentials, then the 401 response indicates that authorization has been refused for those credentials. The client MAY repeat the request with a new or replaced Authorization header field (Section 4.1). If the 401 response contains the same challenge as the prior response, and the user agent has already attempted authentication at least once, then the user agent SHOULD present the enclosed representation to the user, since it usually contains relevant diagnostic information.
The semantics of 403 (and 404) have changed over time. This is from 1999 (RFC 2616):
10.4.4 403 Forbidden
The server understood the request, but is refusing to fulfill it. Authorization will not help and the request SHOULD NOT be repeated. If the request method was not HEAD and the server wishes to make public why the request has not been fulfilled, it SHOULD describe the reason for the refusal in the entity. If the server does not wish to make this information available to the client, the status code 404 (Not Found) can be used instead.
In 2014 RFC 7231 (Hypertext Transfer Protocol (HTTP/1.1): Semantics and Content) changed the meaning of 403:
6.5.3. 403 Forbidden
The 403 (Forbidden) status code indicates that the server understood the request but refuses to authorize it. A server that wishes to make public why the request has been forbidden can describe that reason in the response payload (if any).
If authentication credentials were provided in the request, the server considers them insufficient to grant access. The client SHOULD NOT automatically repeat the request with the same credentials. The client MAY repeat the request with new or different credentials. However, a request might be forbidden for reasons unrelated to the credentials.
An origin server that wishes to «hide» the current existence of a forbidden target resource MAY instead respond with a status code of 404 (Not Found).
Thus, a 403 (or a 404) might now mean about anything. Providing new credentials might help… or it might not.
I believe the reason why this has changed is RFC 2616 assumed HTTP authentication would be used when in practice today’s Web apps build custom authentication schemes using for example forms and cookies.
answered Feb 27, 2013 at 9:44
6
- 401 Unauthorized: I don’t know who you are. This an authentication error.
- 403 Forbidden: I know who you are, but you don’t have permission to access this resource. This is an authorization error.
Premraj
72.1k25 gold badges236 silver badges176 bronze badges
answered Aug 6, 2019 at 12:37
4
This is an older question, but one option that was never really brought up was to return a 404. From a security perspective, the highest voted answer suffers from a potential information leakage vulnerability. Say, for instance, that the secure web page in question is a system admin page, or perhaps more commonly, is a record in a system that the user doesn’t have access to. Ideally you wouldn’t want a malicious user to even know that there’s a page / record there, let alone that they don’t have access. When I’m building something like this, I’ll try to record unauthenticate / unauthorized requests in an internal log, but return a 404.
OWASP has some more information about how an attacker could use this type of information as part of an attack.
answered Dec 25, 2014 at 9:09
5
This question was asked some time ago, but people’s thinking moves on.
Section 6.5.3 in this draft (authored by Fielding and Reschke) gives status code 403 a slightly different meaning to the one documented in RFC 2616.
It reflects what happens in authentication & authorization schemes employed by a number of popular web-servers and frameworks.
I’ve emphasized the bit I think is most salient.
6.5.3. 403 Forbidden
The 403 (Forbidden) status code indicates that the server understood the request but refuses to authorize it. A server that wishes to make public why the request has been forbidden can describe that reason in the response payload (if any).
If authentication credentials were provided in the request, the server considers them insufficient to grant access. The client SHOULD NOT repeat the request with the same credentials. The client MAY repeat the request with new or different credentials. However, a request might be forbidden for reasons unrelated to the credentials.
An origin server that wishes to «hide» the current existence of a forbidden target resource MAY instead respond with a status code of 404 (Not Found).
Whatever convention you use, the important thing is to provide uniformity across your site / API.
answered May 22, 2014 at 10:54
Dave WattsDave Watts
8407 silver badges11 bronze badges
1
These are the meanings:
401: User not (correctly) authenticated, the resource/page require authentication
403: User’s role or permissions does not allow to access requested resource, for instance user is not an administrator and requested page is for administrators.
Note: Technically, 403 is a superset of 401, since is legal to give 403 for unauthenticated user too. Anyway is more meaningful to differentiate.
answered Nov 19, 2019 at 10:17
Luca C.Luca C.
11.1k1 gold badge86 silver badges77 bronze badges
3
!!! DEPR: The answer reflects what used to be common practice, up until 2014 !!!
TL;DR
- 401: A refusal that has to do with authentication
- 403: A refusal that has NOTHING to do with authentication
Practical Examples
If apache requires authentication (via .htaccess
), and you hit Cancel
, it will respond with a 401 Authorization Required
If nginx finds a file, but has no access rights (user/group) to read/access it, it will respond with 403 Forbidden
RFC (2616 Section 10)
401 Unauthorized (10.4.2)
Meaning 1: Need to authenticate
The request requires user authentication. …
Meaning 2: Authentication insufficient
… If the request already included Authorization credentials, then the 401 response indicates that authorization has been refused for those credentials. …
403 Forbidden (10.4.4)
Meaning: Unrelated to authentication
… Authorization will not help …
More details:
The server understood the request, but is refusing to fulfill it.
It SHOULD describe the reason for the refusal in the entity
The status code 404 (Not Found) can be used instead
(If the server wants to keep this information from client)
answered Feb 25, 2015 at 9:03
LeviteLevite
17k8 gold badges50 silver badges50 bronze badges
2
they are not logged in or do not belong to the proper user group
You have stated two different cases; each case should have a different response:
- If they are not logged in at all you should return 401 Unauthorized
- If they are logged in but don’t belong to the proper user group, you should return 403 Forbidden
Note on the RFC based on comments received to this answer:
If the user is not logged in they are un-authenticated, the HTTP equivalent of which is 401 and is misleadingly called Unauthorized in the RFC. As section 10.4.2 states for 401 Unauthorized:
«The request requires user authentication.»
If you’re unauthenticated, 401 is the correct response. However if you’re unauthorized, in the semantically correct sense, 403 is the correct response.
answered Oct 1, 2012 at 14:34
Zaid MasudZaid Masud
13.1k9 gold badges66 silver badges88 bronze badges
4
I have created a simple note for you which will make it clear.
answered Nov 11, 2021 at 12:19
PrathamPratham
4673 silver badges7 bronze badges
In English:
401
You are potentially allowed access but for some reason on this request you were
denied. Such as a bad password? Try again, with the correct request
you will get a success response instead.
403
You are not, ever, allowed. Your name is not on the list, you won’t
ever get in, go away, don’t send a re-try request, it will be refused,
always. Go away.
answered Apr 8, 2020 at 14:23
JamesJames
4,6155 gold badges36 silver badges48 bronze badges
2
401: You need HTTP basic auth to see this.
If the user just needs to log in using you site’s standard HTML login form, 401 would not be appropriate because it is specific to HTTP basic auth.
403: This resource exists but you are not authorized to see it, and HTTP basic auth won’t help.
I don’t recommend using 403 to deny access to things like /includes
, because as far as the web is concerned, those resources don’t exist at all and should therefore 404.
In other words, 403 means «this resource requires some form of auth other than HTTP basic auth (such as using the web site’s standard HTML login form)».
https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.2
answered Sep 23, 2017 at 12:33
Vlad KorneaVlad Kornea
4,2493 gold badges38 silver badges40 bronze badges
401: Who are you again?? (programmer walks into a bar with no ID or invalid ID)
403: Oh great, you again. I’ve got my eye on you. Go on, get outta here. (programmer walks into a bar they are 86’d from)
answered Aug 11, 2022 at 23:10
emeryemery
8,03510 gold badges42 silver badges49 bronze badges
0
I think it is important to consider that, to a browser, 401 initiates an authentication dialog for the user to enter new credentials, while 403 does not. Browsers think that, if a 401 is returned, then the user should re-authenticate. So 401 stands for invalid authentication while 403 stands for a lack of permission.
Here are some cases under that logic where an error would be returned from authentication or authorization, with important phrases bolded.
- A resource requires authentication but no credentials were specified.
401: The client should specify credentials.
- The specified credentials are in an invalid format.
400: That’s neither 401 nor 403, as syntax errors should always return 400.
- The specified credentials reference a user which does not exist.
401: The client should specify valid credentials.
- The specified credentials are invalid but specify a valid user (or don’t specify a user if a specified user is not required).
401: Again, the client should specify valid credentials.
- The specified credentials have expired.
401: This is practically the same as having invalid credentials in general, so the client should specify valid credentials.
- The specified credentials are completely valid but do not suffice the particular resource, though it is possible that credentials with more permission could.
403: Specifying valid credentials would not grant access to the resource, as the current credentials are already valid but only do not have permission.
- The particular resource is inaccessible regardless of credentials.
403: This is regardless of credentials, so specifying valid credentials cannot help.
- The specified credentials are completely valid but the particular client is blocked from using them.
403: If the client is blocked, specifying new credentials will not do anything.
answered Jun 2, 2018 at 23:34
401
response means one of the following:
- An access token is missing.
- An access token is either expired, revoked, malformed, or invalid.
403
response on the other hand means that the access token is indeed valid, but that the user does not have appropriate privileges to perform the requested action.
answered Feb 17, 2022 at 11:16
Ran TurnerRan Turner
12.8k4 gold badges39 silver badges49 bronze badges
0
Given the latest RFC’s on the matter (7231 and 7235) the use-case seems quite clear (italics added):
- 401 is for unauthenticated («lacks valid authentication»); i.e. ‘I don’t know who you are, or I don’t trust you are who you say you are.’
401 Unauthorized
The 401 (Unauthorized) status code indicates that the request has not
been applied because it lacks valid authentication credentials for
the target resource. The server generating a 401 response MUST send
a WWW-Authenticate header field (Section 4.1) containing at least one
challenge applicable to the target resource.
If the request included authentication credentials, then the 401
response indicates that authorization has been refused for those
credentials. The user agent MAY repeat the request with a new or
replaced Authorization header field (Section 4.2). If the 401
response contains the same challenge as the prior response, and the
user agent has already attempted authentication at least once, then
the user agent SHOULD present the enclosed representation to the
user, since it usually contains relevant diagnostic information.
- 403 is for unauthorized («refuses to authorize»); i.e. ‘I know who you are, but you don’t have permission to access this resource.’
403 Forbidden
The 403 (Forbidden) status code indicates that the server understood
the request but refuses to authorize it. A server that wishes to
make public why the request has been forbidden can describe that
reason in the response payload (if any).
If authentication credentials were provided in the request, the
server considers them insufficient to grant access. The client
SHOULD NOT automatically repeat the request with the same
credentials. The client MAY repeat the request with new or different
credentials. However, a request might be forbidden for reasons
unrelated to the credentials.
An origin server that wishes to «hide» the current existence of a
forbidden target resource MAY instead respond with a status code of
404 (Not Found).
answered Jun 5, 2018 at 15:26
cjbarthcjbarth
4,0526 gold badges42 silver badges60 bronze badges
3
I have a slightly different take on it from the accepted answer.
It seems more semantic and logical to return a 403 when authentication fails and a 401 when authorisation fails.
Here is my reasoning for this:
When you are requesting to be authenticated, You are authorised to make that request. You need to otherwise no one would even be able to be authenticated in the first place.
If your authentication fails you are forbidden, that makes semantic sense.
On the other hand the forbidden can also apply for Authorisation, but
Say you are authenticated and you are not authorised to access a particular endpoint. It seems more semantic to return a 401 Unauthorised.
Spring Boot’s security returns 403 for a failed authentication attempt
answered Apr 6, 2022 at 22:44
theMyththeMyth
2544 silver badges14 bronze badges
In the case of 401 vs 403, this has been answered many times. This is essentially a ‘HTTP request environment’ debate, not an ‘application’ debate.
There seems to be a question on the roll-your-own-login issue (application).
In this case, simply not being logged in is not sufficient to send a 401 or a 403, unless you use HTTP Auth vs a login page (not tied to setting HTTP Auth). It sounds like you may be looking for a «201 Created», with a roll-your-own-login screen present (instead of the requested resource) for the application-level access to a file. This says:
«I heard you, it’s here, but try this instead (you are not allowed to see it)»
answered Dec 12, 2014 at 19:01
3