I am looking for a good way to return an error when an unauthenticated/unauthorised user is trying to get a restricted access content from my site. Currently I ask the user to login, check the credentials and save, in the PHP session, the user ID and the session expiration. This information is checked each time a user is trying to access the site (all data is retrieved via PHP scripts).
If the user is not authorized, I currently return an error information, in the JSON format. This information can then be used by the front-end (HTML/JS) to "fail gracefully". But I believe a more proper way is to simply serve an HTTP error code.
However having read about codes 401 and 403 in Wikipedia and at W3C, I am confused by which one I should use. 401 seems to be the right one, but they say explicitly that it assumes the HTTP authentication mechanism. So should I use 403? But for that one they say "Authorization will not help and the request SHOULD NOT be repeated."
Also, is there a standard way to (and should I) provide information on why the access was denied (e.g. for the user agent to distinguish between user not being authorized and the session having expired)?