Create JWT authorization on WordPress custom route

For some of your users, you may want to provide some special services/products/articles. Here you need to check “if those users have the right access”. This is a scenario where JWT web token can be a good option. Generate unique tokens for users and check tokens when they are trying to get those special services/products. If his/her token gets a match, then authorize them for the service.

Let’s see how we can create a process of JWT token on WordPress for authorization. I’m assuming we’ve got a token saved on the options table in auth_token key.
At first, we’ll create a custom route that excepts post request. Then we’ll match the token when we get a request from this route. If a match found we’ll do something, else we’ll send an error message.
So let’s create a custom route…

function plugin_name_create_route() {
  add_action( 'rest_api_init', function() {
    register_rest_route( 'plugin_name/api', '/token/', array(
      'methods' => 'POST',
      'callback' =>  'plugin_name_route_api',
      'permission_callback' => function() { return ''; }
    ) );
  } );
 }

We can add a callback function in register_rest_route arguments, when the user sends requests, that callback method fires It takes the request as a parameter and then sends a response. permission_callback is another required arguments. It expects a function. You can add who can access this route in permission_callback or other checks.
Now Let’s write that callback function…

function plugin_name_route_api( \WP_REST_Request $req ) {
  $auth_token = get_option( 'auth_token' );
  $headers = $req->get_headers();
  $token = $headers['authorization'][0];
}

We can get request headers from get_headers method of WP_REST_Request class. Then just check for a match with the token that we’ve saved on the database. If don’t match then send statusCode 401. You can set the response status code with WP_Error class. Otherwise, send a success message as a response.

if ( $auth_token != $token ) {
  return new WP_Error( '401', esc_html__( 'Not Authorized', 'text_domain' ), array( 'status' => 401 ) );
}
return json_encode( ['message' => 'Successfully Authenticated…'] );

4 1 vote
Article Rating