Ошибка you are not allowed

Не могу понять как исправить ошибку. После гит пуша идет успешная загрузка, но в конце вот эта ошибка:

5fdca8ff5ee1a451801713.png


  • Вопрос задан

    более двух лет назад

  • 385 просмотров

Очевидно, админ репы запретил пушить в мастер. Только через pull(или merge) request.

Белым по синему же:

You are not allowed to push code to protected branches on this project

Делаете свои изменения в отдельной ветке и создаёте Merge Request

Пригласить эксперта


  • Показать ещё
    Загружается…

13 июн. 2023, в 18:12

1000 руб./за проект

13 июн. 2023, в 18:02

5000 руб./за проект

13 июн. 2023, в 17:53

3000 руб./за проект

Минуточку внимания

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

Благо у нас есть замечательные коды 4хх и 5хх, хоть и не так подробно, как хотелось бы, но рассказывающие о том, почему возникла ошибка. Ну а мы, зная эту информацию, можем попытаться ошибку исправить. 

В этом материале речь пойдет об ошибке 405 Method Not Allowed. В деталях опишу проблему и расскажу, как ее побороть.

Что означает код ошибки сервера 405?

Код 405 Method Not Allowed говорит нам о том, что сервер получил определенный запрос с заданным HTTP-методом, смог его распознать, но не дает добро на его реализацию. То есть пользователь не получит доступ к контенту, который запросил.

В отличие от 404, 405 уточняет, что запрашиваемая страница существует и функционирует. Только вот стоит изменить используемый в HTTP-запросе метод. Иначе ничего не выйдет. 

Ошибка 405

Комьюнити теперь в Телеграм

Подпишитесь и будьте в курсе последних IT-новостей

Подписаться

Из-за чего я вижу эту ошибку?

Есть 9 HTTP-методов, которые используются браузерами для общения с серверами. Из них два задействуются чаще остальных. Это метод GET для запроса информации с ресурса и метод POST для передачи какой-нибудь информации на ресурс. Два метода покрывают почти все существующие сценарии взаимодействия клиента и сервера от запроса статьи до отправки логина и пароля на сайт. Так как они выполняют разные задачи, для сервера нет никакой нужды принимать GET для авторизации на сайте или POST для загрузки данных. Если же клиент так делает и отправляет некорректный запрос (не с тем методом, который должен быть), то сервер ответит ему ошибкой. То же произойдет, если ресурс будет настроен так, что не сможет принимать специфичный набор запросов, не попадающих в «стандарт». Такие дела.

Как исправить 405 Method Not Allowed?

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

Что может сделать пользователь?

Ошибка Method Not Allowed под номером 4хх вроде бы говорит о вине клиента. Но несмотря на это, пользователь мало что может сделать, чтобы устранить проблему. В его компетенции только убедиться в том, что он не допустил ошибку в базовых вещах, и попробовать повторить те же действия в надежде на успех.

Заново открыть ту же страницу

Иногда 405 Method Not Allowed может исчезнуть после перезагрузки страницы. Так что перед тем как принимать сложные решения и жаловаться на владельцев сайта, нажмите F5 или Cmd + R раза два. 

Проверить, правильно ли он ввел URL-адрес

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

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

Что может сделать владелец сайта?

Как это часто бывает, у сервера гораздо больше способов исправить клиентскую ошибку. Тут реально целый ворох решений: от удаления подозрительных компонентов из CMS до редактирования конфигурационных файлов. 

Проверить настройки сервера

Тут будут инструкции для владельцев сайтов на базе Apache и Nginx в Timeweb. Понятно, что есть другие варианты конфигураций, но эти два — чуть ли стандарт, использующийся повсеместно. А информация, касающаяся конкретно Timeweb, заденет только расположение файлов и работу с панелью управления хостинга. Остальные моменты универсальны. 

Инструкция для пользователей Apache

Наша задача состоит в том, чтобы в файле .htaccess найти записи, которые могут провоцировать появление ошибки 405. А потом их закомментировать или удалить. Чтобы это сделать:

  • Открываем панель управления Timeweb.
  • Ищем внутри вкладку «Файловая система» и переходим на нее.
  • Открываем файл .htaccess.
  • Внутри .htaccess ищем директивы Rewrite… (обычно это RewriteEngine, RewriteCond и RewriteRule).

Эти директивы помогают в настройке переадресации и некоторых других аспектах поведения сервера. Например, чтобы заставить сервер отправлять клиенту ошибку на каждый запрос GET, можно ввести такой код:

RewriteEngine on 
RewriteCond %{REQUEST_URI} ^/ru/services/?.$ 
RewriteCond %{REQUEST_METHOD} =GET 
RewriteRule ^(.)$ http://timeweb/ru/new$1 [R=405,L]

За появление ошибки отвечает запись [R=405,L]. То есть в настройках указано, как себя будет вести сервер при определенном запросе. Надо найти все такие директивы и закомментировать их, поставив # перед записью.

Инструкция для пользователей Nginx

Здесь нужно сделать примерно то же. Разница в том, как выглядит файл с настройками и в его расположении. 

  • Ищем файл nginx.conf по пути /usr/local/nginx/conf или /usr/local/etc/nginx.
  • Открываем его любым текстовым редактором.
  • Находим код, включающий в себя упоминание ошибки 405.

В Nginx код выглядит немного сложнее. Например, запрос метода для ссылки https://moysait.com/ru/services/create будет выглядеть так:

server { listen 80; listen 443 ssl;

server_name moysait.com;

location /users/create { if ($request_method = POST) { return 405 https://moysait.com/services/create$request_uri; } } }

Делаем ту же процедуру. Останавливаемся везде, где находим директиву с ошибкой 405. Анализируем ее (вдруг, она тут случайно). И при необходимости комментируем или удаляем.

Исправить проблемы, связанные с PHP-скриптами

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

Обойти ограничение можно тремя путями:

  • Попробовать экспортировать БД через phpMyAdmin.
  • Разбить файл БД на несколько мелких частей, передача каждого из которых займет меньше 30 секунд.
  • Использовать для передачи БД Cron-задачу. На них сервер выделяет больше времени.

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

Исправить эксклюзивные для Nginx ошибки

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

Первый вариант — убедить сервер в том, что вместо кода 405 надо отправлять код 200, и это вполне нормально:

server { 
   listen 80; 
   server_name localhost;
location / { 
   root html; 
   index index.html index.htm; } 
error_page 404 /404.html; 
  error_page 403 /403.html; 
error_page 405 =200 $uri;



}

Для тех, у кого Nginx-сервер — это proxy, понадобится вот такой код:

error_page 405 =200 @405; 

location @405 { root /htdocs; proxy_pass http://localhost:8080; }

Аналогичная ошибка возникает при работе с модулем FastCGI. Из-за него сервер неправильно считывает запросы с методом POST, поэтому необходимо делить параметры и адрес скрипта вот так:

location ~.php(.*) {
 fastcgi_pass 127.0.0.1:9000;
 fastcgi_split_path_info ^(.+.php)(.*)$;
 fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
 fastcgi_param PATH_INFO $fastcgi_path_info;
 fastcgi_param PATH_TRANSLATED $document_root$fastcgi_path_info;
 include /etc/nginx/fastcgi_params;
}

Далее речь пойдет об общих методах диагностики и исправления ошибок. На крайний случай, если конкретные решения не помогли.

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

Если недавно что-то поменяли, а после этого все сломалось, то надо это «поменяли» рассмотреть подробнее. Провести ручной дебаггинг, если можно это так назвать. Наверняка где-то затесалась несерьезная, но обидная ошибка. 

Удалить сторонние дополнения для CMS

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

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

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

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

Откатиться на более старую версию CMS

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

Проверить новые записи в базе данных

Расширения могут вносить изменения в базу данных сайта. Иногда не очень полезные. Надо проверить, не появилось ли после установки свежего дополнения каких-либо непрошенных изменений в базе данных. Может, появились подозрительные записи, которых не должно быть. Лучше подвергнуть анализу всю БД от начала до конца (если другие методы исправления ошибки 405 не помогли, конечно).

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

I have a problem when I push my codes to git while I have developer access in my project, but everything is okay when I have master access. Where is the problem come from? And how to fix it?

Error message:

error: You are not allowed to push code to protected branches on this project.

error: failed to push some refs to …

This question is related to
branch
gitlab
git-commit
git-push
git-add

there’s no problem — everything works as expected.

In GitLab some branches can be protected. By default only Maintainer/Owner users can commit to protected branches (see permissions docs). master branch is protected by default — it forces developers to issue merge requests to be validated by project maintainers before integrating them into main code.

You can turn on and off protection on selected branches in Project Settings (where exactly depends on GitLab version — see instructions below).

On the same settings page you can also allow developers to push into the protected branches. With this setting on, protection will be limited to rejecting operations requiring git push --force (rebase etc.)

Since GitLab 9.3

Go to project: «Settings» ? «Repository» ? «Expand» on «Protected branches»

enter image description here

I’m not really sure when this change was introduced, screenshots are from 10.3 version.

Now you can select who is allowed to merge or push into selected branches (for example: you can turn off pushes to master at all, forcing all changes to branch to be made via Merge Requests). Or you can click «Unprotect» to completely remove protection from branch.

Since GitLab 9.0

Similarly to GitLab 9.3, but no need to click «Expand» — everything is already expanded:

Go to project: «Settings» ? «Repository» ? scroll down to «Protected branches».

enter image description here

Pre GitLab 9.0

Project: «Settings» ? «Protected branches» (if you are at least ‘Master’ of given project).

Settings ? Protected branches

Then click on «Unprotect» or «Developers can push»:

enter image description here

Themeisle content is free. When you purchase through referral links on our site, we earn a commission. Learn More

Encountering the “sorry you are not allowed to access this page” error on your WordPress website? 🤔

Sorry you are not allowed to access this page” is a common WordPress error that appears when you are trying to access a restricted page in your WordPress dashboard.

The restricted page could be a post, setting, menu, or even the main dashboard page in some instances.

Not having access to the dashboard is alarming, but there’s no need to panic. With a little effort, you can remove the error and get back to managing your website in no time.

All you need to do is try out the solutions we have listed below in this article. 😎

Let’s get started.

What is the “Sorry you are not allowed to access this page” error? And why does it occur? 🧐

sorry you are not allowed to access this page error

As the name suggests, the “sorry you are not allowed to access this page” error appears on a WordPress site when you are trying to access a page that you don’t have permission to see (or that WordPress doesn’t think you should be allowed to see, possibly because of a misconfiguration).

Sometimes, this is intended behavior because WordPress intentionally limits what users with different roles can do.

👉 For example, if your WordPress account has the Author role, you wouldn’t be able to access the interfaces to install plugins or themes.

This is intentional behavior, in which case the “sorry you are not allowed to access this page” message isn’t really an error. You might need to contact the site administrator to ask them to upgrade your account if you think you should be able to access these areas.

However, this problem can become an error if you’re seeing this message when trying to access dashboard areas that you should have access to.

👉 For example, if you’re seeing this message as the site Administrator, that’s a pretty good sign that something has gone wrong.

The error sometimes appears after you have updated a plugin, theme, or WordPress core. That’s because the data stored in the plugin, theme, or WordPress core does not correspond with the data stored in the database of your site.

Think of it this way: You may be assigned as an admin in the database, but the software you just updated looks upon you as a subscriber and prevents you from accessing its settings page. That’s when you see the “sorry you are not allowed to access this page” error on your site.

Other possible causes include running outdated PHP versions, file permissions problems, incorrect credentials in your wp-config.php file, and more.

No matter why the error appeared, you can remove it from your site by taking the steps in the next section. 👇

Fixing the “sorry you are not allowed to access this page” error is time-consuming because a number of reasons could have led to the error. You might need to try many solutions before you find the root of the problem.

But first, make sure you have a backup of your entire website. Executing some of the solutions in this tutorial could lead to further damage. If that happens, a backup will act as your safety net. You can quickly restore your website and continue trying the solutions.

IMPORTANT: Speaking of backups, if you take daily backups, then try restoring the latest backup of your site. It will often remove the error and you can get back to managing your website in no time. The only drawback here is that you stand to lose any work you did on your website between taking the last backup and the appearance of the error.

Now, let’s get started.

  1. Refresh website
  2. Try different browser & clear cache
  3. Set proper user roles
  4. Disable plugins & themes
  5. Ensure database prefix is correct
  6. Fix file permissions
  7. Upgrade to the latest PHP version
  8. Regenerate .htaccess file

1. Refresh website

The error might have been caused by a temporary issue that took care of itself. Refreshing the website could allow you to access the page. But make sure to wait for 2-3 minutes before you refresh the page.

2. Try different browser & clear cache

You can also try opening the URL on a different browser like Safari, Firefox, Opera Mini, Microsoft Edge, etc. If the site successfully opens in a different browser, then your current browser is showing you a cached version of the website. In that case, to remove the error from your site all you need to do is clear the cache. Here’s a guide that’ll help you do just that.

3. Set proper user roles

WordPress user roles

The error could be occurring because your user roles have been inadvertently changed. Since the “sorry you are not allowed to access this page” error blocks you from accessing the dashboard, you can ask other admins to set your user roles properly.

If you or someone else still has access to the dashboard, you can change a user’s role by editing their profile in the Users area of your dashboard.

Change user roles

Alternatively, you can create a new admin user via phpMyAdmin and gain access to the site.

The phpMyAdmin is the database of your website. It stores a ton of information, including your user roles. You can access phpMyAdmin to check if your user roles have been changed.

4. Disable plugins & themes

If the error occurred after you added or updated a theme or a plugin to your WordPress website, then perhaps the theme or the plugin is the culprit. Try disabling the software.

If you can’t access the Plugins and Themes list in your dashboard to disable the extension from the dashboard, you can also manually disable plugins and themes using FTP or cPanel File Manager.

Open your hosting account and go to cPanel → File Manager → public_html → wp-content. You should see a themes and plugins folder.

If you want to disable a theme, then go to the themes folder, select the theme, right-click, and then select Rename. Rename the theme into something else. Then check your website.

In the same way, disable the plugin you had installed or updated before the error appeared on your site.

You can also try disabling all your plugins at once and checking if the error is gone. If that fixes it, you can reactivate your plugins one by one until you find the problematic plugin.

5. Ensure database prefix is correct

Migration from a different hosting server or a local server can also lead to the “sorry you are not allowed to access this page” error.

Migration causes discrepancies in your wp-config.php file. The most common discrepancy is the change of database prefix.

To fix it, you need to access the wp-config.php file, check the prefix and then match it with the prefix listed on your database. We will show you how to do that.

Step 1: Check wp-config

Open your hosting account and go to cPanel → File Manager → public_html.

If your host doesn’t offer cPanel, you can also follow similar steps using FTP.

You should find the wp-config.php file in the public_html folder. To open the file, right-click on the file and select View.

view wpconfig file - sorry you are not allowed to access this page error
Locating and viewing wp-config file

Next, you will see your database prefix looking something like this: $table_prefix = ‘wpcg_’;

This means that the config file believes that the prefix of our database is wpcg_. Now we need to access our database and check if the prefix there matches with the one in the config file.

database prefix in the wpconfig file
Locating database prefix in wp-config file

NOTE: The default database prefix on a WordPress website is ‘wp_’ We had to change the prefix on our demo site due to security reasons.

Step 2: Check database

Open your hosting account and launch phpMyAdmin, which you can do from cPanel if your host offers it.

On the left side of the phpMyAdmin page, you should find a database option that you can expand. Expanding the database will reveal the prefix.

database prefix in phpmyadmin
Checking database prefix in phpMyAdmin

If it matches with the prefix in the config file then your database prefix is not causing the error.

If it doesn’t match, then you need to edit the wp-config.php file and change the database prefix.

All you need to do is open the wp-config.php file by right-clicking on the file and selecting Edit. Then, scroll down to the database prefix and change it. Don’t forget to hit the Save button before you exit.

Check your website to see if the “sorry you are not allowed to access this page” error is gone.

6. Fix file permissions

In some cases, website users come across the error when the file permissions of the site have been tampered with. We suggest fixing the file permission immediately.

For a detailed look, you can read our full guide to WordPress file permissions. Here’s the quick version…

You will need to install an FTP client like FileZilla and then connect your website with the client. This guide will help you do just that.

After the connection has been established, you should see a public_html folder on FileZilla.

In the public_html folder, you will find these folders: wp-admin, wp-content, and wp-includes. Select all three folders, right-click and click on the Change Permission option.

selecting folders in filezilla
Changing file permission of core WordPress files

Set the permission as 755. And select the Recurse into subdirectories and Apply to directories only option. Hit the OK button to save your settings.

changing file permission - sorry you are not allowed to access this page error
Changing WordPress file permission

Next, select all the files and set the file permission to 644, then select the Recurse into subdirectories and the Apply to files only option. Save your settings and close FileZilla.

Then check if the error is gone from your website.

IMPORTANT: If changed file permission was the cause of the error, then it’s possible that your website is hacked and the file permissions were tampered with by hackers. Scan your website immediately with the help of a WordPress security plugin.

selecting all files in FileZilla - sorry you are not allowed to access this page error
Selecting all files in FileZilla

7. Upgrade to the latest PHP version

An outdated PHP version can also be a reason why you are seeing the error on your WordPress site. The process of updating PHP differs from hosting to hosting. We have a guide on how to update PHP on your WordPress site. Take a look.

If your website is hosted with a hosting provider, we didn’t cover in the article, then reach out to your provider and seek help.

8. Regenerate .htaccess file

Still seeing the error? Then perhaps your .htaccess file is corrupt.

Here’s how

Go to your hosting account and open cPanel → File Manager → public_html → .htaccess. Right-click on the file and select Edit.

Next, replace the content of the file with the following text:

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L] </IfModule>
# END WordPress

Save the file and check if the error has been removed from the site.

That’s it! 🤩 We hope by now you were able to fix the “sorry you are not allowed to access this page” error on your WordPress website. If not, then reach out to your hosting provider and seek help.

Fix the “Sorry you are not allowed to access this page” error for good 🏁

Fixing the “sorry you are not allowed to access this page” error is not difficult but time-consuming work. It can be hard to pinpoint the exact cause behind the error, which is why you need to try every solution to find the right one.

To avoid issues, make sure to take a backup of your website before carrying out any of the solutions.

If you have any questions about the “sorry you are not allowed to access this page” error, leave a comment below.

A clear explanation from Daniel Irvine [original link]:

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

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

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

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

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

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

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

Nick T's user avatar

Nick T

25.5k11 gold badges80 silver badges121 bronze badges

answered Aug 4, 2011 at 6:24

JPReddy's user avatar

24

Edit: RFC2616 is obsolete, see RFC9110.

401 Unauthorized:

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

403 Forbidden:

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

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


emery's user avatar

emery

8,45310 gold badges43 silver badges51 bronze badges

answered Jul 21, 2010 at 7:28

Oded's user avatar

OdedOded

488k99 gold badges881 silver badges1007 bronze badges

11

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

Brief and Terse

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

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

Detailed and In-Depth

From RFC2616

10.4.2 401 Unauthorized

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

and

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

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

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

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

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


Edit: RFC2616 is obsolete, see RFC7231 and RFC7235.

Community's user avatar

answered Feb 5, 2013 at 17:14

ldrut's user avatar

ldrutldrut

3,7971 gold badge17 silver badges4 bronze badges

7

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

Checks are usually done in this order:

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

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

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

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

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

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

answered Feb 23, 2015 at 11:00

Christophe Roussy's user avatar

9

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

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

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

answered Jul 21, 2010 at 7:26

Cumbayah's user avatar

CumbayahCumbayah

4,4051 gold badge25 silver badges32 bronze badges

6

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

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

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

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

3.1. 401 Unauthorized

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

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

10.4.4 403 Forbidden

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

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

6.5.3. 403 Forbidden

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

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

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

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

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

Community's user avatar

answered Feb 27, 2013 at 9:44

Erwan Legrand's user avatar

6

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

Premraj's user avatar

Premraj

71.1k26 gold badges235 silver badges179 bronze badges

answered Aug 6, 2019 at 12:37

Akshay Misal's user avatar

4

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

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

answered Dec 25, 2014 at 9:09

Patrick White's user avatar

5

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

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

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

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

6.5.3. 403 Forbidden

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

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

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

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

Community's user avatar

answered May 22, 2014 at 10:54

Dave Watts's user avatar

Dave WattsDave Watts

8807 silver badges11 bronze badges

1

These are the meanings:

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

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

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

answered Nov 19, 2019 at 10:17

Luca C.'s user avatar

Luca C.Luca C.

11.5k1 gold badge86 silver badges77 bronze badges

3

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

TL;DR

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

Practical Examples

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

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

RFC (2616 Section 10)

401 Unauthorized (10.4.2)

Meaning 1: Need to authenticate

The request requires user authentication. …

Meaning 2: Authentication insufficient

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

403 Forbidden (10.4.4)

Meaning: Unrelated to authentication

… Authorization will not help …

More details:

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

It SHOULD describe the reason for the refusal in the entity

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

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

answered Feb 25, 2015 at 9:03

Levite's user avatar

LeviteLevite

17.2k8 gold badges50 silver badges50 bronze badges

2

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

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

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

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

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

«The request requires user authentication

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

answered Oct 1, 2012 at 14:34

Zaid Masud's user avatar

Zaid MasudZaid Masud

13.2k9 gold badges66 silver badges88 bronze badges

4

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

enter image description here

answered Nov 11, 2021 at 12:19

Pratham's user avatar

PrathamPratham

4773 silver badges7 bronze badges

In English:

401

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

403

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

answered Apr 8, 2020 at 14:23

James's user avatar

JamesJames

4,6335 gold badges36 silver badges48 bronze badges

2

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

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

answered Aug 11, 2022 at 23:10

emery's user avatar

emeryemery

8,45310 gold badges43 silver badges51 bronze badges

0

401: You need HTTP basic auth to see this.

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

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

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

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

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

answered Sep 23, 2017 at 12:33

Val Kornea's user avatar

Val KorneaVal Kornea

4,4293 gold badges39 silver badges41 bronze badges

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

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

  • A resource requires authentication but no credentials were specified.

401: The client should specify credentials.

  • The specified credentials are in an invalid format.

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

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

401: The client should specify valid credentials.

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

401: Again, the client should specify valid credentials.

  • The specified credentials have expired.

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

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

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

  • The particular resource is inaccessible regardless of credentials.

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

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

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

answered Jun 2, 2018 at 23:34

Grant Gryczan's user avatar

A 401 response code means one of the following:

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

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

answered Feb 17, 2022 at 11:16

Ran Turner's user avatar

Ran TurnerRan Turner

14.2k4 gold badges44 silver badges50 bronze badges

0

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

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

401 Unauthorized

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

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

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

403 Forbidden

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

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

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

Community's user avatar

answered Jun 5, 2018 at 15:26

cjbarth's user avatar

cjbarthcjbarth

4,1696 gold badges42 silver badges62 bronze badges

3

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

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

Here is my reasoning for this:

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

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

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

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

answered Apr 6, 2022 at 22:44

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

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

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

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

answered Dec 12, 2014 at 19:01

Shawn's user avatar

3

Понравилась статья? Поделить с друзьями:
  • Ошибка you are have no bonuses
  • Ошибка you are empty не запускается
  • Ошибка you are banned from this server
  • Ошибка you are already connected to the server
  • Ошибка yes на стиральной машине siemens