在检查用户是否为管理员时使用WordPress身份验证 [英] Using WordPress authentication while checking if user is an administrator

查看:62
本文介绍了在检查用户是否为管理员时使用WordPress身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试对使用PHP创建的管理站点使用wordpress身份验证.我只希望具有管理员角色的用户能够登录到此站点.这就是我所拥有的:

I am trying to use wordpress authentication for an admin site I am creating using PHP. I only want users with the role Administrator to be able to login to this site. This is what I have:

if ( in_array( 'administrator', (array) $user->roles ) ) {
    echo "<script type='text/javascript'>alert('User is an admin!')</script>";
    if( !wp_authenticate($user, $pass) ){
        echo "<script type='text/javascript'>alert('Wrong password!')</script>";
    }elseif(!wp_authenticate($user, $pass) ){
        echo "<script type='text/javascript'>alert('Correct password!')</script>";
    }
}else{
    echo "<script type='text/javascript'>alert('You're not an admin!')</script>";
}

这就是我查询数据库以获取用户ID的方式:

And this is how I query the db to get the user ID:

$link = mysqli_connect($host, $username,$password ,$db );
$q1 = " SELECT ID FROM wp_users WHERE 
    user_email=?";
$stmt = mysqli_prepare($link, $q1);
if($stmt){

        mysqli_stmt_bind_param($stmt, "s", $email);
        mysqli_stmt_execute($stmt);
        mysqli_stmt_bind_result($stmt, $id);
        mysqli_stmt_fetch($stmt);
        //echo $id;
        $user = get_userdata( $id );   

}

我收到警报用户是管理员",然后显示空白页.我在做什么错了?

I get the alert "User is an admin" and then it shows a blank page. What am I doing wrong?

推荐答案

首先:该问题与第二个:您第一个程序段中的逻辑非常奇怪...这应该是类似的

Second: the logic in your first block is very strange... this is what is should resemble

您应始终使用内置的WordPress登录表单和身份验证工作流.并不难使用,滚动自己的登录页面会使您的应用程序非常不安全,除非您完全正确

You should always use the built in WordPress login form and authentication workflow. It is not that hard to use and rolling your own login page makes your application very insecure unless you do it exactly right

要使用默认的WordPress登录流程,请在Dashboard的通用PHP文件中放入类似的内容

To use the default WordPress login flow, put something like this in your Dashboard's common PHP file

<?php 
require_once 'path/to/wp-load.php';
// Before every page load
if ( ! is_user_logged_in() ) {
    // Not logged in at all... redirect to WP Login Page
    auth_redirect();
    exit(); // Exit to be safe
} elseif ( ! in_array( 'administrator', wp_get_current_user()->roles ) ) {
    wp_logout(); // Destroy their login session
    wp_die('You must be an administrator'); // Die with a nice error page
}

让我解释一下此工作流程:

Let me explain this workflow:

首先,我们导入wp-load.php.这在某种程度上也被忽略了,并且可能会有更轻松的方法,但是目前它应该可以很好地工作

First we import wp-load.php. This is somewhat frowned upon as well and there might be a lighter way of doing this, but for now it should work well

现在,假设用户加载了 https://example.com/my-admin/index .php ,您的common.php将首先检查用户是否登录.如果不是,它将调用auth_redirect()并退出,该操作会将用户重定向到

Now, say a user loads https://example.com/my-admin/index.php, your common.php will first check if the user is logged in. If not then it will call auth_redirect() and exit which will redirect the user to https://example.com/wp-login.php?return_url=https%3A%2F%2Fexample.com%2Fmy-admin%2Findex.php

用户将使用wp-login页面登录,然后将他们重定向回 https ://example.com/my-admin/index.php ,您的common.php现在将is_logged_in()识别为true ...,因此我们进入下一个elseif,它将检查用户是否管理员.如果不是,那么它将终止他们的身份验证会话,并失败并显示wp_die,我们将终止auth会话,因此,如果他们重新加载页面,它们将被带回登录页面以输入管理员凭据,并且不会重复显示wp_die页面,您可以根据需要进行调整,因为这可能不是您想要的行为(也许重定向到/wp-admin/...或在wp_die中为常规的/wp-admin/提供链接)

The user will login using the wp-login page and then they will be redirected back to https://example.com/my-admin/index.php, where your common.php will now recognize is_logged_in() as true... so we step to the next elseif where it will check if the user is an administrator. If not then it will kill their authentication session and fail with a wp_die We kill the auth session so that if they reload the page they will be brought back to the login page to enter credentials for an admin and not repeatedly shown the wp_die page, you can tweak this however you wish as this might not be the desired behavior (perhaps redirect to /wp-admin/... or provide a link in the wp_die for the regular /wp-admin/)

如果他们确实具有管理员角色,那么将继续执行请求,并且可以访问仪表板.

if they do have the Administrator role, then execution of the request will continue and the dashboard will be accessible.

请注意,要使其正常工作,您将需要使仪表板与WordPress安装在同一域中运行...否则cookie不会转移.

Please note that for this to work you will need to have your dashboard running on the same domain as your WordPress install... or else the cookies won't transfer over.

很难做...此示例不包括随机数,蜜罐或标准登录表单(默认内核或其他插件)提供的任何其他安全功能

It is hard to do... this example doesn't include Nonces, honeypots, or any other security features that you will get with the standard login form (either with default core or from additional plugins)

<?php 
// Your login.php page

// Really, no really, this should just be done with WordPress's default login page with an auth_redirect()
// Really this is not recommended, it's really bad practice, and much less secure
// You've been warned

// If they provided a username and password, then check them
if ( isset( $_POST['username'] ) && isset( $_POST['password'] ) ) {
  $username = $_POST['username']
  $username = $_POST['password']
  // Check the username and password with WordPress to see if they are for any user
  $user = wp_authenticate( $username, $password );
  $error = '';
  if ( is_a( $user, 'WP_User' ) ) {
      // Verify that the user is an admin
      if ( in_array( 'administrator', (array) $user->roles ) ) {
          // Redirect them to the dashboard
          wp_redirect('dashboard.php');
          exit();
      } else {
          $error = "Correct password, but not an Admin : (";
      }
  } else {
      $error = "Wrong password :(";
  }
}
// The Login Page
?>
<html>
<head>
  <title> My Login </title>
</head>
<body>
  <form action="login.php" method="POST">
    <?php if ( $error ): ?>
       <div class="error"><?php echo $error; ?></div>
    <?php endif; ?>
    <label>
    Username:
      <input type="text" name="username" placeholder="username" required />
    </label>
    <label>
    Password:
      <input type="password" name="password" placeholder="password" required />
    </label>
  </form>
</body>
</html>

在加载除登录页面之外的任何其他页面之前,您应该具有此代码

Before you load any other page besides your login page you should have this code

<?php
if ( ! is_user_logged_in() || ! in_array( 'administrator', wp_get_current_user()->roles ) ) {
    wp_redirect('login.php?error=Please%20Login');
    exit();
}
// now you can do your stuff

这篇关于在检查用户是否为管理员时使用WordPress身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆