Code

401 Unauthorized Error: What is this HTTP code and how to fix it?

401 Unauthorized Error: What is this HTTP code and how to fix it?

DevOps Basics: An Introduction to System Administration for Beginners

Learn More

When you visit a web page and encounter it being unavailable, it could be due to a variety of factors. One such reason is an authorization error, known as the 401 Unauthorized error. Let's take a closer look at what this error is, what causes it, and how to fix it.

Contents

  • Error 401 means that access to the requested resource is denied due to a lack of proper authentication. This indicates that the user has not provided the required credentials or that they were incorrect. In most cases, this error occurs when servers require authorization, but the user has not logged in or has provided incorrect access data.
  • Error 401 appears when access to the requested resource is denied due to a lack of proper authentication. This means that the server did not receive valid credentials from the client, such as a username and password, or the information provided was incorrect. This error often occurs when the user is not logged in or is using inappropriate credentials. The server, in turn, requires confirmation of identity to grant access to protected resources.
  • Finding ways to resolve issues encountered by users.
  • Proposing solutions to problems for administrators.

The meaning and causes of the 401 error

The 401 Unauthorized error means "unauthorized" access and occurs in situations when a user attempts to access a protected resource but provides incorrect authentication data. For example, this can happen if they enter an incorrect password when attempting to log in to their account on a social networking platform.

The 401 error can be either explicit or hidden. When it is displayed explicitly, the corresponding message appears on the page you are viewing. Depending on the specific web resource, the wording may vary, and instead of the standard text "Error 401 Unauthorized", you may encounter various alternatives:

  • 401 Unauthorized is a status indicating a lack of authorization.
  • Authorization is required.
  • HTTP Error 401 means that there was a problem with authorization.
  • "Authorization failed".
  • Access denied - "access denied".
  • Authentication required.
  • Login failed - "incorrect credentials".
  • Incorrect credentials.
  • Please authorize.
  • An authentication error is a problem related to the process of confirming the user's identity.

When the system encounters an implicit error, it removes the incorrectly entered data and again presents the user with a blank form for login.

Read also:

Identification, authentication, and authorization are three key aspects in information security, and each of them plays its own unique role.

Identification is the process by which the system recognizes user. This stage involves entering data, such as a username or email, that allows the system to understand who is accessing it.

Authentication, in turn, follows identification and involves verifying the user's identity. At this stage, the system requires confirmation, for example, a password or biometric data, to make sure that the person trying to access is the legitimate owner of the account.

Authorization is the final stage that determines what resources and actions are available to the user after successful authentication. The system determines the level of access based on a pre-established policy, allowing or restricting certain operations.

Thus, identification answers the question "Who are you?", authentication - "Are you really who you say you are?", and authorization - "What are you allowed to do?" These three processes work in tandem to ensure security and access control.

To demonstrate a 401 error, you can use the httpstat.us resource. When you navigate to httpstat.us/401, your browser will display a standard login and password entry window. You can enter any data, as the service will ignore it and eventually return a 401 error without displaying any notifications on the page.

Let's turn to the browser's developer tools (DevTools) and make sure we are indeed getting the error we expect.

  • Please go to the following address: httpstat.us/401.
  • Launch the developer tools by pressing F12 or using the keyboard shortcut Ctrl + Shift + I, which works in most web browsers.
  • Open the "Network" section.
  • Enter your credentials - login and password - to attempt to access the protected resource.
  • Find the message with the 401 code in the list of requests.
  • Click on it to view the full details.
Demonstration of error 401 in the Opera browser via the httpstat.us service Screenshot: Opera / httpstat.us / Skillbox Media

Read also:

Chrome DevTools: Key Tools and Their Practical Application

Chrome DevTools is a powerful set of tools built into the Google Chrome browser, which is designed for web application developers. These tools allow you to analyze and debug code, as well as optimize website performance.

One of the main features is the Elements panel, where you can view and edit HTML and CSS in real time. This allows you to quickly make changes and see the results immediately, which significantly speeds up the development process.

The Console panel is used to execute JavaScript code and display error messages. It allows developers to interact with the web page, debug scripts, and perform diagnostics.

Another important function is Network, which helps monitor server requests, loaded resources, and response time. This information is critical for optimizing page loading speed and eliminating bottlenecks.

The Performance panel allows you to analyze application performance by recording actions and evaluating how long various operations take. Using the data obtained, you can identify problem areas and optimize them.

The Sources tool provides access to the source code, including the ability to set breakpoints and step through JavaScript code, which simplifies the process of finding errors.

In addition, Application Allows you to view data stored in the browser, such as cookies and local storage, which helps manage application state.

These and many other features of Chrome DevTools make it an indispensable assistant for web developers, providing powerful tools for analyzing, debugging, and optimizing web applications.

Factors Contributing to the Error

The 401 error can appear for several reasons, including incorrect user authorization data, technical failures on the client or server side, and issues related to APIs and tokens. Let's take a closer look at each of these reasons.

Incorrect user authentication is an issue that is most often associated with security measures and mechanisms designed to prevent unauthorized access. The main factors that contribute to such situations include:

  • An incorrect login or password was entered when attempting to log into the system.
  • A page access error may occur when a user attempts to open a restricted area without the required subscription or when attempting to log into the admin panel without administrator rights.
  • The administrator can block an account, which can be either temporary or permanent. This decision is usually made in the event of a violation of the terms of service or in the presence of suspicious activity.
  • An IP address may be automatically blocked in the event of multiple unsuccessful login attempts. For example, if there are five or more unsuccessful attempts within 15 minutes, the system has the ability to restrict access from a given IP for up to one hour.

Read also:

Nine Best Password Managers for Everyday Use

Client-side issues are often related to the characteristics of the device or browser the user is using.

  • Incorrect caching of account information can cause the browser to retain old login information even if the user has changed their password.
  • Difficulties related to cookies and user sessions can arise in various situations. For example, when using incognito mode in a browser, it can inadvertently block or delete cookies, which, in turn, can lead to the loss of login information.
  • There are difficulties with time coordination between the server and the client. When the time difference exceeds five minutes, the security system may interpret this as a potential threat and restrict access. Similar issues are often encountered when using virtual machines, when their time does not match the time of the main computer.
  • Old or incompatible browser extensions can cause problems. This is especially true for add-ons that are designed to block ads or improve security. Such extensions can block critical scripts responsible for authorization or interfere with the correct operation of cookies.

Read also:

Everything you need to know about cookies is collected in this article.

Difficulties arising on the server side require the assistance of a system administrator or technical support. The reason is that they are related to the server infrastructure and security settings.

  • Configuration errors on the hosting provider's side can manifest themselves in the form of incorrect configuration of servers such as Apache or Nginx. This can also concern incorrectly configured rules for processing HTTP headers and restrictions on the maximum number of simultaneous connections.
  • The problem of insecure SSL/TLS certificates occurs when using certificates that have expired or are self-signed. Browsers regard such certificates as insecure.
  • Inappropriate operation of security plugins can cause various problems. For example, a conflict may arise between a plugin for two-factor authentication in WordPress and a plugin designed to protect against brute-force attacks. As a result, users may sometimes experience false positives or difficulties when attempting to log in.
  • There are conflicts between different authentication methods. For example, an application combines OAuth 2.0 and HTTP Basic Authentication. While OAuth 2.0 uses tokens for authorization, HTTP Basic Authentication requires a username and password. This may cause confusion about the user's current authorization status.

Read also:

OAuth 2.0 is an authorization protocol that allows third-party applications to gain limited access to a user's resources without having to disclose their credentials. The basic idea is that a user can grant access to their data on one service to another application while remaining confident in the security of their information.

OAuth 2.0 works by using access tokens. When a user wants a third-party application to interact with their account on a specific service, they initiate the authorization process. During this process, the user is redirected to an authorization page where they are asked to log in to their account and confirm that they allow access to the specified data.

Upon successful authorization, the service issues a special token, which the application uses to access the user's resources. This token has a limited validity period and can be configured to grant access only to specific data, adding an additional layer of security. Thus, OAuth 2.0 ensures the protection of personal information while allowing users to easily manage access to their data.

API and token-related errors present difficulties that arise during interactions between different services and applications.

  • Using expired access tokens can be a problem. For example, if a token expires after 24 hours, and the application continues to use it instead of requesting a new one.
  • Invalid API requests can occur when an application uses an invalid data format for sending. For example, if the server expects to receive data as a JSON object, but the client instead transmits information in XML format or leaves required fields blank.
  • Incorrect validation of timestamps in authentication tokens. If the time on the client and server does not match, there is a chance that the token will be rejected, since the system may interpret it as created in the future.

Read also:

API, or application programming interface An API is a set of rules and protocols that allow various software applications to interact with each other. It serves as a kind of intermediary, enabling the exchange of data and functionality between systems. An API can be thought of as a simple interaction between a client and a server. When an application or user requests information or a service, it sends a request through the API. This request contains the necessary parameters that allow the server to understand what exactly needs to be done. The server, upon receiving the request, processes it and returns a response, which is also structured according to certain standards. This response may contain data or confirmation of the operation. Thus, an API simplifies the integration and interoperability of various software solutions, allowing developers to focus on creating new features without delving into the details of each system.

Ultimately, APIs play a key role in modern programming, providing flexibility and the ability to extend application functionality.

Troubleshooting Methods for Users

This section presents the basic steps for resolving the 401 error. We recommend using a process of elimination to isolate the cause of the problem: refresh the page after each step and check if the error persists. If one of the suggested solutions does not work, proceed to the next.

Please ensure that the credentials you have entered are correct. Ensure that the letter case and input language comply with the requirements, and make sure that your username and password do not contain any accidental spaces or extra characters. For example, if your username is user@example.com, entering User@example.com will result in an error.

Check that you have the necessary permissions to access the requested page. Certain sections of the site may be accessible only to administrators or users with premium access. Attempting to access such areas with a standard account may result in an error.

To clear outdated authentication data, you need to clear the cache and cookies from your browser. To do this, follow the instructions below:

  • Go to your browser settings and find the section dedicated to History or Privacy.
  • Determine the time period for clearing. For example, it could be "For the last hour" or "For the entire period".
  • Select the options Cookies and Site data, and then proceed to clearing data from your browser.

After clearing, you will need to log in to your accounts on all resources again. If your browser supports this feature, we recommend deleting cookies only for the website that is causing the problem.

Make sure the time on your device is synchronized. Correct time settings are essential for the effective functioning of security systems, as they rely on timestamps to verify authorization tokens.

For example, if your computer is 15 minutes behind schedule and you try to log in to a banking app, the system may deny you access, considering the authentication token invalid. To prevent such situations, we recommend enabling automatic time synchronization on your device. This feature is available on all popular operating systems, including Windows, Linux, macOS, Android, and iOS.

To resolve conflicts between browser extensions, follow these steps:

  • To open your browser's add-ons menu, look for the puzzle icon, usually located in the upper-right corner of the screen.
  • Temporarily pause all extensions using the corresponding toggles.
  • Try refreshing the page and see if the error is resolved. If it is, activate the extensions one by one to identify the one causing the problem.

Pay close attention to security and ad-blocking extensions, as they most often cause authorization conflicts.

If you cannot identify the conflicting extensions, you should try launching the browser in incognito mode. This will help determine whether the problem is related to your profile. If the error persists in incognito mode, try opening the website in a different browser. Sometimes the cause can be hidden in its settings or in a corrupted user profile.

Read also:

A browser is a program designed to access Internet resources and display their content. Using a browser, users can view web pages, interact with various services, and download files.

There are many types of browsers, each with different functionality and features. The most popular include Google Chrome, Mozilla Firefox, Safari, Microsoft Edge, and Opera. Each has its own unique features, such as extension support, built-in protection against malicious sites, and different ways to organize bookmarks and tabs.

Browsers are multitasking: they allow you to view text and graphics, play video and audio, support online communication via chats and video calls, and provide access to social media and email services. Additionally, modern browsers often include tools to protect user privacy and security settings while browsing the internet.

Flush your DNS cache. DNS is a system that translates human-readable website names into the IP addresses used by devices. Clearing the DNS cache can help resolve access issues by removing stale or corrupted records.

Flushing the DNS should be done at the operating system level, as this system service is responsible for converting domain names to IP addresses.

  • To flush the DNS cache in Windows, you need to run the command prompt with administrator privileges. To do this, enter the following command: ipconfig /flushdns.
  • For macOS, open Terminal and enter the following command: sudo killall -HUP mDNSResponder. When prompted, enter your administrator password.
  • If you are using Linux, open a terminal and run one of the following commands: sudo resolvectl flush-caches or sudo systemd-resolve —flush-caches.

Once the DNS cache is cleared, it is recommended to restart the browser for the changes to take effect.

Read also:

If you're experiencing DNS server unavailability, follow this course of action to resolve the issue.

1. Check your internet connection. Make sure your device is actually connected to the network. Try visiting multiple websites or rebooting your router.

2. Restart your device. Sometimes, simply rebooting your computer or mobile device can fix temporary issues.

3. Check your DNS settings. Open your device's network settings and make sure the correct DNS servers are specified. You can use public DNS servers such as Google (8.8.8.8 and 8.8.4.4) or Cloudflare (1.1.1.1).

4. Flush your DNS cache. In the command prompt, enter the command to flush the DNS cache. On Windows, this is `ipconfig /flushdns`, and on Mac, this is `sudo killall -HUP mDNSResponder`.

5. Check your firewall and antivirus. Sometimes security software can block access to DNS servers. Try temporarily disabling these programs and see if this solves the problem.

6. Contact your ISP. If all the above steps do not help, there may be a problem with your ISP. Contact technical support for information about the status of their DNS servers.

7. Check for updates. Make sure your device's operating system and network drivers are updated to the latest version.

By following this plan, you can fix DNS server unavailability issues and restore normal internet service.

Make sure your antivirus software and firewall are working properly. Sometimes security systems can perceive a website as a threat and restrict access to it. In this case, it's worth temporarily disabling your antivirus and firewall. If this resolves the issue, add the resource in question to the exceptions list.

Make sure your internet connection is working. Try logging into your account using a different network or mobile data. If the login is successful, restart the router and try logging in again.

If the issues persist, we recommend contacting your provider's technical support and explaining the problem in detail. Don't forget to mention the troubleshooting methods you've already tried and include a screenshot of the error you encountered.

Read also:

Ways to get your Wi-Fi password: a complete guide

If you need to know your password from a Wi-Fi network, there are several methods that can help with this. Here are the main ones:

1. Look at the router. On most devices, this code can be found on a sticker located on their case. Typically, both the network name (SSID) and the password are indicated there.

2. Check the settings of your device. If you are already connected to Wi-Fi, you can go to the connection settings on your computer or smartphone. In the Wi-Fi settings, find information about current networks, and there will be an option to display the password.

3. Use the command line. On Windows devices, you can open the command line and run a command to get the password of the network you are connected to. This is quite simple and does not require deep technical knowledge.

4. Use network management applications. There are various programs that can help you extract passwords from saved networks. However, be careful when choosing such applications and check their reliability.

5. If you have access to your router, you can access its web interface by entering the router's IP address in your browser. After logging in, you'll find a section dedicated to wireless settings, where the password will be listed.

6. If you've forgotten your password and can't access it, you can reset your router to factory settings. You'll then be able to set a new password, but keep in mind that doing so will lose all previous settings.

These methods will help you find your Wi-Fi password and restore network access.

Troubleshooting Tips for Website Administrators

When multiple users experience the same issue or the 401 error isn't resolved by standard methods, the administrator should conduct a comprehensive system check. This includes running server diagnostics, analyzing configuration files, examining error logs and logs, monitoring network traffic, auditing the authorization system, and performing other necessary checks.

To begin diagnosing the server-side issue, you should verify the accessibility of the problematic pages using various devices and browsers. Start by testing the site on a desktop computer, checking it in Chrome, Firefox, and Safari. Then, perform a similar test on a mobile phone and tablet. If the resource functions without errors in at least one browser or on another device, the problem is most likely with your primary browser. In this situation, clearing the cache and cookies will be sufficient.

If an error occurs on various devices and in all browsers, you should contact your hosting provider's technical support.

  • Please attach screenshots of the errors and server logs.
  • Specify the exact moment the problem occurred.
  • Specify the steps taken before the error occurred.

Hosting experts will conduct the necessary checks to eliminate possible problems on their side. They will evaluate server availability, the correctness of DNS settings, the functioning of SSL certificates, firewall settings, and web server configuration. They can often quickly identify the source of the problem by analyzing server logs.

A server configuration check is necessary. If the cause of the problem is not related to the hosting, the administrator should carefully review the server settings that may be causing authorization failures. To do this:

  • Review the web server settings specified in Apache configuration files, such as .htaccess and httpd.conf. These documents contain access rules and authorization settings that govern access to various parts of the site. For more information, see the Authentication and Authorization Guide.
  • Pay attention to the security settings and session parameters in the PHP configuration file (php.ini). It is important to carefully check the values ​​of session.gc_maxlifetime, which controls the session lifespan, and session.cookie_lifetime, which determines how long cookies will be stored. These settings affect how long a user can remain logged in without having to log in again. Additional information can be found in the PHP session configuration documentation.
  • Check your firewall configuration and the rules in .htaccess that control access. Also, make sure that your SSL certificates are valid and current. Additionally, it's important to audit file permissions and ownership using the chmod and chown commands. More detailed information on security measures can be found in the Apache documentation's section on security tips.

Analyzing Error and Log Files. Once the server configuration has been verified, it's important to analyze Apache log files, such as error.log and access.log. These files may contain information about authorization errors. You should also pay attention to system logs to identify potential access rights issues. For more information on working with log files, we recommend consulting the documentation: Log Files.

Network traffic analysis. If the logs fail to identify the problem, a detailed analysis of network requests should be performed. Check that authorization headers are being transmitted correctly and that there are no network-level blockages. Tools such as Wireshark and its analogs are suitable for this purpose. Additional information on traffic monitoring can be found in the Wireshark documentation.

Audit the authorization mechanism. If the problem remains unresolved after analyzing the network traffic, it is worth investigating whether the system is preventing users with valid credentials from logging in. This may be due to errors in session token processing, incorrect database settings, or insufficient access rights for certain user groups.

Tools and platforms designed to test the functionality of the authentication system:

  • Burp Suite is a utility designed to monitor data transfer between a web browser and a server during the authentication process. This tool helps detect various security flaws, including insecure password transmission and session management errors. OWASP ZAP is a web application analysis tool that specializes in identifying vulnerabilities in authentication mechanisms. This scanner can detect flaws such as lack of protection against brute-force attacks and identify instances where authentication data is transmitted without proper security. It also finds XSS and SQL injection vulnerabilities that can be used by attackers to bypass authentication systems. Selenium is a tool designed for automated testing of authorization and access control processes. It can be used to emulate the login of various users with different roles, such as administrator, moderator, or regular user. This allows you to test access to secure sections of the website, as well as test the functionality of login and password recovery forms.
  • Postman is an API testing tool that provides authentication capabilities and token functionality testing. Using this platform, you can send API requests using various tokens and examine the responses received from the server. This allows you to evaluate whether tokens are being created and renewed correctly, how the server checks their expiration date, and how the API reacts to invalid or expired tokens.

Read also:

Postman is a tool Designed for working with APIs, it allows developers and testers to easily send requests to and receive responses from servers. It offers a user-friendly interface that makes interacting with APIs intuitive and accessible. To start using Postman, you first need to install the application on your computer or use the web version. Once installed, you can create a new request by specifying its type (GET, POST, PUT, DELETE, etc.) and entering the API endpoint address. Depending on the API's requirements, you can add headers, query parameters, and a body with data. Postman also allows you to save requests and organize them into collections, making it much easier to manage multiple requests. You can share these collections with colleagues or use them to test various scenarios. Additionally, the tool supports test automation and integration with other services, making it a powerful assistant in software development. Additional checks. If the 401 error continues to occur after auditing the authentication system, we recommend the following steps:

  • Check your cache. Incorrect cache operation can cause authentication issues because outdated session information may be used. You can use tools such as Redis CLI or phpRedisAdmin for this purpose.
  • We recommend scanning for malware, as it can capture authentication data or establish hidden access points. You can use tools such as ClamAV, Malwarebytes, or VirusTotal for this purpose.
  • Make sure the plugins and modules responsible for authentication are working correctly. Conflicts between different plugins often cause authentication failures. To identify the problematic plugin, disable them one by one using Debug Bar or Query Monitor.
  • Update elements of the authentication system. Old versions may contain vulnerabilities that threaten your site's security and can cause login issues. Tools such as Composer Version Check and WP-CLI can be used to check if your versions are up-to-date.

If these checks are inconclusive, consider contacting the developers of the content management system or framework used for your site. They may be able to help diagnose the cause of the 401 error or offer a ready-made solution.

Also, you have the option of having an independent expert conduct a system audit or restore your site to the latest stable version using a backup.

When troubleshooting, it's important to record all steps you take and their results. This approach will not only prevent the recurrence of this problem, but will also significantly simplify the process of resolving similar situations in the future.

Read also:

Backup: what is it, why is it needed and how to use it implement.

What's next?

If none of the described methods bring results, it is recommended to refer to the technical documentation for a possible solution. Here are some useful resources regarding the 401 error:

  • MDN Web Docs provides a detailed explanation of the HTTP 401 Unauthorized error, including its causes and features.
  • OAuth 2.0 is a specification that describes an authorization protocol that often results in 401 errors.
  • RFC 7235 is a document that regulates issues related to authentication in the HTTP protocol. It sets out security principles, as well as methods for handling errors that occur due to lack of authorization, in particular the 401 code.

For more information about the code, join our Telegram channel. We'll be glad to see you among our subscribers!

Read also:

  • HTTP, or the Hypertext Transfer Protocol, is the fundamental protocol used to exchange data on the Internet. It plays a key role in enabling communication between web servers and clients such as browsers.

    The main purpose of HTTP is to allow users to request and receive various resources, including text pages, images, and videos. When you enter a website address in your browser, an HTTP request is sent to the server, which processes the request and returns the desired content.

    Thus, HTTP is the primary tool that enables interaction on the network and allows users to access information posted on various web resources.

  • "I'm Tired of Working in a Warehouse": A Story About Test Engineer Alexey Vdovin.
  • Error 403, also known as "Access Denied," occurs when the server refuses to provide access to the requested resource. This can happen for several reasons, including insufficient permissions to view the page or restricted access for certain users or groups.

    If you encounter this error, there are several ways to resolve it. First, check that the URL you entered is correct; sometimes the error can be caused by a typo. If the address is correct, try clearing your browser cache and cookies, as outdated data can cause access issues.

    If you are a site administrator, ensure that file and folder permissions are set correctly. Check your web server configuration and ensure that the necessary permissions are granted. If access to the resource is restricted at the IP address level, you may need to whitelist your address.

    If none of these steps help, you should contact your hosting support team or site administrator for further assistance.

For more exciting coding content, join our Telegram channel. We will be glad to see you among our subscribers!

DevOps Fundamentals: A Path to System Administration for Beginners

You will master the skills of administering the Linux operating system, learn how to configure web servers and ensure the smooth operation of websites. This will give you the opportunity to start a career as a system administrator and provide fundamental knowledge for further growth in the field of DevOps engineering.

Learn more