wordpress中jwt插件使用畅想

jwt插件什么?

wordpress的开发者们可能会有所了解,它可以给我们的rest-api接口提供访问wordpress用户验证性数据或者方法时,提供一个令牌,可以让我们的resp-api就像在wordpress后台一样访问,否则wordpress不允许我们通过resp-api直接使用权限类的方法及数据。

如何使用呢?

因为我们做的wordpress插件想要使用权限类的方法,如login_user等方法等。
jwt它也提供了一套rest-api,可以帮我们生成一个权限认证的token,有了这个token,wp就可以让我们访问权限类数据或者方法。

首先我们要知道,jwt可以通过接口,帮我们生成一个token,经我的排查,发现它并没有保存到服务端,它只负责通过算法生成,那么到这里,不去看源码,我们可以大胆的想像到它会把失效日期,以及一些权限信息放到token里,直接返回给客户端。所以我们之前发现jwt生成的token,多次生成的是可以共存的,所以也从这一方面来映证了,它只是一个分发式的生成,并不会保存到服务端,生成一个新的token,旧的token依旧有效。

如何创建用户

wordpress创建用户的方式是,输入用户名,邮箱发送认证邮件的方式来实现注册,如果我们想要让用户快捷通过app注册,就需要把这一步隐形化。

1.准备工作:快速创建用户

$user_id = wp_create_user( $username, $password, $email = 空串 );
wp_set_current_user($user_id);
wp_set_auth_cookie($user_id);

使用这个方法,可以快速创建用户,而且邮箱是可选项

wp_set_current_user($user_id);

Changes the current user by ID or name.
Set $id to null and specify a name if you do not know a user's ID.
Some WordPress functionality is based on the current user and not based on the signed in user. Therefore, it opens the ability to edit and perform actions on users who aren't signed in

wp_set_auth_cookie($user_id);

Sets the authentication cookies based on user ID.
The $remember parameter increases the time that the cookie will be kept. The default the cookie is kept without remembering is two days. When $remember is set, the cookies will be kept for 14 days or two weeks.

用户登录

@param array $credentials — Optional. User info in order to sign on.
@param string|bool $secure_cookie — Optional. Whether to use secure cookie.
@return WP_User|WP_Error — WP_User on success, WP_Error on failure.

function wp_signon($credentials = array(), $secure_cookie = '') { }

用户注册登录

有了上面的准备工作,就可以和现有的方式结合。

直接用户端,通过验证码,通过微信/微博三方平台,获取用户信息,注册,那么我们就要在手机验证码 | oAuth认证获取用户信息之后,访问我们自己的自动注册登录接口

查询oAutho认证的key或者手机号码,如果存在直接调用登录接口,查询用户并返回。(这里可以在服务器直接调用jwt生成token,也可以把用户名和密码返回,由用户端生成)

如果不存在,调用注册接口,生成用户,并且保存用户提交过来的相关字段,如电话号码,oAuth信息等。

把生成的用户名|邮箱|密码返回给用户,用户调用jwt的认证接口,生成token并保存。(或者可以直接在服务端,通过username&password)调用jwt的生成token的方法,返回给用户端。

完成自动注册/登录。

好了,大概的流程就已经明了啦。接下来我们可能涉及到三方oAuth登录,和手机验证码登录的相关记录。

暂无评论

相关推荐

微信扫一扫,分享到朋友圈

wordpress中jwt插件使用畅想