Here is a full list of the error codes and descriptions, including recommended
resolution steps, that are thrown by the Firebase Admin Node.js Authentication API:
auth/claims-too-large
setCustomUserClaims()
exceedsthe maximum allowed size of 1000 bytes.
auth/email-already-exists
have a unique email.
auth/id-token-expired
auth/id-token-revoked
auth/insufficient-permission
permission to access the requested Authentication resource. Refer to
Set up a
Firebase project for documentation on how to generate a credential
with appropriate permissions and use it to authenticate the Admin SDKs.
auth/internal-error
process the request. The error message should contain the response from
the Authentication server containing additional information. If the error
persists, please report the problem to our
Bug Report support channel.
auth/invalid-argument
should contain additional information.
auth/invalid-claims
setCustomUserClaims()
are invalid.
auth/invalid-continue-uri
auth/invalid-creation-time
auth/invalid-credential
perform the desired action. Certain Authentication methods such as
createCustomToken()
and verifyIdToken()
requirethe SDK to be initialized with a certificate credential as opposed to a
refresh token or Application Default credential. See
Initialize the SDK for
documentation on how to authenticate the Admin SDKs with a certificate
credential.
auth/invalid-disabled-field
disabled
user property isinvalid. It must be a boolean.
auth/invalid-display-name
displayName
user property isinvalid. It must be a non-empty string.
auth/invalid-dynamic-link-domain
current project.
auth/invalid-email
email
user property is invalid.It must be a string email address.
auth/invalid-email-verified
emailVerified
user property isinvalid. It must be a boolean.
auth/invalid-hash-algorithm
algorithms.
auth/invalid-hash-block-size
auth/invalid-hash-derived-key-length
auth/invalid-hash-key
auth/invalid-hash-memory-cost
auth/invalid-hash-parallelization
auth/invalid-hash-rounds
auth/invalid-hash-salt-separator
auth/invalid-id-token
auth/invalid-last-sign-in-time
auth/invalid-page-token
listUsers()
is invalid. Itmust be a valid non-empty string.
auth/invalid-password
password
user property is invalid.It must be a string with at least six characters.
auth/invalid-password-hash
auth/invalid-password-salt
auth/invalid-phone-number
phoneNumber
is invalid. It must bea non-empty E.164 standard compliant identifier string.
auth/invalid-photo-url
photoURL
user property is invalid.It must be a string URL.
auth/invalid-provider-data
auth/invalid-provider-id
auth/invalid-oauth-responsetype
responseType
should be set to true.
auth/invalid-session-cookie-duration
5 minutes and 2 weeks.
auth/invalid-uid
uid
must be a non-empty string with at most128 characters.
auth/invalid-user-import
auth/maximum-user-count-exceeded
auth/missing-android-pkg-name
be installed.
auth/missing-continue-uri
auth/missing-hash-algorithm
and its parameters be provided.
auth/missing-ios-bundle-id
auth/missing-uid
uid
identifier is required for the current operation.
auth/missing-oauth-client-secret
flow.
auth/operation-not-allowed
Enable it from the
Sign-in Method
section of the Firebase console.auth/phone-number-already-exists
phoneNumber
is already in use by an existinguser. Each user must have a unique
phoneNumber
.
auth/project-not-found
Admin SDKs. Refer to
Set up a
Firebase project for documentation on how to generate a credential
for your project and use it to authenticate the Admin SDKs.
auth/reserved-claims
setCustomUserClaims()
are reserved. For example,
OIDC specific claims such as (sub, iat, iss, exp, aud, auth_time, etc)
should not be used as keys for custom claims.
auth/session-cookie-expired
auth/session-cookie-revoked
auth/too-many-requests
auth/uid-already-exists
uid
is already in use by an existing user. Eachuser must have a unique
uid
.
auth/unauthorized-continue-uri
the Firebase Console.
auth/user-not-found
Появление сообщения об ошибке 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 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.
Error Code | HTTP 401 Unauthorized Error |
Error Type | Commonly a client-side error |
Error Variations | 401 Authorization Required 401 Unauthorized HTTP 401 Error – Unauthorized Access Denied |
Error Causes | Outdated Browser Cache and Cookies Plugin Incompatibility Incorrect URL or Outdated Link |
The HTTP 401 error is all too common 🤦♀️ — and this guide will give you everything you need to fix it the next time you see that message showing up ✅Click to Tweet
What Causes a 401 Error?
If you encounter an error code in the 400s, you know you’re dealing with a client-side (or browser-side) issue. While the problem may be happening within your browser, however, it doesn’t necessarily always mean that’s the culprit, which we’ll explain in more detail later.
401 errors occur on restricted resources, such as password-protected pages of your WordPress site. So it’s safe to assume that the cause of the problem has something to do with the authentication credentials.
Outdated Browser Cache and Cookies
One of the most common reasons you might experience a 401 error is that your browser’s cache and cookies are out of date, preventing the authorization from successfully going through. If your browser isn’t using the valid authentication credentials (or any at all), the server will reject the request.
Plugin Incompatibility
At other times, this error is caused by a plugin incompatibility or error. For example, a firewall or security plugin can mistake your login attempt as malicious activity, and return a 401 error to protect the page.
Incorrect URL or Outdated Link
It’s also possible that the source of the problem can be attributed to a minor mistake. Common culprits in this category include an incorrectly-typed URL or an outdated link.
How to Fix the 401 Error?
Now that we’ve gone through a bit of background on the 401 error, it’s time to discuss how you can resolve it.
Let’s take a look at five methods you can use:
1. Look for Errors in the URL
We’ll start off with the easiest potential fix: making sure you used the correct URL. This may sound simple, but 401 errors can sometimes appear if the URL wasn’t correctly entered in.
Another possibility is that the link you used to visit the page in question points to the wrong URL. For example, it might be outdated, or leading to a page that no longer exists (and no redirects are in place).
Therefore, it’s worth double-checking the URL you used. If you typed it in yourself, verify that you spelled everything correctly. If you clicked on a link, confirm that it’s pointing to the page you’re trying to access (or try to visit that page directly through the website).
2. Clear Your Browser’s Cache
Your browser’s cache is designed to improve your online experience, by reducing page loading times. Unfortunately, sometimes it can also cause unwanted interruptions.
As we mentioned earlier, one of the common causes of the 401 error is outdated or incorrect cache data or cookies. Therefore, if you don’t notice any issues with the page’s URL, the next step is to clear your browser’s cache.
This will clean out any invalid information that’s locally stored in your browser, which could be interrupting the authentication process. Similarly, your browser’s cookies might contain authentication data that simply needs to be refreshed.
If you’re a Google Chrome user, you can do this by clicking on the menu icon in the top-right corner of the browser, and then going to Settings. Under the Privacy and security section, click on Clear browsing data:
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.
# #swift #firebase #google-cloud-firestore
Вопрос:
Мое приложение готовится к распространению в Apple app Store, и последнее, что мне нужно сделать, это разрешить пользователям блокировать другого пользователя. Моя идея заключалась в том, что у пользователя на firebase будет коллекция под названием «заблокировано», и в ней будут документы с именами заблокированных пользователей, затем всякий раз, когда пользователь открывает профиль, приложение проверяет, заблокирован ли пользователь этого профиля, и если они заблокированы, оно просто показывает заголовок, в котором говорится, что пользователь заблокирован, вместо того, чтобы показывать обычную информацию о профиле.
Вот как выглядит код, добавляющий заблокированного пользователя в список:
public func BlockUser(username: String) {
let currentUser = UserDefaults.standard.value(forKey: "username") as! String
let ref = database.collection("users")
.document(currentUser)
.collection("blocked")
.document(username)
ref.setData(["username": username])
}
И это работает, потому что это то, что появляется в firestore:
Итак, затем выполните вторую часть (проверьте, есть ли пользователь профиля в списке заблокированных). Я использую этот код:
public var userIsBlocked: Bool = false
public func IsBlockedByUser(username: String) {
let currentUser = UserDefaults.standard.value(forKey: "username") as! String
let ref = database.collection("users")
.document(currentUser)
.collection("blocked")
.document(username)
ref.getDocument { (document, error) in
if let document = document, document.exists {
self.userIsBlocked = true
} else {
print("Document does not exist")
self.userIsBlocked = false
}
}
}
Однако, даже если пользователь находится в списке заблокированных, когда я открываю его профиль, он все равно печатает «Документ не существует». Я использовал пример кода googles для поиска документа, так почему он его не находит?
Комментарии:
1. Моя авторизация Firebase использует только электронную почту и пароль. Имя пользователя и хранится в Firestore со всеми сообщениями пользователей и прочим. Я не понимаю, почему пользовательские настройки по умолчанию-плохое место для хранения имени пользователя. Не могли бы вы, пожалуйста, объяснить?
2. Извините, я перепутал имя пользователя с идентификатором пользователя. Но я все равно не уверен, что буду хранить имя пользователя по умолчанию, потому что не думаю, что это подходящее место. Я бы подумал о создании объекта, который управляет пользователем, который хранит информацию о пользователе, например имя пользователя, и прослушивает изменения в состоянии аутентификации. При запуске приложения объект заполняется, если пользователь вошел в систему, и сохраняет эту информацию до тех пор, пока пользователь не выйдет из системы. Нет никакой необходимости сохранять эти данные за пределами жизненного цикла приложения, не так ли?
Ответ №1:
Я все еще не вижу проблемы с кодом, который я использовал ранее, но я заменил его запросом, и это, похоже, устранило проблему. Вот новый код, который я использую для поиска, если пользователь заблокирован:
public var userIsBlocked: Bool = false
public func UserIsBlocked(username: String) {
let currentUser = UserDefaults.standard.value(forKey: "username") as! String
let ref = database.collection("users")
.document(currentUser)
.collection("blocked")
ref.whereField("username", isEqualTo: username)
.getDocuments() { (querySnapshot, err) in
if let err = err {
print("Error getting documents: (err)")
self.userIsBlocked = false
} else {
for document in querySnapshot!.documents {
print("(document.documentID) => (document.data())")
self.userIsBlocked = true
}
}
}
}
public var blockedByUser: Bool = false
public func IsBlockedByUser(username: String) {
let currentUser = UserDefaults.standard.value(forKey: "username") as! String
let ref = database.collection("users")
.document(currentUser)
.collection("blockedBy")
ref.whereField("username", isEqualTo: username)
.getDocuments() { (querySnapshot, err) in
if let err = err {
print("Error getting documents: (err)")
self.blockedByUser = false
} else {
for document in querySnapshot!.documents {
print("(document.documentID) => (document.data())")
self.blockedByUser = true
}
}
}
}
А затем, когда открывается профиль пользователя, эти функции вызываются, чтобы проверить, заблокировал ли текущий пользователь пользователя, чей профиль они пытаются просмотреть, или был заблокирован ими. В зависимости от результата двум переменным присваивается значение true или false. Если оба они являются ложными, профиль загружается, а если один из них является истинным, профиль не загружается и отображает предупреждение перед возвращением к предыдущему контроллеру представления. Этот код повсюду, но он выполняет свою работу!