Clarification on auth_redirect()

Trying to secure some pages redirecting non-loegged-in users to the log-in page, i found auth_redirect() function here

Docs says “Checks user is logged in, if not it redirects them to login page”.

Now, if so, why do i need to prepend if(!is_user_logged_in()) to make the function work? It shouldn’t be needed, but if i omit it, i will be keep on being redirected forever.

What’s the correct way to use this function?

Solutions Collecting From Web of "Clarification on auth_redirect()"

The answer requires a little bit of WP forensics because this function has been in WordPress since 1.5 but has undergone some changes along the way. One thing that has not changed however is the description “Checks if a user is logged in, if not it redirects them to the login page.”

I think that technically it’s supposed to. And in its original iteration, it did.

However, some bad conditional logic was introduced that makes this not work correctly. In the current version of WP (4.1.1), the problem (or one of them) is this line:

if ( $user_id = wp_validate_auth_cookie( '',  $scheme) ) {

This comparison logic does not work because of the single “=”. What it is supposed to do is to compare the $user_id to the returned value of wp_validate_auth_cookie(), which, if the user is logged in will return a user ID.

But it’s not as simple as just fixing the logic. If you look at the function, $user_id is undefined. I suspect that it should be a global variable, but I’m not certain.

I looked back through the history of this function to see when this issue was introduced and discovered it was in 2.7. So this has been a problem with the function for a number of years. Prior to this change, the logic simply tested for a valid (not false) value returned from wp_validate_auth_cookie() rather than comparing that value to what should be the user ID of the logged in user.

I think that fixing the comparison logic and adding the global $user_id may be the solution to correcting the function’s issues. I’ll be testing that out and submitting this as a proposed fix.