laravel 搭建oauth2认证服务,可用于app登录等验证

oauth2

oauth2是一种验证方式, 这里不加以解释,不明白的小伙伴可以看一看阮一峰的文章-理解oauth2.0

使用的库

https://github.com/lucadegasperi/oauth2-server-laravel

  • 按github上的教程搭建oauth2认证
    先进行composer安装然后配置,数据迁移。
  • 选择一种验证方式
    oauth2-server-laravel 支持Client Credentials Grant,password等四种验证方式,可按照教程在config/oauth2.php下配置,例如选择password granttype,就可按照https://github.com/lucadegasperi/oauth2-server-laravel/blob/master/docs/authorization-server/choosing-grant.md操作。
  • 登录验证(这里使用密码方式)
    现在oauth_clients表中新建一条数据,然后每次登录验证时就发送参数client_id和client_secret; 在User.php修改验证的用户表
protected $table="ims_mc_members"; 

在routes.php新建以下路由

Route::post('oauth/access_token', function() {
return Response::json(Authorizer::issueAccessToken());
});

表单请求上面的路由,发送表单数据

grant_typ = "password" 
client_id = "your_client_id"
client_secret = "your_client_secret" 
username = "you_email@xxx.com" 
password = "your_password",

注意2点,
1.按照自己写的restapi格式发送表单,post或者get的话指定action就好,其他如delete,patch,put等就需要对应的在表单中加上一个隐藏的input如:

_method = 'delete'

2.默认用邮箱登录
以上就搭建完了,等等,如果我登录不用邮箱怎么办,如果我用了salt加密怎么办, 那往下看吧。

自定义验证规则

有时候可能不是用邮箱登录,或者验证方式与上面的不同,比如我的系统使用md5+salt验证,mobile和email都可登录,这时候就要修改默认验证方式了

  1. 修改app下PasswordGrantVerifier.php的verify.php方法
public function verify($username, $password)
{
//harry 修改验证 anasit
      $credentials = [
        'uniacid' => $_REQUEST['uniacid'],
        'password' => $password,
    ];
    if(strpos($username, '@')){
        $credentials['email'] = $username;
    }else{
        $credentials['mobile'] = $username;
    }

    if (Auth::once($credentials)) {
        return Auth::user()->id;
    }

    return false;
}

因为之前会正则验证邮箱和手机号,所以就偷了个懒,用是否含有@来区分邮箱和手机号了。

  1. 这样就修改成mobile和email都可登录了
    哎,上面的uniacid是什么鬼?
    uniacid是因为在做微信开发,识别不同公众号,比如权限管理,管理员和用户都在一个user表中,一个人可以是管理员也可以是用户,他的账号密码可能相同,只是一个的role(角色)是user,一个是admin,这样你就可以在$credentials,加入一个键值对'role'=>'admin'或'role'=>'user'来做验证。
    但是接下来还要修改验证方式,
    验证方法在/vendor/laravel/frameword/src/Illuminate/Auth/EloquentUserProvider.php里面的validateCredentials方法可以自定义自己的验证逻辑md5,hash或者其他,我的修改为
  public function validateCredentials(UserContract $user, array $credentials)
{
$plain = $credentials['password'];
$salt =$user->getAuthSalt();
$upwd = md5($plain.$salt.config('app.authkey'));
return $user->getAuthPassword() == $upwd;
}

getAuthPassword是获取用户表中的password,但是我还要salt验证,就需要新建一个getAuthSalt()方法取得用户表中的salt,需要在\vendor\laravel\framework\src\Illuminate\Auth\Authenticatable.php,\vendor\laravel\framework\src\Illuminate\Auth\GenericUser.php,\vendor\laravel\framework\src\Illuminate\Contracts\Auth\Authenticatable.php,是不是好多文件不好找,其实在vendor文件下搜索一下getAuthPassword就基本知道要修改哪些文件了,
修改好的是这样的
\vendor\laravel\framework\src\Illuminate\Auth\Authenticatable.php

public function getAuthSalt()
{
return $this->salt;
}

\vendor\laravel\framework\src\Illuminate\Auth\GenericUser.php

public function getAuthSalt()
{
return $this->attributes['salt'];
}

\vendor\laravel\framework\src\Illuminate\Contracts\Auth\Authenticatable.php

public function getAuthPassword();

这样就万事大吉了,开心的写代码吧。

定义url获取access_token

在routers.php加入下面代码

Route::post('oauth/access_token', function() {
    return Response::json(Authorizer::issueAccessToken());
});

给需要登录才能看到的资源(控制器)加入oauth2中间件

如routers.php加入下面代码, 访问购物车时需要access_token

Route::put('wechat/{uniacid}/anas_shop/cart', ['middleware' => 'oauth', 'uses' => 'Anas_shop\CartController@put']);

提交表单时需要加入

<input type="hidden" name="access_token" value="xxxxxxxxxxxx" >

获取当前access_token的用户id

使用Authorizer::getResourceOwnerId(); 方法即可获取,这里写成model供控制器调用

<?php
namespace App;  //文件路径

use DB;
use Session;
use Illuminate\Support\Facades\Auth;
use Illuminate\Database\Eloquent\Model;
use LucaDegasperi\OAuth2Server\Facades\Authorizer;

class Functions extends Model {
      protected static function memberinfo(){
        $member_id = Authorizer::getResourceOwnerId(); 获取到的id
        $member = DB::table('ims_mc_members')->where('uid', $member_id)->first();
        return $member;
    }

}

更多oauth2的使用,去看文档吧

希望这篇文章能帮到你!

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 最近在和同学参与一个创业项目,用到了laravel,仔细研究了一下,发现laravel封装了很多开箱即用的方法,通...
    MakingChoice阅读 3,331评论 0 0
  • 2016-08-17 补充 Exception 部分改造方案的内容2016-08-13 补充 View 部分改造方...
    haolisand阅读 5,330评论 0 16
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,087评论 19 139
  • 先说几句废话,调和气氛。事情的起由来自客户需求频繁变更,伟大的师傅决定横刀立马的改革使用新的框架(created ...
    wsdadan阅读 3,115评论 0 12
  • 简介 laravel 使实施认证的变得非常简单,事实上,它提供了非常全面的配置项以适应应用的业务。认证的配置文件存...
    Dearmadman阅读 6,212评论 2 13