WordPress 技巧:防止暴露用户名

我们知道作者的文章列表链接是:https://blog.wpjam.com/author/superdenis/,其中的superdenis user_nicename也可以说是 user 的 slug, 最长 50 个字符。

默认情况下,在用户注册的时候,直接过滤掉user_login一些不适合在链接中生成的字符,然后全部转成小写字母生成user_nicename

所以大部分 WordPress 用户的user_nicenameuser_login是一样的,这样通过查看某个作者的文章列表链接,就能猜到他的登录账号user_login,然后就可以暴力破解。

如何防止暴露用户名

1. 修改 user_nicename。

WordPress 后台没有提供修改的user_nicename的地方,「#WPJAM 用户管理#」插件已经实现了该功能。

2. 作者的文章列表链接不出现 user_login

如果用户的user_nicenameuser_login是一样的情况下:

作者文章链接使用author_id 代替user_nicename

add_filter('author_link', function($link, $author_id, $author_nicename){
	$author	= get_userdata($author_id);
	
	if(sanitize_title($author->user_login) == $author_nicename){
		global $wp_rewrite;

		$link	= $wp_rewrite->get_author_permastruct();
		$link	= str_replace('%author%', $author_id, $link);
		$link	= home_url(user_trailingslashit($link));
	}
	
	return $link;
}, 10, 3);

原来的作者链接直接设置为 404 页面,防止用户名暴露。

add_action('pre_get_posts',  function($wp_query) {
	if($wp_query->is_main_query() && $wp_query->is_author()){
		if($author_name = $wp_query->get('author_name')){
			$author_name	= sanitize_title_for_query($author_name);
			$author			= get_user_by('slug', $author_name);

			if($author){
				if(sanitize_title($author->user_login) == $author->user_nicename){
					$wp_query->set_404();
				}
			}else{
				if(is_numeric($author_name)){
					$wp_query->set('author_name', '');
					$wp_query->set('author', $author_name);
				}
			}
		}
	}
});

原文来自:https://blog.wpjam.com/m/hide-wordpress-user-login/