0

I have a meta box on a custom post type which has an link in it. This link goes to an endpoint in the wp-json rest API. On the endpoint in the rest API I use current_user_can to verify if the user is logged in.

This is the endpoint, just changed the names:

register_rest_route( 'myapi', '/download_file/', array(
    'methods' => 'GET',
    'callback'    => 'file',
    'permission_callback' => function () {
        return current_user_can('administrator');
    }
) );

The endpoint downloads a file. The point is that you have to be logged in to download the file. However, when I click the link, I get a 403.

This is the link markup:

<a href="http://example.com/wp-json/myapi/download_file" target="_blank">
  Download file
</a>

Do I need to add something else to this link? Or do a post request with some proof I'm logged in?

EDIT: Maybe this is the problem:

On login, wordpress uses the wordpress_[hash] cookie to store your authentication details. Its use is limited to the admin console area, /wp-admin/ From here.

2
  • Is that your actual callback function? file? Commented Aug 17, 2017 at 13:47
  • No. it was just an example. I can change it.
    – ptf
    Commented Aug 17, 2017 at 14:00

1 Answer 1

1

I needed to include the nonce in the URL. Solved it by adding ?_wpnonce=<?= wp_create_nonce( 'wp_rest' ); ?> to my URL. There is some info here, but I thought the nonuce wasn't needed unless I tried to alter data, or something like that. That the WordPress authentication cookie would be enough.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.