laravel5.5用户认证
程序员文章站
2022-05-19 15:50:26
...
之前对应laravel的用户认证模模糊糊的,现在认真的看了一下文档和查阅资料对用户手动认证的功能总结了一下
1.配置路由
Route::get('/','aaa@qq.com)
2.在/config/auth.php里找到guards和providers添加自己增加的配置
'guards' => [
'web' => [//控制器如不使用guard默认使用web,
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
],
//此处为自己添加的配置
'admin' => [
'driver' => 'session',
'provider' => 'users',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Model\Users::class,//模块里用户表对应的模型
],
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
3.创建用户表对应模型和在\database\migrations下的他对应的数据库迁移文件
在/app文件夹下会多一个/Model/Users模型
php artisan make:model Model/Users -m
修改刚创建的迁移文件为
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name')->unique();
$table->string('password');
$table->string('email')->unique();
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
执行下面命令,生成数据库表(前提是数据库名和账号密码在.env文件配好)
php artisan migrate
4.使用模型工厂,填充测试数据
在/database/factories下的文件里,改为
<?php
use Faker\Generator as Faker;
$factory->define(App\Model\Users::class, function (Faker $faker) {//App\Model\Users::class指的是用户表对应的模型
static $password;
return [
'name' => $faker->name,
'email' => $faker->unique()->safeEmail,
'password' => $password ?: $password = bcrypt('secret'), // secret
'remember_token' => str_random(10),
];
});
执行php artisan tinker
回车的命令行里输入 factory(App\Model\Users::class,3)->create()
然后在表里生成3条记录
5.模型里/app/Model/Users模型继承 /app下的User模型
<?php
namespace App\Model;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Auth\User;//引入User模型,让Users模型继承,
class Users extends User
{
//
}
6.在控制器里的login方法里写用户认证
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
class LoginController extends Controller
{
public function login()
{
$status = Auth::guard('admin')->attempt([
'name'=>'Gussie Ryan',
'password'=>'secret',
'email'=>'aaa@qq.com',
],FALSE);
}
}
就此完成认证
注意:上面获取的用户密码会自动解密,未登录跳转登录默认是Login控制器的login方法,最好带上name,我自己试的时候没带上name报错
Route::get('login', "aaa@qq.com")->name('login');
7.常见的操作方法
// 获取当前认证用户...
$user = Auth::guard('admin')->user();
// 获取当前认证用户的ID...
$id = Auth::guard('admin')->id();
//判断用户是否认证
$status=Auth::guard('admin')->check();
//用户退出
Auth::guard('admin')->logout();
8.实现未登录跳转到登录页面的中间件验证
Route::get('/', "aaa@qq.com")->middleware("auth:admin");
加中间件即可
tips:如果登录之后返回之前的页面带参数怎么办
可以自定义auth
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Contracts\Auth\Factory as Auth;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Routing\Router;
class MyAuth
{
/**
* The authentication 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[] ...$guards
* @return mixed
*
* @throws \Illuminate\Auth\AuthenticationException
*/
public function handle($request, Closure $next, ...$guards)
{
$this->authenticate($guards);
return $next($request);
}
/**
* Determine if the user is logged in to any of the given guards.
*
* @param array $guards
* @return void
*
* @throws \Illuminate\Auth\AuthenticationException
*/
protected function authenticate(array $guards)
{
//记录当前的URL到session,登录后跳转到这个session
$current_uri = \Request::getRequestUri();
if($current_uri != '/login'){
$redirect_to_product_arr = ['/cart'];
if(in_array($current_uri, $redirect_to_product_arr)) {
//如果是添加到购物车,那么登陆后跳转到商品详情页面
session(['url.intended' => route('products.show',session('product_detail_id'))]);
} else {
session(['url.intended' => url()->current()]);
}
}
if (empty($guards)) {
return $this->auth->authenticate();
}
foreach ($guards as $guard) {
if ($this->auth->guard($guard)->check()) {
return $this->auth->shouldUse($guard);
}
}
throw new AuthenticationException('Unauthenticated.', $guards);
}
}
可能会疑问这些代码是什么,这是auth中间件的源码
源码对应位置
跳转利用的是
return redirect()->intended('home');
其中是默认值
原理解析
会在 session 中存储一个值,把用户要访问的地址存到 session 中
redirect()->intended('home') 会把这个值取出来跳转到这个地址,如果没有就跳到默认地址
$path = $this->session->pull('url.intended', $default);
return $this->to($path, $status, $headers, $secure);