Lumen框架 之api用户认证
一、配置
1、在\app\bootstrap\app.php中取消注释
$app->withFacades(); $app->withEloquent(); $app->routeMiddleware([ 'auth' => App\Http\Middleware\Authenticate::class ]); $app->register(App\Providers\AuthServiceProvider::class);
2、创建用户数据模型
<?php namespace App\Models; use Illuminate\Auth\Authenticatable; use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract; use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Laravel\Lumen\Auth\Authorizable; class User extends Model implements AuthenticatableContract, AuthorizableContract { use Authenticatable, Authorizable, HasFactory; protected $table = 'users'; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'name', 'email', 'api_token' ]; /** * The attributes excluded from the model's JSON form. * * @var array */ protected $hidden = [ 'password', ]; }
3、路由定义
$router->post('/user/login', ['uses' => 'ExampleController@doLogin']); $router->group(['middleware' => 'auth'], function () use ($router) { $router->get('/user/info', ['uses' => 'ExampleController@info']); });
4、Controller逻辑
<?php namespace App\Http\Controllers; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\DB; class ExampleController extends Controller { /** * Create a new controller instance. * * @return void */ public function __construct() { } /** * 用户登录 * @return \Illuminate\Http\JsonResponse */ public function doLogin() { $username = request()->input('username'); $password = request()->input('password'); $admin = DB::table('users')->where('username', $username)->first(); if($admin) { if($admin->password == md5(md5($password).$admin->salt)) { $token = md5($admin->id.time()); DB::table('users')->where('id', '=', $admin->id)->update([ 'api_token' => $token ]); $admin->api_token = $token; return response()->json(['code' => 0, 'msg' => '登录成功', 'data' => $admin]); } } return response()->json(['code' => -1, 'msg' => '登录失败']); } /** * 获取用户信息 * @return \Illuminate\Http\JsonResponse */ public function info() { $user = Auth::user(); return response()->json(['code' => 0, 'msg' => '获取成功', 'data' => $user]); } }
5、认证服务,修改\app\Http\Providers\AuthServiceProvider.php文件代码
<?php namespace App\Providers; use App\Models\User; use Illuminate\Support\Facades\Gate; use Illuminate\Support\ServiceProvider; class AuthServiceProvider extends ServiceProvider { /** * Register any application services. * * @return void */ public function register() { // } /** * Boot the authentication services for the application. * * @return void */ public function boot() { // Here you may define how you wish users to be authenticated for your Lumen // application. The callback which receives the incoming request instance // should return either a User instance or null. You're free to obtain // the User instance via an API token or any other method necessary. $this->app['auth']->viaRequest('api', function ($request) { $token = $request->headers->get('api_token'); if ($token) { return User::where('api_token', $token)->first(); } }); } }
6、定义认证中间件,修改\app\Http\Middleware\Authenticate.php
<?php namespace App\Http\Middleware; use Closure; use Illuminate\Contracts\Auth\Factory as Auth; class Authenticate { /** * The authentication guard factory instance. * * @var \Illuminate\Contracts\Auth\Factory */ protected $auth; /** * Create a new middleware instance. * * @param \Illuminate\Contracts\Auth\Factory $auth * @return void */ public function __construct(Auth $auth) { $this->auth = $auth; } /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @param string|null $guard * @return mixed */ public function handle($request, Closure $next, $guard = null) { if ($this->auth->guard($guard)->guest()) { return response()->json(['code' => 401, 'msg' => 'Unauthorized.']); } return $next($request); } }