05创建laravel5.8前后台api项目--jwt前台后台账号分离

安装jwt-auth

官方安装教程点击此处,我想要实现前台affiliate用户生成token跟后台admin用户生成token互不影响,首先创建两张表:执行命令php artisan make:model Affiliate -a 和 php artisan make:model Admin -a

increments('id');
            $table->string('email', 32);
            $table->string('password', 128);
            $table->tinyInteger('status');
            $table->timestamps();
        });
    }
}
increments('id');
            $table->string('email', 32);
            $table->string('password', 128);
            $table->tinyInteger('status');
            $table->timestamps();
        });
    }

}

配置jwt-auth

官方快速使用教程点击此处,推荐先撸一遍官网代码,然后尝试实践这个前后台账号分离的教程。

第一步:修改App\Models\Affiliate model文件

getKey();
    }

    /**
     * Return a key value array, containing any custom claims to be added to the JWT.
     *
     * @return array
     */
    public function getJWTCustomClaims()
    {
        return [];
    }
}

第二步:修改config/auth.php 配置了两个守卫中间件,想在路由使用frontend则需要指定auth:frontend(见第三步)

 [
        'guard' => 'frontend',
        'passwords' => 'users',
    ],

    'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],

        'frontend' => [
            'driver' => 'jwt',
            'provider' => 'affiliate',
        ],

        'backend' => [
            'driver' => 'jwt',
            'provider' => 'admin',
        ],
    ],

    'providers' => [
        'affiliate' => [
            'driver' => 'eloquent',
            'model' => App\Models\Affiliate::class,
        ],

        'admin' => [
            'driver' => 'eloquent',
            'model' => App\Models\Admin::class,
        ],

    ],
];

第三步:修改routes\local\frontend.php,第一个路由组不需要校验登录,第二个路由组需要走auth:frontend登录

group(function(){

    Route::group(['prefix' => 'affiliate'], function () {
        // 用户登录
        Route::post('login', 'AffiliateController@login');
        // 用户注册
        Route::post('register', 'AffiliateController@register');
        // 发重置密码邮件
        Route::post('password/email', 'AffiliateController@password_email');

        // 重置密码
        Route::post('password/reset', 'AffiliateController@password_reset');
    });
    
});


Route::group(['namespace' => 'Frontend', 'middleware' => ['auth:frontend']], function(){
    Route::group(['prefix' => 'affiliate'], function () {
        // 验证token
        Route::post('me', 'AffiliateController@me');
        // 用户登出
        Route::post('logout', 'AffiliateController@logout');
        // 修改密码
        Route::post('password/update', 'AffiliateController@password_update');
    });
});

第四步:修改App\Http\Controllers\Frontend\AffiliateController

input('email');
        $password = Hash::make(request()->input('password'));
        $ret = Affiliate::where('email', $email)->first();
        if($ret) return response()->json(['error' => 'email exist'], 500);
        
        Affiliate::create(['email' => $email, 'password'=>$password]);
        return response()->json(['success' => 'registered successfully'], 200);
    }

    // 登录
    public function login()
    {
        $credentials = request(['email', 'password']);

        if (! $token = auth()->attempt($credentials)) {
            return response()->json(['error' => 'Unauthorized'], 401);
        }

        return response()->json([
            'access_token' => 'bearer '.$token,
            'expires_in' => auth()->factory()->getTTL() * 60
        ]);
    }

    // 查询账号信息
    public function me()
    {
        return response()->json(auth()->user());
    }

}

模仿affiliate代码新建实现admin账号系统的代码

第一步:修改App\Models\Admin model文件

getKey();
    }

    /**
     * Return a key value array, containing any custom claims to be added to the JWT.
     *
     * @return array
     */
    public function getJWTCustomClaims()
    {
        return [];
    }
}

第二步:修改routes\local\backend.php

group(function(){
    Route::group(['prefix' => 'admin'], function () {
        // 用户登录
        Route::post('login', 'AdminController@login');
        // 用户注册
        Route::post('register', 'AdminController@register');
    });
    
});

Route::group(['namespace' => 'Backend', 'middleware' => 'auth:backend'], function(){
    Route::group(['prefix' => 'admin'], function () {
        // 验证token
        Route::post('me', 'AdminController@me');
    });
});

第三步:修改App\Http\Controllers\Backend\AdminController。方法Auth()就是Auth('frontend')的意思,默认是frontend账号;后台用户使用Auth('backend'),前面配置过了。

input('email');
        $password = Hash::make(request()->input('password'));
        $ret = Admin::where('email', $email)->first();
        if($ret) return response()->json(['error' => 'email exist'], 500);

        Admin::create(['email' => $email, 'password'=>$password]);
        return response()->json(['success' => 'registered successfully'], 200);
    }

    public function login()
    {
        $credentials = request(['email', 'password']);

        if (! $token = auth('backend')->attempt($credentials)) {
            return response()->json(['error' => 'Unauthorized'], 401);
        }

        return response()->json([
            'access_token' => 'bearer '.$token,
            'expires_in' => auth('backend')->factory()->getTTL() * 60
        ]);
    }

    public function me()
    {
        $user = auth('backend')->user();
        return response()->json($user);
    }
}

效果演示

 

源代码地址:https://github.com/windawake/laravel-repository-pratice/tree/master

你可能感兴趣的:(laravel)