Ошибка 403 unauthorized

From Wikipedia, the free encyclopedia

HTTP 403 is an HTTP status code meaning access to the requested resource is forbidden. The server understood the request, but will not fulfill it.if it was correct

Specifications[edit]

HTTP 403 provides a distinct error case from HTTP 401; while HTTP 401 is returned when the client has not authenticated, and implies that a successful response may be returned following valid authentication, HTTP 403 is returned when the client is not permitted access to the resource despite providing authentication such as insufficient permissions of the authenticated account.[a]

Error 403: «The server understood the request, but is refusing to authorize it.» (RFC 7231)[1]

Error 401: «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). If the request already included Authorization credentials, then the 401 response indicates that authorization has been refused for those credentials.» (RFC 2616)[2]

The Apache web server returns 403 Forbidden in response to requests for URL[3] paths that corresponded to file system directories when directory listings have been disabled in the server and there is no Directory Index directive to specify an existing file to be returned to the browser. Some administrators configure the Mod proxy extension to Apache to block such requests and this will also return 403 Forbidden. Microsoft IIS responds in the same way when directory listings are denied in that server. In WebDAV, the 403 Forbidden response will be returned by the server if the client issued a PROPFIND request but did not also issue the required Depth header or issued a Depth header of infinity.[3]

Reasons for HTTP Status Code 403: Forbidden[edit]

The HTTP status code 403 is used by the server to indicate that access to the requested resource is forbidden. This status code is triggered for various reasons and signifies that while the server understood the request, it refuses to grant access.

A 403 status code can occur for the following reasons:[4]

  • Insufficient permissions: The most common reason for a 403 status code is that the user lacks the necessary permissions to access the requested resource. This can mean that the user is not logged in, has not provided valid credentials, or does not belong to the appropriate user group to access the resource.
  • Authentication required: In some cases, the server requires authentication to access certain resources. If the user does not provide valid credentials or if the authentication fails, a 403 status code is returned.
  • IP restrictions: The server may also restrict access to specific IP addresses or IP ranges. If the user’s IP address is not included in the list of permitted addresses, a 403 status code is returned.
  • Server configuration: The server’s configuration can be set to prohibit access to certain files, directories, or areas of the website. This can be due to a misconfiguration or intentional restrictions imposed by the server administrator.
  • Blocked by firewall or security software: A 403 status code can occur if a firewall or security software blocks access to the resource. This may happen due to security policies, malware detection, or other security measures.

Examples[edit]

Client request:[5]

GET /securedpage.php HTTP/1.1
Host: www.example.org

Server response:[5]

HTTP/1.1 403 Forbidden
Content-Type: text/html

<html>
   <head><title>403 Forbidden</title></head>
   <body>
      <h1>Forbidden</h1>
      <p>You don't have permission to access /securedpage.php on this server.</p>
   </body>
</html>

Substatus error codes for IIS[edit]

en.Wikipedia error message

The following nonstandard codes are returned by Microsoft’s Internet Information Services, and are not officially recognized by IANA.[6]

  • 403.1 – Execute access forbidden
  • 403.2 – Read access forbidden
  • 403.3 – Write access forbidden
  • 403.4 – SSL required
  • 403.5 – SSL 128 required
  • 403.6 – IP address rejected
  • 403.7 – Client certificate required
  • 403.8 – Site access denied
  • 403.9 – Too many users
  • 403.10 – Invalid configuration
  • 403.11 – Password change
  • 403.12 – Mapper denied access
  • 403.13 – Client certificate revoked
  • 403.14 – Directory listing denied
  • 403.15 – Client Access Licenses exceeded
  • 403.16 – Client certificate is untrusted or invalid
  • 403.17 – Client certificate has expired or is not yet valid
  • 403.18 – Cannot execute request from that application pool
  • 403.19 – Cannot execute CGIs for the client in this application pool
  • 403.20 – Passport logon failed
  • 403.21 – Source access denied
  • 403.22 – Infinite depth is denied
  • 403.502 – Too many requests from the same client IP; Dynamic IP Restriction limit reached
  • 403.503 – Rejected due to IP address restriction

See also[edit]

  • List of HTTP status codes
  • URL redirection

Notes[edit]

  1. ^ See #403 substatus error codes for IIS for possible reasons of why a webserver may refuse to fulfill a request.

References[edit]

  1. ^
    Hypertext Transfer Protocol (HTTP/1.1): Semantics and Content. IETF. sec. 6.5.3. doi:10.17487/RFC7231. RFC 7231.
  2. ^ Nielsen, Henrik; Mogul, Jeffrey; Masinter, Larry M.; Fielding, Roy T.; Gettys, Jim; Leach, Paul J.; Berners-Lee, Tim (June 1999). «RFC 2616 — Hypertext Transfer Protocol — HTTP/1.1». Tools.ietf.org. doi:10.17487/RFC2616. Retrieved 2018-04-09.
  3. ^ a b «HTTP Extensions for Web Distributed Authoring and Versioning (WebDAV)». IETF. June 2007. Archived from the original on March 3, 2016. Retrieved January 12, 2016.
  4. ^ HTTP status code 402 How do I solve the problem with the 403 status code?
  5. ^ a b Example of «Client request» and «Server response» for HTTP status code 403
  6. ^ IIS 7.0 and later versions define the following HTTP status codes that indicate a more specific cause of an error 403

External links[edit]

  • Apache Module mod_proxy – Forward
  • Working with SELinux Contexts Labeling files
  • Hypertext Transfer Protocol (HTTP/1.1): Semantics and Content

A clear explanation from Daniel Irvine [original link]:

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

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

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

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

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

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

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

Nick T's user avatar

Nick T

25.8k12 gold badges83 silver badges121 bronze badges

answered Aug 4, 2011 at 6:24

JPReddy's user avatar

24

Edit: RFC2616 is obsolete, see RFC9110.

401 Unauthorized:

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

403 Forbidden:

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

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


emery's user avatar

emery

8,67310 gold badges44 silver badges51 bronze badges

answered Jul 21, 2010 at 7:28

Oded's user avatar

OdedOded

490k99 gold badges884 silver badges1010 bronze badges

12

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

Brief and Terse

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

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

Detailed and In-Depth

From RFC2616

10.4.2 401 Unauthorized

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

and

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

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

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

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

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


Edit: RFC2616 is obsolete, see RFC7231 and RFC7235.

Community's user avatar

answered Feb 5, 2013 at 17:14

ldrut's user avatar

ldrutldrut

3,8171 gold badge17 silver badges4 bronze badges

7

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

Checks are usually done in this order:

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

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

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

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

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

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

answered Feb 23, 2015 at 11:00

Christophe Roussy's user avatar

9

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

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

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

answered Jul 21, 2010 at 7:26

Cumbayah's user avatar

CumbayahCumbayah

4,4251 gold badge25 silver badges32 bronze badges

6

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

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

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

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

3.1. 401 Unauthorized

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

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

10.4.4 403 Forbidden

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

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

6.5.3. 403 Forbidden

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

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

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

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

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

Community's user avatar

answered Feb 27, 2013 at 9:44

Erwan Legrand's user avatar

6

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

Premraj's user avatar

Premraj

72.3k27 gold badges237 silver badges180 bronze badges

answered Aug 6, 2019 at 12:37

Akshay Misal's user avatar

4

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

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

answered Dec 25, 2014 at 9:09

Patrick White's user avatar

6

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

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

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

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

6.5.3. 403 Forbidden

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

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

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

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

Community's user avatar

answered May 22, 2014 at 10:54

Dave Watts's user avatar

Dave WattsDave Watts

8907 silver badges11 bronze badges

1

These are the meanings:

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

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

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

answered Nov 19, 2019 at 10:17

Luca C.'s user avatar

Luca C.Luca C.

11.7k1 gold badge86 silver badges77 bronze badges

3

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

TL;DR

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

Practical Examples

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

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

RFC (2616 Section 10)

401 Unauthorized (10.4.2)

Meaning 1: Need to authenticate

The request requires user authentication. …

Meaning 2: Authentication insufficient

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

403 Forbidden (10.4.4)

Meaning: Unrelated to authentication

… Authorization will not help …

More details:

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

It SHOULD describe the reason for the refusal in the entity

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

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

answered Feb 25, 2015 at 9:03

Levite's user avatar

LeviteLevite

17.3k8 gold badges51 silver badges50 bronze badges

2

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

enter image description here

answered Nov 11, 2021 at 12:19

Pratham's user avatar

PrathamPratham

4973 silver badges7 bronze badges

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

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

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

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

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

«The request requires user authentication

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

answered Oct 1, 2012 at 14:34

Zaid Masud's user avatar

Zaid MasudZaid Masud

13.2k9 gold badges67 silver badges88 bronze badges

4

In English:

401

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

403

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

answered Apr 8, 2020 at 14:23

James's user avatar

JamesJames

4,6535 gold badges37 silver badges48 bronze badges

2

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

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

answered Aug 11, 2022 at 23:10

emery's user avatar

emeryemery

8,67310 gold badges44 silver badges51 bronze badges

0

401: You need HTTP basic auth to see this.

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

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

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

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

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

answered Sep 23, 2017 at 12:33

Val Kornea's user avatar

Val KorneaVal Kornea

4,4893 gold badges40 silver badges41 bronze badges

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

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

  • A resource requires authentication but no credentials were specified.

401: The client should specify credentials.

  • The specified credentials are in an invalid format.

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

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

401: The client should specify valid credentials.

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

401: Again, the client should specify valid credentials.

  • The specified credentials have expired.

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

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

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

  • The particular resource is inaccessible regardless of credentials.

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

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

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

answered Jun 2, 2018 at 23:34

Grant Gryczan's user avatar

401 response code means one of the following:

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

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

answered Feb 17, 2022 at 11:16

Ran Turner's user avatar

Ran TurnerRan Turner

15k5 gold badges47 silver badges53 bronze badges

0

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

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

401 Unauthorized

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

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

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

403 Forbidden

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

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

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

Community's user avatar

answered Jun 5, 2018 at 15:26

cjbarth's user avatar

cjbarthcjbarth

4,2016 gold badges43 silver badges62 bronze badges

3

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

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

Here is my reasoning for this:

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

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

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

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

answered Apr 6, 2022 at 22:44

I think it’s easier like this:

401 if the credentials you are using is not recognized by the system, for example if it’s different realm or something.

if you managed to pass 401

403 if you are not allowed to access the resource, if you get this when you are not authenticated, chances are you won’t be getting it even if you are authenticated, the system doesn’t check if you have credentials or not.

Disclosure: I haven’t read the RFCs.

answered Jul 10 at 20:47

fireh's user avatar

firehfireh

212 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

Shawn's user avatar

3

Assume your Web API is protected and a client attempts to access it without the appropriate credentials. How do you deal with this scenario? Most likely, you know you have to return an HTTP status code. But what is the more appropriate one? Should it be 401 Unauthorized or 403 Forbidden? Or maybe something else?

As usual, it depends 🙂. It depends on the specific scenario and also on the security level you want to provide. Let’s go a little deeper.

If you prefer, you can watch a video on the same topic:

Web APIs and HTTP Status Codes

Before going into the specific topic, let’s take a quick look at the rationale of HTTP status codes in general. Most Web APIs are inspired by the REST paradigm. Although the vast majority of them don’t actually implement REST, they usually follow a few RESTful conventions when it comes to HTTP status codes.

The basic principle behind these conventions is that a status code returned in a response must make the client aware of what is going on and what the server expects the client to do next. You can fulfill this principle by giving answers to the following questions:

  • Is there a problem or not?
  • If there is a problem, on which side is it? On the client or on the server side?
  • If there is a problem, what should the client do?

This is a general principle that applies to all the HTTP status codes. For example, if the client receives a 200 OK status code, it knows there was no problem with its request and expects the requested resource representation in the response’s body. If the client receives a 201 Created status code, it knows there was no problem with its request, but the resource representation is not in the response’s body. Similarly, when the client receives a 500 Internal Server Error status code, it knows that this is a problem on the server side, and the client can’t do anything to mitigate it.

In summary, your Web API’s response should provide the client with enough information to realize how it can move forward opportunely.

Let’s consider the case when a client attempts to call a protected API. If the client provides the appropriate credentials (e.g., a valid access token), its request is accepted and processed. What happens when the client has no appropriate credentials? What status code should your API return when a request is not legitimate? What information should it return, and how to guarantee the best security experience?

Fortunately, in the OAuth security context, you have some guidelines. Of course, you can use them even if you don’t use OAuth to secure your API.

«The basic principle behind REST status code conventions is that a status code must make the client aware of what is going on and what the server expects the client to do next»

Tweet

Tweet This

When to Use 400 Bad Request?

Let’s start with a simple case: a client calls your protected API, omitting a required parameter. In this case, your API should respond with a 400 Bad Request status code. In fact, if that parameter is required, your API can’t even process the client request. The client’s request is malformed.

Your API should return the same status code even when the client provides an unsupported parameter or repeats the same parameter multiple times in its request. In both cases, the client’s request is not as expected and should be refused.

Following the general principle discussed above, the client should be empowered to understand what to do to fix the problem. So, you should add in your response’s body what was wrong with the client’s request. You can provide those details in the format you prefer, such as simple text, XML, JSON, etc. However, using a standard format like the one proposed by the Problem Details for HTTP APIs specifications would be more appropriate to enable uniform problem management across clients.

For example, if your client calls your API with an empty value for the required data parameter, the API could reply with the following response:

HTTP/1.1 400 Bad Request
Content-Type: application/problem+json
Content-Language: en

{
  "type": "https://myapi.com/validation-error",
  "title": "Validation error",
  "detail": "Your request parameters are not valid.",
  "invalid-params": [
    {
      "name": "data",
      "reason": "cannot be blank."
    }
  ]
}

When to Use 401 Unauthorized?

Now, let’s assume that the client calls your protected API with a well-formed request but no valid credentials. For example, in the OAuth context, this may fall in one of the following cases:

  • An access token is missing.
  • An access token is expired, revoked, malformed, or invalid for other reasons.

In both cases, the appropriate status code to reply with is 401 Unauthorized. In the spirit of mutual collaboration between the client and the API, the response must include a hint on how to obtain such authorization. That comes in the form of the WWW-Authenticate header with the specific authentication scheme to use. For example, in the case of OAuth2, the response should look like the following:

HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer realm="example"

You have to use the Bearer scheme and provide the realm parameter to indicate the set of resources the API is protecting.

If the client request does not include any access token, demonstrating that it wasn’t aware that the API is protected, the API’s response should not include any other information.

On the other hand, if the client’s request includes an expired access token, the API response could include the reason for the denied access, as shown in the following example:

HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer realm="example",
                  error="invalid_token",
                  error_description="The access token expired"

When to Use 403 Forbidden?

Let’s explore a different case now. Assume, for example, that your client sends a request to modify a document and provides a valid access token to the API. However, that token doesn’t include or imply any permission or scope that allows the client to perform the desired action.

In this case, your API should respond with a 403 Forbidden status code. With this status code, your API tells the client that the credentials it provided (e.g., the access token) are valid, but it needs appropriate privileges to perform the requested action.

To help the client understand what to do next, your API may include what privileges are needed in its response. For example, according to the OAuth2 guidelines, your API may include information about the missing scope to access the protected resource.

Try out the most powerful authentication platform for free.Get started →

Security Considerations

When you plan how to respond to your client’s requests, always keep security in mind.

How to deal with response details

A primary security concern is to avoid providing useful information to potential attackers. In other words, returning detailed information in the API responses to attempts to access protected resources may be a security risk.

For example, suppose your API returns a 401 Unauthorized status code with an error description like The access token is expired. In this case, it gives information about the token itself to a potential attacker. The same happens when your API responds with a 403 Forbidden status code and reports the missing scope or privilege.

In other words, sharing this information can improve the collaboration between the client and the server, according to the basic principle of the REST paradigm. However, the same information may be used by malicious attackers to elaborate their attack strategy.

Since this additional information is optional for both the HTTP specifications and the OAuth2 bearer token guidelines, maybe you should think carefully about sharing it. The basic principle on sharing that additional information should be based on the answer to this question: how would the client behave any differently if provided with more information?

For example, in the case of a response with a 401 Unauthorized status code, does the client’s behavior change when it knows that its token is expired or revoked? In any case, it must request a new token. So, adding that information doesn’t change the client’s behavior.

Different is the case with 403 Forbidden. By informing your client that it needs a specific permission, your API makes it learn what to do next, i.e., requesting that additional permission. If your API doesn’t provide this additional information, it will behave differently because it doesn’t know what to do to access that resource.

Don’t let the client know…

Now, assume your client attempts to access a resource that it MUST NOT access at all, for example, because it belongs to another user. What status code should your API return? Should it return a 403 or a 401 status code?

You may be tempted to return a 403 status code anyway. But, actually, you can’t suggest any missing permission because that client has no way to access that resource. So, the 403 status code gives no actual helpful information. You may think that returning a 401 status code makes sense in this case. After all, the resource belongs to another user, so the request should come from a different user.

However, since that resource shouldn’t be reached by the current client, the best option is to hide it. Letting the client (and especially the user behind it) know that resource exists could possibly lead to Insecure Direct Object References (IDOR), an access control vulnerability based on the knowledge of resources you shouldn’t access. Therefore, in these cases, your API should respond with a 404 Not Found status code. This is an option provided by the HTTP specification:

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).

For example, this is the strategy adopted by GitHub when you don’t have any permission to access a repository. This approach avoids that an attacker attempts to access the resource again with a slightly different strategy.

How to deal with bad requests

When a client sends a malformed request, you know you should reply with a 400 Bad Request status code. You may be tempted to analyze the request’s correctness before evaluating the client credentials. You shouldn’t do this for a few reasons:

  • By evaluating the client credentials before the request’s validity, you avoid your API processing requests that aren’t allowed to be there.
  • A potential attacker could figure out how a request should look without being authenticated, even before obtaining or stealing a legitimate access token.

Also, consider that in infrastructures with an API gateway, the client credentials will be evaluated beforehand by the gateway itself, which doesn’t know at all what parameters the API is expecting.

The security measures discussed here must be applied in the production environment. Of course, in the development environment, your API can provide all the information you need to be able to diagnose the causes of an authorization failure.

Recap

Throughout this article, you learned that:

  • 400 Bad Request is the status code to return when the form of the client request is not as the API expects.
  • 401 Unauthorized is the status code to return when the client provides no credentials or invalid credentials.
  • 403 Forbidden is the status code to return when a client has valid credentials but not enough privileges to perform an action on a resource.

You also learned that some security concerns might arise when your API exposes details that malicious attackers may exploit. In these cases, you may adopt a more restricted strategy by including just the needed details in the response body or even using the 404 Not Found status code instead of 403 Forbidden or 401 Unauthorized.

The following cheat sheet summarizes what you learned:

4xx HTTP status codes cheat sheet

«Четырёхсотые» коды состояния описывают проблемы на стороне клиента: обычно они возникают, когда браузер отправляет серверу некорректный HTTP-запрос.

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

  • Что означает ошибка 403 (Forbidden)
  • Что могло пойти не так
  • Ошибки на стороне пользователя
  • Ошибки на стороне сайта
  • Ограничения на стороне хостера или провайдера
  • Как исправить ошибку 403
  • Что делать владельцу сайта
  • Что делать пользователю

Ошибка 403 (Forbidden) — это когда сервер понял запрос, но почему-то отказывается выполнять его и отдавать браузеру HTML-код страницы.

Помимо «Forbidden», сервер может описать ошибку и другими словами: «error access denied» (доступ запрещён), «you don’t have permission to access» (нет разрешения на вход) и так далее. Сообщения разные, но смысл один.

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

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

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

Неправильный URL-адрес. Возможно, вы случайно постучались на какую-то секретную страничку, а это ни вам, ни серверу не нужно. Банально, но стоит перепроверить ссылку ещё разок.

Проблема в устройстве. Проверить это можно, зайдя на страницу с другого девайса. Если всё откроется, значит, дело в конкретной технике. Причины у этого могут быть разные:

  • Неправильные данные в кэше. Тогда можно почистить его или перезагрузить страницу сочетанием Ctrl + F5 (при таком принудительном обновлении кэш игнорируется).
  • Устаревшие данные в cookies. Если проблема в этом, то достаточно почистить их, и всё заработает.
  • Вы заходите на страницу со смартфона, на котором включён режим экономии трафика. Из-за него браузер может не передавать сайту какие-то нужные ему данные — это и вызывает HTTP-ошибку Forbidden. В этом случае достаточно отключить экономию трафика.

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

Кадр: сериал «Парки и зоны отдыха» / NBC

«Forbidden» может возникнуть, если что-то не так с компонентами сайта. Вот несколько возможных проблем, которые может и должен решить администратор сайта.

Некорректный индексный файл. Это файл, который указывает на главную страницу домена или поддомена. Нужно, чтобы у него были правильное название и формат — а они, в свою очередь, определяются CMS, которой вы пользуетесь. Например, для сайтов на WordPress это может быть index.html, index.htm или index.php.

А ещё индексный файл должен находиться в корневой папке домена или поддомена — смотря к чему он относится.

Неправильно расположены файлы сайта. Как и index, другие файлы сайта тоже должны лежать в корневой директории. Где именно — зависит от CMS и хостинга, которые вы используете.

Неверно настроены права доступа. У каждого файла и папки есть права доступа, которые состоят из трёх цифр от 0 до 7: первая — права владельца, вторая — групповые права, третья — публичные права. Сама цифра означает, какие права предоставлены этой группе.

Если у пользователя нет прав на выполнение действия, то он получит HTTP-ошибку 403 Forbidden. Обычно на папки выставляют доступ 755, на файлы — 644.

Проблемы с плагином. Если вы устанавливали плагины для своей CMS, то вызвать код 403 может какой-то из них. Возможно, он не обновился до последней версии, повреждён или несовместим с конфигурациями сайта.

Вот как это проверить, если у вас WordPress:

  • Перейдите в раздел wp-content и найдите папку plugins.
  • Переименуйте её — это отключит работу всех плагинов.
  • Если проблема уйдёт, значит, дело было в плагинах.

Далее можно включать плагины обратно и искать конкретного виновника. Чтобы это сделать, отключайте их по очереди и обновляйте страницу — где-то по пути точно обнаружите, где с каким плагином проблема.

Некорректные указания в файле .htaccess. Если вы используете Apache Web Server, попробуйте переименовать файл .htaccess. Так же как и с плагинами, это отключит его и позволит понять, виновен ли он в ошибке.

Если дело всё-таки в .htaccess, проверьте и исправьте его директивы. Вот на какие условия стоит обратить внимание:

  • deny (запрещает доступ);
  • allow (разрешает доступ);
  • require (запрещает или разрешает доступ всем, кроме указанных пользователей);
  • redirect (перенаправляет запрос на другой URL);
  • RewriteRule (преобразует строку с помощью регулярных выражений).

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

Чтобы проверить, в этом ли дело, отключите брандмауэр и повторите запрещённое действие. Если сработает — проблема найдена. Проверьте журнал брандмауэра: там должна быть указана конкретная причина блокировки запроса.

Узнав причину, добавьте её в исключения, и такие запросы будут выполняться корректно.

Тариф хостинга не поддерживает инструменты. Например, вы пишете на PHP 8, а тариф рассчитан только на PHP 7.4. В таком случае придётся либо перейти на другую версию инструмента, либо сменить тариф (а может, и целого хостера).

Бывает так: с логикой на сервере всё в порядке, HTTP-запрос составлен корректно, а ошибка 403 всё равно возникает. Но подождите кричать «Тысяча чертей!» — возможно, шайба на стороне посредника.

Хостер прекратил обслуживание сайта. Просрочка платежа, нарушение условий хостинга, блокировки Роскомнадзора и другие малоприятные истории. Самое время проверить почту — обычно доступ к сайту не отключают без предупреждения.

Не успел обновиться кэш DNS-серверов. Если ваш сайт переезжал на другой адрес, в кэше DNS-серверов могли остаться устаревшие данные. Остаётся только ждать. Обычно кэш обновляется в течение суток, но в редких случаях процесс может занять два-три дня.

Проблемы на стороне провайдера. Возможно, у него неправильно настроена конфигурация оборудования или он заблокировал вас намеренно. Выход один и для пользователя, и для владельца сайта — обратиться к провайдеру.

Да-а, такая маленькая ошибка, а проблем — как с запуском Falcon Heavy на Марс. Держите чек-лист, который поможет не запутаться и быстро всё пофиксить.

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

Проверьте настройки сайта. Пробегитесь по списку ошибок, о которых мы писали выше. Перебирайте один вариант за другим, пока не поймёте, где собака зарыта.

Если ничего не помогает — обратитесь за помощью к своему хостинг-провайдеру.

  • Перепроверьте URL страницы: правильный ли он? Вы могли кликнуть по ошибочной ссылке или сайт переехал на другой адрес, а поисковики этого ещё не поняли.
  • Проверьте, авторизованы ли вы на сайте. Залогиньтесь, если есть такая возможность.
  • Зайдите на страницу с другого устройства. Если сайт заработал — проблема в устройстве. Попробуйте перезагрузить страницу, почистить кэш и cookies браузера или отключить экономию трафика.
  • Включите или выключите VPN. Возможно, доступ к сайту блокируется по IP-адресу для пользователей из определённой страны или региона. Попробуйте использовать IP-адреса разных стран.
  • Подключитесь к другой сети. Например, если пользуетесь 4G, перейдите на Wi-Fi. Это поможет понять, есть ли проблемы на стороне поставщика интернета.

Если ничего не помогает, значит, проблема на стороне сайта. Обратитесь в техподдержку и сообщите об ошибке — возможно, о ней ещё никто не знает.

The 403 error is used to identify web pages or resources that cannot be accessed. However, it may happen that the 403 Forbidden error pops up when it shouldn’t and this can be frustrating regardless of whether the error is occurring on your site, or if it happens on the page you are trying to visit.

In this article, the 403 error: how to solve it, we are going to look at the reason for the 403 error and the various ways it can occur. We will then see how to get around the error if you are a user trying to browse a page or if the problem is occurring on your site.

Table of Contents

The 403 error: how to solve it — what does it mean?

Error 403 is part of the HTTP 4XX status codes, also referred to as client-side errors. This category also includes one of the most common errors you may come across while browsing: the 404 error. The 404 error or 404 not found is used to indicate that the requested page or resource could not be found. As opposed to client errors there are server errors such as the error 500, 502 bad gateway and 504 gateway time-out.

The 403 Forbidden error occurs when you do not have permission to access the page or resource you are trying to open. There are two main instances where the 403 error can occur.

403 Error Access Forbidden

In the first case, you are trying to access a resource for which you don’t really have permission, for example, a section of the site accessible only to registered users.

In the second case, instead, you are trying to reach a page that should be accessible, but the website owner has not correctly configured the permissions, so you get a 403 error.

Besides these two cases, there are other causes that can lead to a 403 error, which we will see in the following paragraphs.

As it happens with other error pages (for example the error 500 or 404), error 403 can be customized. Moreover, it is possible that the 403 error presents itself in different variations, let’s see which are the main ones.

403 Error Forbidden

Variations of error 403

Error 403 can be found in different forms, the most common ones are:

  • Error 403 can be found in different forms, the most common ones are:
  • Error 403
  • Error 403 Forbidden
  • Error 403 Access Denied
  • HTTP ERROR 403
  • HTTP Error 403 Forbidden
  • 403 Forbidden — nginx
  • Forbidden
  • You are not authorized to view this page
  • Forbidden: You don’t have permission to access [directory/file] on this server
  • It appears you don’t have permission to access this page
  • HTTP Error 403 — Forbidden — You do not have permission to access the document or program you requested
  • Access Denied — You don’t have permission to access
  • Access to [domain name] was denied. You don’t have the authorization to view this page.
403 Error Forbidden Nginx
Example of error 403 Forbidden — nginx

What causes error code 403

In this section, we will see what are all the possible causes of error 403. In the next paragraphs, instead, we are going to see how to solve error 403 from site visitors and how to remove the error 403 on your site.

Directory listing denied

When you try to access a folder on your site from your browser that does not contain a default document, the web server may return a 403 Forbidden error. In particular, this occurs when there is no default document (such as index.php or index.html) and at the same time Directory listings have been blocked.

Directory listing (or directory index) is deactivated precisely to avoid that trying to reach an address for which there is no default file is displayed. This option is disabled for security reasons, if you have a site with SupportHost the option is already deactivated. Alternatively, to understand how to disable it, you can follow the steps outlined in our WordPress security guide.

File or folder permissions configuration error

Error 403 can also be caused if the site’s file and folder permissions settings are not set correctly. File and folder permissions allow you to specify which users can interact with files and how.

403 Error File And Folders

Permissions pertain to the ability to read, write, and execute files and are indicated by a 3-digit number, each for each action (read, write, and execute). When we talk about how to get rid of the 403 error, we’ll see how to go about changing the permissions of files and folders.

Corrupt .htaccess file

In Apache servers, the 403 Forbidden error can be due to an error in the .htaccess file. The .htaccess file is used for several reasons including protecting access to files and folders and creating redirects (such as 301 redirects).

In the section on how to fix the 403 Forbidden error, we will see how to regenerate the .htaccess file with WordPress.

Unauthorized user

Sites that require an authentication typically display a 401 Unauthorized error warning. However, in some cases, it is possible for the webserver to show a 403 error.

Plugin incompatibility

Another cause of the 403 error can be a problem with a plugin or lack of compatibility between different plugins on your WordPress site.

In this case, you should disable all plugins and check if the error persists. If the 403 error does not appear after deactivating the plugins, you’ll have to reactivate them one by one to figure out which one is causing the problem.

In the next paragraphs, we will see how to identify the problematic plugins.

CDN problems

Some CDNs like CloudFlare allow you to set up a firewall and block traffic based on location, IP address or other parameters. If the request sent to the server is not within the rules set in the firewall you may receive a 403 error in response.

To check if the error is caused by the CDN itself, try disabling it temporarily and see if the 403 error continues to appear.

In the paragraph on troubleshooting we will see how to disable the CDN to see if it is causing the problem.

Hotlink Protection

Hotlink protection is a measure to prevent hotlinking. Hotlinking occurs when someone places an image on your site using the address of an image hosted on another site. In this way, the image will be displayed on the target site, but it will use the resources of the site that is hosting it.

To avoid this situation you can enable hotlink protection. When the hotlink protection is enabled, if it is not set correctly it can lead to the appearance of a 403 Forbidden error. In this case, you should check that the hotlink protection is configured correctly.

Cause of Error 403 on IIS

On Microsoft IIS (Internet Information Services) servers, HTTP error codes are accompanied by additional numeric codes that allow you to get more details about the causes of the error. You can find the complete list in the Microsoft documentation.

For example, in the case of errors on file and/or folder permissions you may encounter one of these three errors depending on the type of problem (read, write or execute):

  • 403.1 — Execute access forbidden
  • 403.2 — Read access forbidden
  • 403.3 — Write access forbidden.

On ISS servers you may also get a 403 error if there are too many simultaneous connections (403.9 — Too many users).

Troubleshooting 403 error: how to fix it as a user

If the error code 403 occurs on the site you are visiting you can try different ways.

Update the page

It may seem like the most trivial thing, but if you haven’t already, the first thing you should do is try to refresh the page. You can click on the reload page button in your browser or press the F5 key on your keyboard.

403 Error Reload Page

Sometimes the 403 error may occur due to a technical problem and be only temporary, so you may hope to resolve it by simply reloading the page.

In addition to simply refreshing the page, you can also have the browser reload the page ignoring the cache. To do this, just press Ctrl+F5 on Windows or Shift+CMD+R on Mac.

Check the address

Another thing to do is to make sure that the address you are trying to visit does not contain any errors. Make sure you typed it correctly or that there are no errors, for example, you may have followed a link with an error in the address.

In this case, try to reach the destination page in another way. For example, you could link to the site’s homepage and use the site’s search function to find the content you were interested in reaching.

Clear cache and cookies

Clearing the cache and cookies of the browser you are using can help you in case the error is occurring on only one device or browser.

403 Error Clear Cache Chrome

If you’ve tried to reach the address from another device or with a different browser and only encounter the 403 error with a particular browser you can follow our guide to figuring out how to clear cache and cookies on major browsers.

Disable VPN

VPNs are used to ensure privacy and mask IP addresses. However, not all sites allow access using a VPN. In this case, if you are getting a 403 error and you are using a VPN you can try disabling it and see if it resolves the error.

Contact the site owner

Another thing you can do is try to contact the site owners directly. In this way you can report the 403 error and check if your IP address has been blocked.

See the cache copy of the site

If none of the previous methods helped you to solve the 403 error, there is still another solution you can try to be able to see the page on which the error occurs.

Search engines like Google or Bing allow you to access the cache copy of web pages. To view the Google cache of a page you just need to do a search on Google and then click on the down arrow you see next to the address. Here’s how to do that using the example you see in this screenshot.

403 Error Check Google Cache

Alternatively, if you can’t see the cached copy of the site this way, you can also use the Wayback Machine.

Just connect to the site and type in the address of the page you want to view. After that, check if there are any copies of the page stored and click on one of the available dates to see the cached version stored on that date.

403 Error Wayback Machine Supporthost

The 403 error: how to solve it and fix it on your site

In this section, we will see what you can do to fix the 403 Forbidden error, on your site based on the causes we listed earlier.

We will then see how to:

  • modify the file and folder permissions
  • restore the htaccess file, generating a new one
  • check if the error 403 is due to a plugin.

Also remember that you should make sure that the problem does not depend on CDN or hotlink protection, as we saw before.

Change file and folder permissions

As we have seen the 403 error can occur if the file and folder permissions are not set correctly.

The following file and folder permissions should be set for WordPress files and folders:

  • 644 or 640 for files
  • 755 or 750 for folders.

This is an exception to the wp-config.php file which should be set to 440 or 400.

You can verify that the permissions are set correctly in two ways: by using the file manager to access files and folders on your site or by using an FTP client such as FileZilla.

Use the cPanel file manager

Log in to cPanel and click on File Manager to access the file manager.

IMAGE

In the Permissions column, you will see the file and folder permissions.

IMAGE

To change them just select a file or folder and click on Permissions as you see in this screenshot.

IMAGE

Then change the permissions and click on Change Permissions to save. In this example, we see how to set permissions for the file wp-config.php.

403 Error Set Permissions WordPress Wp Config

Usare FileZilla

You can check the file and folder permissions using an FTP client like FileZilla. First, you have to connect to the server with FileZilla, the data to be entered are host, username, password and port.

403 Error Filezilla Quick Connection

If you have activated a plan with SupportHost such as a WordPress hosting or a dedicated solution like a dedicated server or VPS cloud hosting, you just need to use the login details you find in the activation email.

You can also create a new FTP account with cPanel.

After logging in browse to the file or folder for which you want to change the permissions, right-click on the file and click on File Permissions as you see here in this example.

403 Error Filezilla File Permissions

Change the read, write and execute settings and click OK.

403 Error Change Filezilla Permissions

In the case of folders, instead of having to change permissions for all subfolders and files within them, you can choose to apply them automatically. To do so, right-click on the top folder and click on File Permissions.

403 Error Filezilla Permission For All Files And Directories

After setting the new permissions check the Include subfolders box and you can choose to:

  • apply permissions to all files and folders
  • apply only to files
  • apply only to folders.

Regenerate htaccess file

The 403 Forbidden error can be caused by a problem in the .htaccess file, the best solution is to have WordPress regenerate the file in order to eliminate the error. Before proceeding, however, you need to create a backup copy of your current .htaccess file. To do this you need to access your site’s files, you can do this by using the control panel’s file manager or accessing the server via FTP, for example with FileZilla.

In this example, we will see how to do it with the cPanel file manager. Login to cPanel and click on File Manager.

Cpanel File Manager 403 Error

The .htaccess file is located at the root of the site, but in case you don’t see it, make sure that the option to show hidden files is enabled.

Click on the settings and check the Show hidden files (dotfiles) box as you see in this screenshot and click on Save.

403 Error Show Hidden Files In Cpanel

Locate the .htaccess file and download a copy onto your computer, simply right click on the file and then click on Download.

403 Error Backup Copy File Htaccess

After that, you can delete the .htaccess file, right-click on the file and then click Delete.

403 Error Delete Htaccess File

Login to your WordPress site dashboard and click on Settings → Permalink.

403 Error Permalink Settings

Scroll to the bottom of the page and click Save Changes, doing so will automatically generate a new .htaccess file for WordPress.

403 Error WordPress Permalink Save Changes

Deactivate and reactivate plugins

A recently installed WordPress plugin or an incompatibility issue between different plugins on your site can cause a 403 error. To figure out if a plugin is the cause of the error you’ll need to temporarily deactivate them, let’s see how to do that with two different methods.

If you can access the WordPress dashboard you can deactivate plugins directly from there, otherwise, you’ll have to proceed in a different way, which we’ll see in a moment.

Disable plugins from the dashboard

To deactivate plugins from the dashboard login to your WordPress site and click on the Plugins tab. From this section first, you need to check the box next to Plugins to select all of them.

403 Error Select All WordPress Plugins

After that from the Bulk Actions menu, click on the Deactivate item and then click on the Apply button.

403 Error Deactivate WordPress Plugins

This will deactivate all plugins.

Deactivate plugins by connecting to the server

If you can’t access the dashboard of your site, you’ll have to directly access the files hosted on the server. As we have seen before to delete the .htaccess file or change file permissions you could do it either from the file manager of your site’s control panel, for example from cPanel, or through an FTP client like FileZilla.

In this example, we will see how to do it with the file manager, but the procedure to follow is quite similar.

The folder we are interested in is the one where the plugins are contained, which in turn is located inside the wp-content folder. The full path will usually be /public_html/wp-content/plugins.

To deactivate all plugins we just need to rename the folder, for example in «deactivated plugins», as you see in this screenshot.

403 Error Reneme WordPress Plugin Folder

Reactivate plugins

After deactivating the plugins, connect to the site again and check if the error 403 still appears. If the error does not appear anymore, then the cause is one of the plugins that were active on your site.

At this point you just need to figure out which plugin is causing the problem and to do that you need to reactivate the plugins one by one, checking each time if the 403 error reappears.

If you have deactivated the plugins from the dashboard, you only need to activate them manually one by one. If you renamed the plugins folder, you’ll have to change the name back to «plugins». Then you can activate the plugins from the dashboard.

To activate plugins, login to WordPress, click on the Plugins tab and then click on Activate under the name of the plugin as you see in this screenshot.

403 Error Activate Plugin

Once you have identified the plugin causing the problem what can you do? First of all, check if the plugin is up to date and if not, update it. In case the error continues to appear after updating the plugin you can try to contact the developer and ask for assistance.

Otherwise, the only thing to do is to replace the plugin with one that has the same function.

Disable CDN

The causes for error 403 may also include a problem with the CDN (content distribution network). To rule this out, we can disable the CDN by changing the nameservers and setting the default ones from the hosting.

If you are our customer, you will need to make sure you are using our nameservers:

  • ns.supporthost.com
  • ns.supporthost.eu
  • ns.supporthost.net
  • ns.supporthost.us

All you have to do is go to the nameserver management section from the customer area and select the option Use default nameservers as shown here:

Use Supporthost Default Nameservers

If you have any doubts, follow the detailed procedure described in our tutorial on nameservers.

Contact support

If you couldn’t solve the 403 error with the methods we’ve seen, you can contact your provider for assistance. If you are a SupportHost customer, you can open a ticket and one of our operators will guide you.

403 Error Open Support Ticket

Conclusion

As we have seen in this article, the 403 error: how to solve it, the 403 forbidden error is displayed when you do not have the necessary permissions to access the requested page. In most cases, the error is caused by incorrect configuration of file or folder permissions or a problem with the .htaccess file.

We have seen how to bypass the 403 error code from user and how to get rid of 403 error if it occurs on your site. Did the error show up on your site as well? How did you solve it and if so with which method? Let me know in the comments below.

Понравилась статья? Поделить с друзьями:
  • Ошибка 403 iis
  • Ошибка 403 google android
  • Ошибка 403 html шаблон
  • Ошибка 403 google аккаунт
  • Ошибка 4020 куосера