How to get current logged in user using Wordpress Rest Api?

后端 未结 5 1946
盖世英雄少女心
盖世英雄少女心 2020-12-25 11:32

I tried to add a custom request.

add_action(\'rest_api_init\', function () {
    register_rest_route( \'custom\', \'/login\', array(
        \'methods\' =>         


        
5条回答
  •  情书的邮戳
    2020-12-25 11:59

    If you prefer use JWT Authentication for WP REST API, it may be easier to implement with Json Web Tokens.

    First you authenticate the client sending a HTTP POST request to the endpoint /wp-json/jwt-auth/v1/token sending username and password fields to generate a auth token.

    A succefull response would be similar to:

    {
        "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC9qd3QuZGV2IiwiaWF0IjoxNDM4NTcxMDUwLCJuYmYiOjE0Mzg1NzEwNTAsImV4cCI6MTQzOTE3NTg1MCwiZGF0YSI6eyJ1c2VyIjp7ImlkIjoiMSJ9fX0.YNe6AyWW4B7ZwfFE5wJ0O6qQ8QFcYizimDmBy6hCH_8",
        "user_display_name": "admin",
        "user_email": "admin@localhost.dev",
        "user_nicename": "admin"
    }
    

    Then you pass the token each request settings the request header Authorization like:

    Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC9qd3QuZGV2IiwiaWF0IjoxNDM4NTcxMDUwLCJuYmYiOjE0Mzg1NzEwNTAsImV4cCI6MTQzOTE3NTg1MCwiZGF0YSI6eyJ1c2VyIjp7ImlkIjoiMSJ9fX0.YNe6AyWW4B7ZwfFE5wJ0O6qQ8QFcYizimDmBy6hCH_8
    

提交回复
热议问题