A clear explanation from Daniel Irvine [original link]:
There’s a problem with 401 Unauthorized, the HTTP status code for authentication errors. And that’s just it: it’s for authentication, not authorization.
Receiving a 401 response is the server telling you, “you aren’t
authenticated–either not authenticated at all or authenticated
incorrectly–but please reauthenticate and try again.” To help you out,
it will always include a WWW-Authenticate header that describes how
to authenticate.This is a response generally returned by your web server, not your web
application.It’s also something very temporary; the server is asking you to try
again.So, for authorization I use the 403 Forbidden response. It’s
permanent, it’s tied to my application logic, and it’s a more concrete
response than a 401.Receiving a 403 response is the server telling you, “I’m sorry. I know
who you are–I believe who you say you are–but you just don’t have
permission to access this resource. Maybe if you ask the system
administrator nicely, you’ll get permission. But please don’t bother
me again until your predicament changes.”In summary, a 401 Unauthorized response should be used for missing
or bad authentication, and a 403 Forbidden response should be used
afterwards, when the user is authenticated but isn’t authorized to
perform the requested operation on the given resource.
Another nice pictorial format of how http status codes should be used.
Nick T
25.2k11 gold badges79 silver badges120 bronze badges
answered Aug 4, 2011 at 6:24
23
Edit: RFC2616 is obsolete, see RFC9110.
401 Unauthorized:
If the request already included Authorization credentials, then the 401 response indicates that authorization has been refused for those credentials.
403 Forbidden:
The server understood the request, but is refusing to fulfill it.
From your use case, it appears that the user is not authenticated. I would return 401.
emery
8,03510 gold badges42 silver badges49 bronze badges
answered Jul 21, 2010 at 7:28
OdedOded
485k98 gold badges877 silver badges1003 bronze badges
11
Something the other answers are missing is that it must be understood that Authentication and Authorization in the context of RFC 2616 refers ONLY to the HTTP Authentication protocol of RFC 2617. Authentication by schemes outside of RFC2617 is not supported in HTTP status codes and are not considered when deciding whether to use 401 or 403.
Brief and Terse
Unauthorized indicates that the client is not RFC2617 authenticated and the server is initiating the authentication process. Forbidden indicates either that the client is RFC2617 authenticated and does not have authorization or that the server does not support RFC2617 for the requested resource.
Meaning if you have your own roll-your-own login process and never use HTTP Authentication, 403 is always the proper response and 401 should never be used.
Detailed and In-Depth
From RFC2616
10.4.2 401 Unauthorized
The request requires user authentication. The response MUST include a WWW-Authenticate header field (section 14.47) containing a challenge applicable to the requested resource. The client MAY repeat the request with a suitable Authorization header field (section 14.8).
and
10.4.4 403 Forbidden
The server understood the request but is refusing to fulfil it. Authorization will not help and the request SHOULD NOT be repeated.
The first thing to keep in mind is that «Authentication» and «Authorization» in the context of this document refer specifically to the HTTP Authentication protocols from RFC 2617. They do not refer to any roll-your-own authentication protocols you may have created using login pages, etc. I will use «login» to refer to authentication and authorization by methods other than RFC2617
So the real difference is not what the problem is or even if there is a solution. The difference is what the server expects the client to do next.
401 indicates that the resource can not be provided, but the server is REQUESTING that the client log in through HTTP Authentication and has sent reply headers to initiate the process. Possibly there are authorizations that will permit access to the resource, possibly there are not, but let’s give it a try and see what happens.
403 indicates that the resource can not be provided and there is, for the current user, no way to solve this through RFC2617 and no point in trying. This may be because it is known that no level of authentication is sufficient (for instance because of an IP blacklist), but it may be because the user is already authenticated and does not have authority. The RFC2617 model is one-user, one-credentials so the case where the user may have a second set of credentials that could be authorized may be ignored. It neither suggests nor implies that some sort of login page or other non-RFC2617 authentication protocol may or may not help — that is outside the RFC2616 standards and definition.
Edit: RFC2616 is obsolete, see RFC7231 and RFC7235.
answered Feb 5, 2013 at 17:14
ldrutldrut
3,7771 gold badge17 silver badges4 bronze badges
7
+----------------------- | RESOURCE EXISTS ? (if private it is often checked AFTER auth check) +----------------------- | | NO | v YES v +----------------------- 404 | IS LOGGED-IN ? (authenticated, aka user session) or +----------------------- 401 | | 403 NO | | YES 3xx v v 401 +----------------------- (404 no reveal) | CAN ACCESS RESOURCE ? (permission, authorized, ...) or +----------------------- redirect | | to login NO | | YES | | v v 403 OK 200, redirect, ... (or 404: no reveal) (or 404: resource does not exist if private) (or 3xx: redirection)
Checks are usually done in this order:
- 404 if resource is public and does not exist or 3xx redirection
- OTHERWISE:
- 401 if not logged-in or session expired
- 403 if user does not have permission to access resource (file, json, …)
- 404 if resource does not exist or not willing to reveal anything, or 3xx redirection
UNAUTHORIZED: Status code (401) indicating that the request requires authentication, usually this means user needs to be logged-in (session). User/agent unknown by the server. Can repeat with other credentials. NOTE: This is confusing as this should have been named ‘unauthenticated’ instead of ‘unauthorized’. This can also happen after login if session expired.
Special case: Can be used instead of 404 to avoid revealing presence or non-presence of resource (credits @gingerCodeNinja)
FORBIDDEN: Status code (403) indicating the server understood the request but refused to fulfill it. User/agent known by the server but has insufficient credentials. Repeating request will not work, unless credentials changed, which is very unlikely in a short time span.
Special case: Can be used instead of 404 to avoid revealing presence or non-presence of resource (credits @gingerCodeNinja) in the case that revealing the presence of the resource exposes sensitive data or gives an attacker useful information.
NOT FOUND: Status code (404) indicating that the requested resource is not available. User/agent known but server will not reveal anything about the resource, does as if it does not exist. Repeating will not work. This is a special use of 404 (github does it for example).
As mentioned by @ChrisH there are a few options for redirection 3xx (301, 302, 303, 307 or not redirecting at all and using a 401):
- Difference between HTTP redirect codes
- How long do browsers cache HTTP 301s?
- What is correct HTTP status code when redirecting to a login page?
- What’s the difference between a 302 and a 307 redirect?
answered Feb 23, 2015 at 11:00
9
According to RFC 2616 (HTTP/1.1) 403 is sent when:
The server understood the request, but is refusing to fulfill it. Authorization will not help and the request SHOULD NOT be repeated. If the request method was not HEAD and the server wishes to make public why the request has not been fulfilled, it SHOULD describe the reason for the refusal in the entity. If the server does not wish to make this information available to the client, the status code 404 (Not Found) can be used instead
In other words, if the client CAN get access to the resource by authenticating, 401 should be sent.
answered Jul 21, 2010 at 7:26
CumbayahCumbayah
4,3771 gold badge24 silver badges32 bronze badges
6
Assuming HTTP authentication (WWW-Authenticate and Authorization headers) is in use, if authenticating as another user would grant access to the requested resource, then 401 Unauthorized should be returned.
403 Forbidden is used when access to the resource is forbidden to everyone or restricted to a given network or allowed only over SSL, whatever as long as it is no related to HTTP authentication.
If HTTP authentication is not in use and the service has a cookie-based authentication scheme as is the norm nowadays, then a 403 or a 404 should be returned.
Regarding 401, this is from RFC 7235 (Hypertext Transfer Protocol (HTTP/1.1): Authentication):
3.1. 401 Unauthorized
The 401 (Unauthorized) status code indicates that the request has not been applied because it lacks valid authentication credentials for the target resource. The origin server MUST send a WWW-Authenticate header field (Section 4.4) containing at least one challenge applicable to the target resource. If the request included authentication credentials, then the 401 response indicates that authorization has been refused for those credentials. The client MAY repeat the request with a new or replaced Authorization header field (Section 4.1). If the 401 response contains the same challenge as the prior response, and the user agent has already attempted authentication at least once, then the user agent SHOULD present the enclosed representation to the user, since it usually contains relevant diagnostic information.
The semantics of 403 (and 404) have changed over time. This is from 1999 (RFC 2616):
10.4.4 403 Forbidden
The server understood the request, but is refusing to fulfill it. Authorization will not help and the request SHOULD NOT be repeated. If the request method was not HEAD and the server wishes to make public why the request has not been fulfilled, it SHOULD describe the reason for the refusal in the entity. If the server does not wish to make this information available to the client, the status code 404 (Not Found) can be used instead.
In 2014 RFC 7231 (Hypertext Transfer Protocol (HTTP/1.1): Semantics and Content) changed the meaning of 403:
6.5.3. 403 Forbidden
The 403 (Forbidden) status code indicates that the server understood the request but refuses to authorize it. A server that wishes to make public why the request has been forbidden can describe that reason in the response payload (if any).
If authentication credentials were provided in the request, the server considers them insufficient to grant access. The client SHOULD NOT automatically repeat the request with the same credentials. The client MAY repeat the request with new or different credentials. However, a request might be forbidden for reasons unrelated to the credentials.
An origin server that wishes to «hide» the current existence of a forbidden target resource MAY instead respond with a status code of 404 (Not Found).
Thus, a 403 (or a 404) might now mean about anything. Providing new credentials might help… or it might not.
I believe the reason why this has changed is RFC 2616 assumed HTTP authentication would be used when in practice today’s Web apps build custom authentication schemes using for example forms and cookies.
answered Feb 27, 2013 at 9:44
6
- 401 Unauthorized: I don’t know who you are. This an authentication error.
- 403 Forbidden: I know who you are, but you don’t have permission to access this resource. This is an authorization error.
Premraj
72.1k25 gold badges236 silver badges175 bronze badges
answered Aug 6, 2019 at 12:37
4
This is an older question, but one option that was never really brought up was to return a 404. From a security perspective, the highest voted answer suffers from a potential information leakage vulnerability. Say, for instance, that the secure web page in question is a system admin page, or perhaps more commonly, is a record in a system that the user doesn’t have access to. Ideally you wouldn’t want a malicious user to even know that there’s a page / record there, let alone that they don’t have access. When I’m building something like this, I’ll try to record unauthenticate / unauthorized requests in an internal log, but return a 404.
OWASP has some more information about how an attacker could use this type of information as part of an attack.
answered Dec 25, 2014 at 9:09
5
This question was asked some time ago, but people’s thinking moves on.
Section 6.5.3 in this draft (authored by Fielding and Reschke) gives status code 403 a slightly different meaning to the one documented in RFC 2616.
It reflects what happens in authentication & authorization schemes employed by a number of popular web-servers and frameworks.
I’ve emphasized the bit I think is most salient.
6.5.3. 403 Forbidden
The 403 (Forbidden) status code indicates that the server understood the request but refuses to authorize it. A server that wishes to make public why the request has been forbidden can describe that reason in the response payload (if any).
If authentication credentials were provided in the request, the server considers them insufficient to grant access. The client SHOULD NOT repeat the request with the same credentials. The client MAY repeat the request with new or different credentials. However, a request might be forbidden for reasons unrelated to the credentials.
An origin server that wishes to «hide» the current existence of a forbidden target resource MAY instead respond with a status code of 404 (Not Found).
Whatever convention you use, the important thing is to provide uniformity across your site / API.
answered May 22, 2014 at 10:54
Dave WattsDave Watts
8407 silver badges11 bronze badges
1
These are the meanings:
401: User not (correctly) authenticated, the resource/page require authentication
403: User’s role or permissions does not allow to access requested resource, for instance user is not an administrator and requested page is for administrators.
Note: Technically, 403 is a superset of 401, since is legal to give 403 for unauthenticated user too. Anyway is more meaningful to differentiate.
answered Nov 19, 2019 at 10:17
Luca C.Luca C.
11.1k1 gold badge86 silver badges77 bronze badges
3
!!! DEPR: The answer reflects what used to be common practice, up until 2014 !!!
TL;DR
- 401: A refusal that has to do with authentication
- 403: A refusal that has NOTHING to do with authentication
Practical Examples
If apache requires authentication (via .htaccess
), and you hit Cancel
, it will respond with a 401 Authorization Required
If nginx finds a file, but has no access rights (user/group) to read/access it, it will respond with 403 Forbidden
RFC (2616 Section 10)
401 Unauthorized (10.4.2)
Meaning 1: Need to authenticate
The request requires user authentication. …
Meaning 2: Authentication insufficient
… If the request already included Authorization credentials, then the 401 response indicates that authorization has been refused for those credentials. …
403 Forbidden (10.4.4)
Meaning: Unrelated to authentication
… Authorization will not help …
More details:
The server understood the request, but is refusing to fulfill it.
It SHOULD describe the reason for the refusal in the entity
The status code 404 (Not Found) can be used instead
(If the server wants to keep this information from client)
answered Feb 25, 2015 at 9:03
LeviteLevite
16.9k8 gold badges50 silver badges50 bronze badges
2
they are not logged in or do not belong to the proper user group
You have stated two different cases; each case should have a different response:
- If they are not logged in at all you should return 401 Unauthorized
- If they are logged in but don’t belong to the proper user group, you should return 403 Forbidden
Note on the RFC based on comments received to this answer:
If the user is not logged in they are un-authenticated, the HTTP equivalent of which is 401 and is misleadingly called Unauthorized in the RFC. As section 10.4.2 states for 401 Unauthorized:
«The request requires user authentication.»
If you’re unauthenticated, 401 is the correct response. However if you’re unauthorized, in the semantically correct sense, 403 is the correct response.
answered Oct 1, 2012 at 14:34
Zaid MasudZaid Masud
13.1k9 gold badges66 silver badges88 bronze badges
4
I have created a simple note for you which will make it clear.
answered Nov 11, 2021 at 12:19
PrathamPratham
4673 silver badges7 bronze badges
In English:
401
You are potentially allowed access but for some reason on this request you were
denied. Such as a bad password? Try again, with the correct request
you will get a success response instead.
403
You are not, ever, allowed. Your name is not on the list, you won’t
ever get in, go away, don’t send a re-try request, it will be refused,
always. Go away.
answered Apr 8, 2020 at 14:23
JamesJames
4,6155 gold badges36 silver badges48 bronze badges
2
401: You need HTTP basic auth to see this.
If the user just needs to log in using you site’s standard HTML login form, 401 would not be appropriate because it is specific to HTTP basic auth.
403: This resource exists but you are not authorized to see it, and HTTP basic auth won’t help.
I don’t recommend using 403 to deny access to things like /includes
, because as far as the web is concerned, those resources don’t exist at all and should therefore 404.
In other words, 403 means «this resource requires some form of auth other than HTTP basic auth (such as using the web site’s standard HTML login form)».
https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.2
answered Sep 23, 2017 at 12:33
Vlad KorneaVlad Kornea
4,2493 gold badges38 silver badges40 bronze badges
401: Who are you again?? (programmer walks into a bar with no ID or invalid ID)
403: Oh great, you again. I’ve got my eye on you. Go on, get outta here. (programmer walks into a bar they are 86’d from)
answered Aug 11, 2022 at 23:10
emeryemery
8,03510 gold badges42 silver badges49 bronze badges
0
I think it is important to consider that, to a browser, 401 initiates an authentication dialog for the user to enter new credentials, while 403 does not. Browsers think that, if a 401 is returned, then the user should re-authenticate. So 401 stands for invalid authentication while 403 stands for a lack of permission.
Here are some cases under that logic where an error would be returned from authentication or authorization, with important phrases bolded.
- A resource requires authentication but no credentials were specified.
401: The client should specify credentials.
- The specified credentials are in an invalid format.
400: That’s neither 401 nor 403, as syntax errors should always return 400.
- The specified credentials reference a user which does not exist.
401: The client should specify valid credentials.
- The specified credentials are invalid but specify a valid user (or don’t specify a user if a specified user is not required).
401: Again, the client should specify valid credentials.
- The specified credentials have expired.
401: This is practically the same as having invalid credentials in general, so the client should specify valid credentials.
- The specified credentials are completely valid but do not suffice the particular resource, though it is possible that credentials with more permission could.
403: Specifying valid credentials would not grant access to the resource, as the current credentials are already valid but only do not have permission.
- The particular resource is inaccessible regardless of credentials.
403: This is regardless of credentials, so specifying valid credentials cannot help.
- The specified credentials are completely valid but the particular client is blocked from using them.
403: If the client is blocked, specifying new credentials will not do anything.
answered Jun 2, 2018 at 23:34
401
response means one of the following:
- An access token is missing.
- An access token is either expired, revoked, malformed, or invalid.
403
response on the other hand means that the access token is indeed valid, but that the user does not have appropriate privileges to perform the requested action.
answered Feb 17, 2022 at 11:16
Ran TurnerRan Turner
12.7k4 gold badges38 silver badges48 bronze badges
0
Given the latest RFC’s on the matter (7231 and 7235) the use-case seems quite clear (italics added):
- 401 is for unauthenticated («lacks valid authentication»); i.e. ‘I don’t know who you are, or I don’t trust you are who you say you are.’
401 Unauthorized
The 401 (Unauthorized) status code indicates that the request has not
been applied because it lacks valid authentication credentials for
the target resource. The server generating a 401 response MUST send
a WWW-Authenticate header field (Section 4.1) containing at least one
challenge applicable to the target resource.
If the request included authentication credentials, then the 401
response indicates that authorization has been refused for those
credentials. The user agent MAY repeat the request with a new or
replaced Authorization header field (Section 4.2). If the 401
response contains the same challenge as the prior response, and the
user agent has already attempted authentication at least once, then
the user agent SHOULD present the enclosed representation to the
user, since it usually contains relevant diagnostic information.
- 403 is for unauthorized («refuses to authorize»); i.e. ‘I know who you are, but you don’t have permission to access this resource.’
403 Forbidden
The 403 (Forbidden) status code indicates that the server understood
the request but refuses to authorize it. A server that wishes to
make public why the request has been forbidden can describe that
reason in the response payload (if any).
If authentication credentials were provided in the request, the
server considers them insufficient to grant access. The client
SHOULD NOT automatically repeat the request with the same
credentials. The client MAY repeat the request with new or different
credentials. However, a request might be forbidden for reasons
unrelated to the credentials.
An origin server that wishes to «hide» the current existence of a
forbidden target resource MAY instead respond with a status code of
404 (Not Found).
answered Jun 5, 2018 at 15:26
cjbarthcjbarth
4,0526 gold badges41 silver badges60 bronze badges
3
I have a slightly different take on it from the accepted answer.
It seems more semantic and logical to return a 403 when authentication fails and a 401 when authorisation fails.
Here is my reasoning for this:
When you are requesting to be authenticated, You are authorised to make that request. You need to otherwise no one would even be able to be authenticated in the first place.
If your authentication fails you are forbidden, that makes semantic sense.
On the other hand the forbidden can also apply for Authorisation, but
Say you are authenticated and you are not authorised to access a particular endpoint. It seems more semantic to return a 401 Unauthorised.
Spring Boot’s security returns 403 for a failed authentication attempt
answered Apr 6, 2022 at 22:44
theMyththeMyth
2544 silver badges14 bronze badges
In the case of 401 vs 403, this has been answered many times. This is essentially a ‘HTTP request environment’ debate, not an ‘application’ debate.
There seems to be a question on the roll-your-own-login issue (application).
In this case, simply not being logged in is not sufficient to send a 401 or a 403, unless you use HTTP Auth vs a login page (not tied to setting HTTP Auth). It sounds like you may be looking for a «201 Created», with a roll-your-own-login screen present (instead of the requested resource) for the application-level access to a file. This says:
«I heard you, it’s here, but try this instead (you are not allowed to see it)»
answered Dec 12, 2014 at 19:01
3
Methods to fix a 401 Unauthorized error
Updated on September 15, 2022
The 401 Unauthorized error is an HTTP status code that means the page you were trying to access cannot be loaded until you first log in with a valid user ID and password.
If you’ve just logged in and received the 401 Unauthorized error, it means that the credentials you entered were invalid for some reason.
401 Unauthorized error messages are often customized by each website, especially very large ones, so keep in mind that this error may present itself in more ways than these common ones:
- 401 Unauthorized
- Authorization Required
- HTTP Error 401 — Unauthorized
The 401 Unauthorized error displays inside the web browser window, just as web pages do. Like most errors like these, you can find them in all browsers that run on any operating system.
How to Fix the 401 Unauthorized Error
-
Check for errors in the URL. It’s possible that the 401 Unauthorized error appeared because the URL was typed incorrectly or the link that was selected points to the wrong URL—one that is for authorized users only.
-
If you’re sure the URL is valid, visit the website’s main page and look for a link that says Login or Secure Access. Enter your credentials here and then try the page again.
If you don’t have credentials or have forgotten yours, follow the instructions provided on the website for setting up an account or resetting your password.
Do you usually struggle to remember your passwords? Consider keeping them in a password manager so that you only have to remember one password.
-
Reload the page. As simple as it might seem, closing down the page and reopening it might be enough to fix the 401 error, but only if it’s caused by a misloaded page.
-
Delete your browser’s cache. There might be invalid login information stored locally in your browser that’s disrupting the login process and throwing the 401 error. Clearing the cache will remove any problems in those files and give the page an opportunity to download fresh files directly from the server.
-
If you’re sure the page you’re trying to reach shouldn’t need authorization, the 401 Unauthorized error message may be a mistake. At that point, it’s probably best to contact the website owner or other website contact and inform them of the problem.
The web site owner of some websites can be reached via email at webmaster@website.com, replacing website.com with the actual website name. Otherwise, find a Contact page for specific contact instructions.
Other Ways You Might See 401 Errors
Web servers running Microsoft IIS might give more information about the 401 Unauthorized error, such as the following:
Microsoft IIS 401 Error Codes | |
---|---|
Error | Explanation |
401.1 | Logon failed. |
401.2 | Logon failed due to server configuration. |
401.3 | Unauthorized due to ACL on resource. |
401.4 | Authorization failed by filter. |
401.5 | Authorization failed by ISAPI/CGI application. |
401.501 | Access Denied: Too many requests from the same client IP; Dynamic IP Restriction Concurrent request rate limit reached. |
401.502 | Forbidden: Too many requests from the same client IP; Dynamic IP Restriction Maximum request rate limit reached. |
401.503 | Access Denied: the IP address is included in the Deny list of IP Restriction |
401.504 | Access Denied: the host name is included in the Deny list of IP Restriction |
You can learn more about IIS-specific codes on Microsoft’s the HTTP status code in IIS 7 and later versions page.
Errors Like 401 Unauthorized
The following messages are also client-side errors and so are related to the 401 Unauthorized error: 400 Bad Request, 403 Forbidden, 404 Not Found, and 408 Request Timeout.
A number of server-side HTTP status codes also exist, like the often-seen 500 Internal Server Error.
FAQ
-
What do I do if I receive a http 401 error in Zoom?
Double-check the URL to make sure it’s accurate, and if so reload the page. If that doesn’t work, log out and log back in again, and if you’re still having problems try turning off any themes or plugins that may be active. Clearing your browser cache might also fix the issue.
-
What’s the difference between 401 Unauthorized and 403 Forbidden?
A 401 Unauthorized code indicates some sort of issue tied to login credentials for a given web page, while 403 Forbidden errors mean the page has been blocked.
Thanks for letting us know!
Get the Latest Tech News Delivered Every Day
Subscribe
We’ve covered the 403 (Forbidden) HTTP Error code in some detail before, but it also has a near identical sibling.
So what exactly is the difference between the 401 (Unauthorized) and 403 (Forbidden) status codes? Surely they mean the same thing? Let’s take a closer look!
RFC Standards
The most up to date RFC Standard defining 401 (Unauthorized) is RFC 7235
The 401 (Unauthorized) status code indicates that the request has not been applied because it lacks valid authentication credentials for the target resource…The user agent MAY repeat the request with a new or replaced Authorization header field.
Whereas 403 (Forbidden) is most recently defined in RFC 7231
The 403 (Forbidden) status code indicates that the server understood the request but refuses to authorize it…If authentication credentials were provided in the request, the server considers them insufficient to grant access.
Common Causes
As mentioned in the previous article, the 403 error can result when a user has logged in but they don’t have sufficient privileges to access the requested resource. For example, a generic user may be attempting to load an ‘admin’ route.
The most obvious time you’d encounter a 401 error, on the other hand, is when you have not logged in at all, or have provided the incorrect password.
These are the two most common causes for this pair of errors.
Less Common Causes
There are some instances where it’s not quite as straightforward as that, though.
403 errors can occur because of restrictions not entirely dependent on the logged in user’s credentials.
For example, a server may have locked down particular resources to only allow access from a predefined range of IP addresses, or may utilize geo-blocking. The latter can be potentially circumvented with a VPN.
401 errors can occur even if the user enters the correct credentials. This is rare, and might be something you only really encounter while developing your own authenticated back ends. But if the authorization header is malformed it will return a 401.
For example, you might have a JWT (JSON Web Token) you want to include in the request header, which expects the format Authorization: Bearer eyJhbGci......yJV_adQssw5c
. If you were to forget the word ‘Bearer’ before the JWT, you would encounter the 401 error.
I have run in to this problem myself when testing APIs under development with Postman and forgetting the correct syntax for auth headers!
That’s it
I hope this clears up any confusion surrounding these very similar errors.
If you found this helpful, or wish to challenge or extend anything raised here, feel free to contact me on Twitter @JacksonBates.
Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started
Содержание
- How to Fix a 401 Unauthorized Error?
- Что делать с ошибкой 401 Unauthorized Error – методы исправления
- Как исправить ошибку 401
- Другие варианты ошибки 401
- Ошибки подобные 401
- How to fix the Web Error Code Error 401 Authorization Required
- Ошибка сервера 401: что это за ошибка и как ее исправить
- Причины появления ошибки сервера 401 и способы ее устранения на стороне пользователя
- Устранение ошибки 401 администратором веб-ресурса
- Дополнительная информация об ошибке с кодом 401
The 401 Unauthorized Error is an HTTP status code error that represented the request sent by the client to the server that lacks valid authentication credentials. It may be represented as 401 Unauthorized, Authorization required, HTTP error 401- Unauthorized. It represents that the request could not be authenticated. It consists of a www-Authenticate header which contains the hint on how to authorize correctly.
401 Unauthorized Error Occur: This error may occur due to the reasons described below:
- It may occur client does not provide the proper authentication credentials to the server within the request time.
- It may occur when the server rejects the request of the client for some reason even though the client provides proper authentication credentials.
- When the client is banned for some reason by the server.
Methods to rectify the error: The 401 Unauthorized error can be fixed by using any of the following ways:
- Check The URL: Due to manual errors in typing the URL, the 401 unauthorized error may occur. Hence, checking the URL and rectifying the mistakes in it will fix the 401 error status.
- Flush the DNS: Errors in DNS also creates 401 error status sometimes. Therefore, clearing the DNS will also rectify this error. In Windows, the DNS can be flushed by typing ipconfig/flushdns in the command prompt and clicking on ENTER.
- Clear Browser Cookie: In some situations, the cookies may not work smoothly leading to improper server authentication. Thus, by clearing the cookies, the error can be rectified.
- Logging out and Logging in again: This error may also occur during the maintenance time of the websites. Therefore, visiting the website and logging in again by providing the credentials may also rectify this error.
- Website mistake: A few times all the above things are good or accurate but still you will get the 401 Unauthorized Error, which is a mistake of the website. That time you need to contact the webmaster of that website and inform that the server is down. You can email them at webmaster@webmaster.com replace the webmaster.com with the website, or you can see the contact us option on any website through that you can inform them.
Some other ways of 401 Authentication error: This error can occur in the below forms also:
Источник
Что делать с ошибкой 401 Unauthorized Error – методы исправления
Ошибка 401 Unauthorized Error – это код состояния HTTP, который означает, что страница, к которой вы пытались получить доступ, не может быть загружена, пока вы не войдете в систему с действительным идентификатором пользователя и паролем.
Если вы только что вошли в систему и получили 401 ошибку авторизации, это означает, что введенные вами учетные данные по какой-то причине недействительны.
Сообщения об ошибках 401 часто настраиваются на каждом веб-сайте индивидуально, особенно если это крупный портал, поэтому имейте в виду, что эта ошибка может проявляться многими способами, из которых самые распространенные:
- 401 Unauthorized
- Authorization Required
- HTTP Error 401 – Ошибка авторизации
401 ошибка авторизации отображается внутри окна веб-браузера, как обычная веб-страница. Как и большинство подобных ошибок, вы можете найти их во всех браузерах, работающих в любой операционной системе.
Как исправить ошибку 401
Проверьте на наличие ошибок в URL. Возможно, ошибка 401 Unauthorized возникла, потому что URL-адрес был введен неправильно, или выбранная ссылка указывает на неправильный URL-адрес, предназначенный только для авторизованных пользователей.
Если вы уверены, что URL-адрес действителен, посетите главную страницу веб-сайта и найдите ссылку с надписью «Логин» или «Безопасный доступ». Введите здесь свои учетные данные, а затем повторите попытку.
Если у вас нет учетных данных или вы забыли свои, следуйте инструкциям на веб-сайте для настройки учетной записи или изменения пароля.
Если вам трудно вспоминать свои, храните их в диспетчере паролей, чтобы приходилось помнить только один пароль.
Перезагрузите страницу. Как бы просто это не показалось, закрытия страницы и её повторное открытие может помочь исправить ошибку 401, но только если она вызвана ошибочно загруженной страницей.
Удалите кеш вашего браузера. Возможно, в вашем браузере хранится неверная информация для входа в систему, что нарушает процесс входа и выдает ошибку 401. Очистка кеша устранит все проблемы в этих файлах и даст странице возможность загружать свежие файлы прямо с сервера.
Другие варианты ошибки 401
Веб-серверы под управлением Microsoft IIS могут предоставить дополнительную информацию об ошибке 401 Unauthorized, например:
Коды ошибок Microsoft IIS 401 | |
---|---|
Ошибка | Объяснение |
401,1 | Войти не удалось. |
401,2 | Ошибка входа в систему из-за конфигурации сервера. |
401,3 | Несанкционированный доступ из-за ACL на ресурс. |
401,4 | Авторизация не пройдена фильтром. |
401,5 | Авторизация блокирована приложением ISAPI/CGI. |
401,501 | Доступ запрещен: слишком много запросов с одного и того же клиентского IP; Ограничение динамического IP-адреса – достигнут предел одновременных запросов. |
401,502 | Запрещено: слишком много запросов с одного IP-адреса клиента; Ограничение динамического IP-адреса – достигнут максимальный предел скорости запросов. |
401,503 | Отказ в доступе: IP-адрес включен в список запрещенных IP |
401,504 | Отказ в доступе: имя хоста включено в список запрещенных |
Ошибки подобные 401
Следующие сообщения также являются ошибками на стороне клиента и относятся к 401 ошибке: 400 Bad Request, 403 Forbidden, 404 Not Found и 408 Request Timeout.
Также существует ряд кодов состояния HTTP на стороне сервера, например, часто встречающийся 500 Internal Server Error.
Источник
How to fix the Web Error Code Error 401 Authorization Required
This article features error number Code 401, commonly known as Authorization Required described as The request header did not contain the necessary authentication codes, and the client is denied access.
Error Information
Error name: Authorization Required
Error number: Error 401
Applies to: Windows 10, 8, 7, Vista, XP
Description: The request header did not contain the necessary authentication codes, and the client is denied access.
This repair tool can fix common computer errors like BSODs, system freezes and crashes. It can replace missing operating system files and DLLs, remove malware and fix the damage caused by it, as well as optimize your PC for maximum performance.
About Status Codes
When you receive web error codes, you may either be having client or server issues. The problem could be related to browser or settings that are blocking your connection, or it can be any other issues related to the server you are trying to access.
To explain the problem further, here are some useful information about web error codes, their symptoms, causes and repair methods.
Definitions (Beta)
Here we list some definitions for the words contained in your error, in an attempt to help you understand your problem. This is a work in progress, so sometimes we might define the word incorrectly, so feel free to skip this section!
- Access — DO NOT USE this tag for Microsoft Access, use [ms-access] instead
- Authentication — Authentication is the process of determining whether someone or something is, in fact, who or what it is declared to be.
- Authorization — Authorization is the process of determining whether a user, program or device is allowed to access a protected resource in a particular way
- Client — A client is an application or system that accesses a service made available by a server.
- Denied — Anything related to the refusal of a system to accomplish some operation requested by an user
- Header — This tag is deprecated because it lacks discriminating power
- Request — A request is a message sent by a source to another object.
- Required — Required is an HTML attribute of an input element that forces that the input be supplied.
- Access — Microsoft Access, also known as Microsoft Office Access, is a database management system from Microsoft that commonly combines the relational Microsoft JetACE Database Engine with a graphical user interface and software-development tools
Symptoms of Code 401 — Authorization Required
Web error codes are also known as http status codes. There are five different classes of http status codes and they always start with the following digits, depending on what kind of error was encountered by the user. These are also the symptoms of the error that the user is experiencing. To explain further, here are the status codes.
4xx: Client Error
This error is sent back to the user when it is a client-side error. The user receives notifications of a bad request, content not found or unauthorized access to the content or something to that effect.
400 — Bad Request
401 — Unauthorized
402 — Payment Required
403 — Forbidden
404 — Not Found
405 — Method Not Allowed
406 — Not Accepted
407 — Proxy Authentication Required
408 — Request Timeout
409 — Conflict
410 — Gone
411 — Length Required
412 — Precondition Failed
413 — Request Entity Too Large
414 — Request-URI Too Long
415 — Unsupported Media Type
416 — Request Range Not Satisfied
417 — Expectation Failed
(For illustrative purposes only)
Causes of Authorization Required — Error 401
4XX codes are caused by the user or settings from the user’s side. The request was not understood by the server because of wrong address bar entry, incorrect syntax, unstable connection or erroneous OS.
Repair Methods
There are particular troubleshooting steps for particular Web Error codes. However, there are also generalized repair methods users can perform when faced with these kinds of errors.
If a repair method works for you, please click the upvote button to the left of the answer, this will let other users know which repair method is currently working the best.
Источник
Ошибка сервера 401: что это за ошибка и как ее исправить
Появление сообщения об ошибке 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» строку такого типа:
Где в поле /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 ошибке:
Как видим, появление ошибки авторизации 401 Unauthorized не является критичным для рядового посетителя сайта и чаще всего устраняется самыми простыми способами. В более сложной ситуации оказываются администраторы и владельцы интернет-ресурсов, но и они в 100% случаев разберутся с данным багом путем изменения настроек или корректировки html-кода с привлечением разработчика сайта.
Источник