if(!is_user_logged_in()) returns true when 404

Please try this for your redirect:

add_action( 'template_redirect', function(){

    // no non-authenticated users allowed
    if( ! is_user_logged_in() )
    {
        wp_redirect( home_url( '/wp-login.php' ), 302 );
        exit();
    }
});

to allow only logged in users to view your site.

It’s generally too late to use redirect directly in the header.php file, so it’s better to use an hook that fires before http headers are sent, like the template_redirect hook. It’s also important that template_redirect is not activated on the wp-login.php page.