【问题标题】:Wordpress JWT authentication Token IssueWordpress JWT 身份验证令牌问题
【发布时间】:2019-08-04 22:05:15
【问题描述】:

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

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

那么为什么这个 url API 需要认证,而没有认证就不能访问这个 api 是我关心的。

任何帮助将不胜感激。

【问题讨论】:

    标签: wordpress authentication jwt wordpress-rest-api


    【解决方案1】:

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

    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 ) );
                }
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2019-12-04
      • 2017-10-22
      • 1970-01-01
      • 2021-10-15
      • 2017-01-19
      • 1970-01-01
      • 2019-09-10
      • 2021-02-11
      • 2020-07-07
      相关资源
      最近更新 更多