1

I'm using Slim PHP and want to redirect the user to /login if they are not logged in but try to access a page that requires a user to be logged in. When searching for how to build my middleware, I find variations of this code all over the place

class Auth{    
    public function requireLogin(Request $request, Response $response, $next){
        if( !isLoggedIn() ) return $response->withRedirect('/login', 403);

        return $next($request, $response);
    }    
}

for example in this SO answer and this Slim discourse answer.

The problem is that I can't get the combination of redirecting and HTTP 403 to work. From what I can tell, normal HTTP redirects are restricted to the HTTP codes 3xx. Indeed, the above code works fine when used with for example 302.

Am I missing something, or are all the answers that combine withRedirect and 403 "incorrect" (as in not causing an actual redirect of the users browser)?

Magnus
  • 17,157
  • 19
  • 104
  • 189
  • 1
    403 is specifically **Forbidden** it's not a redirect header at all... I think you'd be better off doing one or the other personally; e.g. you *could* **302** to a *login failed* page. – CD001 Jan 08 '20 at 14:06
  • This is the kind of things you would see in an API, the API would returns 403 (more of a 401 actually ) and then the frontend would catch this error, handling it by redirecting you to the login page. In your case, since it's the PHP redirecting it, you could throw an exception and catch it in an error handler but you wouldn't see the 403 error. You kind of don't need it in your case. – Nicolas Jan 08 '20 at 14:09
  • As a clarification between 403 and 401. The 403 error code means the authentication was a success but the user lacks the permission required to perform an action. The 401 simply means an authentication is required to access this page, or this action. In your case, i think the 401 error would be more appropriate. – Nicolas Jan 08 '20 at 14:16
  • This other question seems relevant https://stackoverflow.com/questions/2839585/what-is-correct-http-status-code-when-redirecting-to-a-login-page – Nima Jan 08 '20 at 15:36

1 Answers1

2

If your application is an HTML website that's accessed using a web browser, then the browser will only redirect if the status code is a 3xx one.

If your application is an API that's accessed using an HTTP client then you have more leeway. For an API, you'd use a 403 or 401 status code to indicate that the request cannot be fulfilled without authorisation. You may also include a Location header to tell the client where to go to get authorisation, but of course it's up to the client if they follow up on that link.

Rob Allen
  • 12,643
  • 1
  • 40
  • 49