WP API v2 + JWT & Angular 1.5

54

插件:

http://v2.wp-api.org/

JWT Authentication for WP REST API

配置

PHP:Minimum PHP version: 5.3.0

PHP HTTP Authorization Header enable

Most of the shared hosting has disabled the HTTP Authorization Header by default.

To enable this option you’ll need to edit your .htaccess file adding the follow

 RewriteEngine on
 RewriteCond %{HTTP:Authorization} ^(.*)
 RewriteRule ^(.*) - [E=HTTP_AUTHORIZATION:%1]

Nginx

location ~ [^/]\.php(/|$) {
        fastcgi_split_path_info ^(.+?\.php)(/.*)$;
        if (!-f $document_root$fastcgi_script_name) {
                return 404;
        }
        include fastcgi_params;
        fastcgi_param HTTP_AUTHORIZATION $http_authorization;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_pass php;
}

吧 user_id 加入到 jwt response

add_filter('jwt_auth_token_before_dispatch', function($data, $user){
        $data['user_id'] = $user->ID;
        return $data;
}, 10, 2);

Config

获取到user_token之后,把 token 放到每个请求的 header 里。

  angular.module('starter', ['starter.controllers']).config(function( $httpProvider) {

    $httpProvider.interceptors.push(['$q', function($q) {
      return {
        request: function(config) {
          config.headers = config.headers || {};
          //Assume that you store the token in a cookie.
          var ionWordpress_user_token = window.localStorage.ionWordpress_user_token;
          //If the cookie has the CurrentUser and the token
          //add the Authorization header in each request
          if (ionWordpress_user_token != undefined) {
            config.headers.Authorization = 'Bearer ' + window.localStorage.ionWordpress_user_token;
          }
          return config;
        }
      };
    }]);
  });

controllers

获取token

angular.module('starter.controllers', [])

  .controller('DashCtrl', function($scope, $http, $httpParamSerializer) {

    var apiHost = 'http://yourdomian/wp-json';

    var transform = function(data) {
      console.log(data);
      return $httpParamSerializer(data);
    }

    $scope.getUser = function() {
      return (window.localStorage.ionWordpress_user) ? JSON.parse(window.localStorage.ionWordpress_user) : null;
    };

    if ($scope.getUser() == null) {

      $http.post(apiHost + '/jwt-auth/v1/token',
        {
          username: 'test_user',
          password: 'test_password'
        },
        {
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
          },
          transformRequest: transform
        })

        .then(function(response) {
          console.log(response.data);
          window.localStorage.ionWordpress_user = JSON.stringify(response.data);
          window.localStorage.ionWordpress_user_token = response.data.token;
          window.localStorage.ionWordpress_user_date = new Date().getTime();
        //return response.data;
        })

        .catch(function(error) {
          console.error('Error', error);
        });

    } else {

      $scope.user = $scope.getUser();

      $scope.getComments = function(postId, page) {

        return $http.get(apiHost + '/wp/v2/comments/?post=' + postId + '&page=' + page).then(function(response) {
          console.log('Get comments', response);
        });
      }

      //$scope.getComments(4913, 1);

      $scope.addComment = function(comment) {
        return $http.post(apiHost + '/wp/v2/comments', comment,
          {
            headers: {
              'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
            },
            transformRequest: transform
          }
        ).then(function(response) {
          console.log('add comment', response);
        });
      }

      $scope.addComment({
        author: 1196,
        // author_email: '',
        // author_name: '',
        post: 4660,
        content: "ying ying yao Lorem ipsum dolor " + new Date()
      });

    }

  })

说点什么

1243 评论 在 "WP API v2 + JWT & Angular 1.5"

提醒
排序:   最新 | 最旧 | 得票最多

挺好的,祝你快乐

偶然来访,受益良多!

增达网,看看笑话就有钱!每天收入无上限!

收入途径:

①:坐等收钱,逆向网赚,上线替下线发展,不推广照样赚钱

②:浏览赚钱,每阅读一篇笑话就有钱,十万文章不限量观看

③:推广赚钱,主动推广的收入是不推广的十倍,赚钱更可观

④:广告提成,你的下线发布一次广告,你可得广告费的两成

注册网址:

http://www.zengda.xin/?ic=lbc

无上线无法注册,请勿删除后缀!

掐指一算,这个博客能风光一百年!

安装企业网络电话,6-8分钱,适合电话营销,QQ138130 友情链接

Ég segi það sama með flensurnar. Reyndar aðallega lelskkóiabarnið sem er búin að vera með hor í allan vetur, en hún er nýbúin með síðasta pensillínkúr og var aftur orðin horug og slöpp í dag. Þetta fer alveg að verða orðið miklu meira en gott.

Its the worst right!? Actually I bought my guy a northface fleece already! it was on sale so that should at least get me through the fall. I get so excited to get things like that on sale, since I know I would never pay full price for it!

Penso proprio che il Papa dovrebbe ascoltare Cossiga,così chi lo criticasse,lo farebbe sapendo di rischiare la sua posizione.Mi pare sia semplicemente una questione di giustizia e responsabilità,in quanto lo scandalo che danno alcune uscite,sopratutto per i semplici,non rimarrebbe impunito,soprattutto quando c’è di mezzo la disobbedienza.Grande anche Ferrara, che ormai non andrebbe più considerato un ateo devoto,ma un devoto e basta.Penso che un giorno o l’altro convocherà tutti per dare l’annuncio della sua conversione.

Booking a self-catering vacation home isn't different. If you will be booking a self-catered holiday home the possibilities are that at some point during your holiday you are going to need to do some cooking to feed you family unless you intend dining out constantly.

より:I have learn several just right stuff here. Definitely worth bookmarking for revisiting. I wonder how much effort you set to make one of these fantastic informative web site.

Well done to think of something like that

Hai!Én viszek Stargate kártyát, de tudok még vinni érdeklődés esetén 2 pakli Star Treket (Borg és Federation). Sötét nagyúr nekem is van, de Amund azt már hoz. Van még WoW kártyám és Mech Warrior figurás cuccom is valamennyi, ha valaki ezirányba érdeklődik. Illetve a megboldogult Káosz Galaktika kártyából is van egy jó adagom.

What is with all this tiny stuff? Don’t they know as we age we need things bigger?? LOL… these are pretty and very neat. I’d heard of “inchies”, but not MOO cards. What does it stand for?

10-28-12calin spune: buna am si eu o problema cu munitoruil am win7 proffesional si mi se stinge munitorul la unele jocuri wow mt2???care e problema???si cand se stinge scrie ac olo power saving mode dar unitatea merge si munitorul nu mai merge:((!!!sper sa ma ajutati -3V-a ajutat acest raspuns?

You write so honestly about this. Thanks for sharing!

x0k7Ky to ask. Does operating a well-established blog like yours take

Way cool! Some extremely valid points! I appreciate you writing this write-up plus the rest of the site is extremely good.

I wanted to thank you for this great read!! I definitely enjoying every little bit of it I have you bookmarked to check out new stuff you post

we like to honor numerous other web web-sites on the web, even if they aren

Looking forward to reading more. Great blog article.Really thank you! Fantastic.

Thankyou for this post, I am a big big fan of this internet site would like to go on updated.

I was very happy to search out this net-site.I wished to thanks to your time for this excellent read!! I definitely having fun with each little little bit of it and I have you bookmarked to check out new stuff you weblog post.

Nice blog here! Also your web site loads up very fast! What web host are you using? Can I get your affiliate link to your host? I wish my site loaded up as fast as yours lol

There may be noticeably a bundle to learn about this. I assume you made certain nice factors in options also.

There is clearly a lot to know about this. I suppose you made various good points in features also.

I’m just writing to let you be aware of of the fine encounter my friend’s daughter found reading your webblog. She noticed so many pieces, including what it is like to possess a great coaching mood to have the others easily know precisely specified tortuous issues. You really surpassed visitors’ expected results. I appreciate you for delivering the effective, trustworthy, explanatory as well as easy guidance on that topic to Ethel.

It?s an important Hello! Wonderful post! Please when I could see a follow up!

I simply could not go away your website before suggesting that I extremely loved the usual info an individual provide for your guests? Is going to be back steadily to check out new posts

It as actually a great and helpful piece of info. I am glad that you shared this useful info with us. Please keep us up to date like this. Thanks for sharing.

Im grateful for the article.Really looking forward to read more. Really Cool.

I抎 have to check with you here. Which isn’t one thing I normally do! I get pleasure from reading a put up that can make people think. Also, thanks for permitting me to remark!

I’а†ve learn several just right stuff here. Certainly value bookmarking for revisiting. I wonder how much attempt you place to create this type of great informative site.

Is going to be again continuously to check up on new posts

Major thankies for the post.Really thank you! Will read on

I went over this site and I think you have a lot of fantastic information, bookmarked (:.

Really enjoyed this blog post.Really looking forward to read more. Want more.

Thanks-a-mundo for the blog article.Much thanks again. Really Cool.

Most likely You Also Make These kind of Slip ups With the bag ?

Say, you got a nice blog post.Really thank you! Want more.

Muchos Gracias for your blog post. Really Great.

Im grateful for the post.Much thanks again. Will read on…

A big thank you for your blog post.Much thanks again. Awesome.

wow, awesome post.Really thank you! Much obliged.

Muchos Gracias for your article.Much thanks again.

I抦 impressed, I need to say. Actually rarely do I encounter a weblog that抯 each educative and entertaining, and let me tell you, you could have hit the nail on the head. Your idea is outstanding; the issue is something that not sufficient persons are talking intelligently about. I’m very blissful that I stumbled across this in my search for something relating to this.

that is the end of this article. Here you?ll locate some websites that we assume you will appreciate, just click the hyperlinks over

Im grateful for the blog post.Really looking forward to read more. Really Cool.

I value the blog article. Much obliged.

You have observed very interesting details! ps nice web site.

It as great that you are getting thoughts from this piece of writing as well as from our argument made here.

wpDiscuz