WordPress JWT身份验证令牌发行

时间:2019-03-14 05:03:18

标签: wordpress authentication jwt wordpress-rest-api

我正在使用JWT身份验证插件将wordpress rest api用于api访问身份验证,但问题是https://example.com/wp-json/jwt-auth/v1/token生成了不允许的错误。

例如,如果我尝试在邮递员``https://example.com/wp-json/jwt-auth/v1/token''中运行此url,则该API还需要进行身份验证才能通过身份验证顺利运行。

所以为什么这个url API需要身份验证,而没有身份验证就无法访问此api。

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

该解决方案创建了一个插件,并在其中添加了以下代码,效果很好。

if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly.
}

if ( ! function_exists( 'require_auth_for_all_endpoints' ) ) {
    add_filter( 'rest_pre_dispatch', 'require_auth_for_all_endpoints', 10, 3 );
    function require_auth_for_all_endpoints( $result, $server, $request ) {
        if ( ! is_user_logged_in() ) {

            // Only allow these endpoints: JWT Auth.
            $allowed_endpoints = array(
                '/jwt-auth/v1/token/validate',
                '/jwt-auth/v1/token',
                '/oauth/authorize',
                '/oauth/token',
                '/oauth/me',
            );
            $allowed_endpoints = apply_filters( 'reqauth/allowed_endpoints', $allowed_endpoints );

            // Endpoint checker.
            $regex_checker = '#^(' . join( '|', $allowed_endpoints ) . ')#';
            $regex_checker = apply_filters( 'reqauth/regex_checker', $regex_checker );

            $is_allowed = preg_match( $regex_checker, $request->get_route() );
            $is_allowed = apply_filters( 'reqauth/is_allowed', $is_allowed );

            if ( ! $is_allowed ) {
                return new WP_Error( 'rest_not_logged_in', __( 'You are not currently logged in.' ), array( 'status' => 401 ) );
            }
        }
    }
}
相关问题