laravel 使用attempt登录认证
1、数据库如下:
注意:laravel的自带登录认证attempt默认使用的就是bcrypt函数的加密算法,如果用了别的加密算法会出现匹配不上的就返回了false的情况;所以演示数据库密码是:123456,用来
$aaa = Hash::make("123456")
得到的。
2、控制器( App\Http\Controllers\Admin\admin.php)
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
// use Illuminate\Support\Facades\DB;
// use Illuminate\Support\Facades\Hash;
class Admin extends Controller
{
// 管理首页
public function index()
{
return '欢迎进入后台管理系统';
// return View('admin/admin');
}
// 登录界面
public function login()
{
return View('admin/login');
}
// 登录验证
public function chklogin(Request $request)
{
$username = trim($request->username);
$password = trim($request->password);
$verify = trim($request->verify);
// 密码不支持MD5验证,改为明文也不行,最后网上找到方法将密码加密存进数据库
// $aaa = Hash::make("123456");
session_start();
$code = $_SESSION['code'];
if ($verify == '') {
exit(json_encode(['code'=>401,'msg'=>'请输入验证码']));
}
if (strtolower($verify) != strtolower($code)) {
exit(json_encode(['code'=>401,'msg'=>'验证码错误']));
}
if (!Auth::attempt(['username'=>$username,'password'=>$password])) {
exit(json_encode(['code'=>401,'msg'=>'用户名或密码错误']));
};
dump($username, $password, $verify);
// dump($password);
// dump($verify);
}
//获取验证码
public function get_verify()
{
return self::create();
}
}
2.1、基类控制器( app\Http\Controllers\Controller.php)
namespace App\Http\Controllers;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;
class Controller extends BaseController
{
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
// 获取验证码配置
private static function _getCodeConfig()
{
return [
// 验证码字符集
'codeStr' => 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789',
// 验证码个数
'codeCount' => 4,
// 字体大小
'fontsize' =>18,
// 验证码的宽度
'width' => 100,
// 验证码高度
'height' => 36,
// 是否有干扰点?true有,false没有
'disturbPoint' => true,
// 干扰点个数,disturbPoint开启后生效
'pointCount' => 100,
// 是否有干扰条?true有,false没有
'disturbLine' => true,
// 干扰条个数,disturbLine开启后生效
'lineCount' => 3
];
}
// 创建图片验证码
public static function create()
// public static function create()
{
// 配置
$config = self::_getCodeConfig();
//创建画布
$image = imagecreatetruecolor($config['width'], $config['height']);
//背景颜色
$bgcolor=imagecolorallocate($image, 255, 255, 255);
imagefill($image, 0, 0, $bgcolor);
$captch_code = '';//存储验证码
$captchCodeArr = str_split($config['codeStr']);
//随机选取4个候选字符
for ($i=0;$i<$config['codeCount'];$i++) {
$fontsize = $config['fontsize'];
$fontcolor=imagecolorallocate($image, rand(0, 120), rand(0, 120), rand(0, 120));//随机颜色
$fontcontent = $captchCodeArr[rand(0, strlen($config['codeStr'])-1)];
$captch_code.=$fontcontent;
$_x = $config['width']/$config['codeCount'];
$x=($i*(int)$_x)+rand(5, 10); //随机坐标
$y=rand(5, 10);
imagestring($image, $fontsize, $x, $y, $fontcontent, $fontcolor); // 水平地画一行字符串
}
session_start();
$_SESSION['code']=$captch_code;
//增加干扰点
if ($config['disturbPoint']) {
for ($i=0;$i<$config['pointCount'];$i++) {
$pointcolor=imagecolorallocate($image, rand(50, 200), rand(50, 200), rand(50, 200));
imagesetpixel($image, rand(1, 99), rand(1, 29), $pointcolor);
}
}
//增加干扰线
if ($config['disturbLine']) {
for ($i=0;$i<$config['lineCount'];$i++) {
$linecolor=imagecolorallocate($image, rand(80, 280), rand(80, 220), rand(80, 220));
imageline($image, rand(1, 99), rand(1, 29), rand(1, 99), rand(1, 29), $linecolor);
}
}
//输出格式
header('content-type:image/png');
imagepng($image);
//销毁图片
imagedestroy($image);
}
}
3、路由(routes\web.php)
// 登录页面
Route::get('admin/login', 'Admin\Admin@login');
//获取验证码
Route::get('admin/verify', 'Admin\Admin@get_verify');
//登录验证
Route::post('admin/chklogin', 'Admin\Admin@chklogin');
//后台首页
Route::get('admin/', 'Admin\Admin@index');
4、视图(resources\views\admin\login.blade.php)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>管理员登录 - 后台管理</title>
<meta name="renderer" content="webkit">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0">
<script type="text/javascript" src="/static/layui/layui.js"></script>
<link rel="stylesheet" href="/static/layui/css/layui.css">
<link rel="stylesheet" href="/static/style.css">
</head>
<body>
<div class="layadmin-user-login layadmin-user-display-show" id="LAY-user-login" style="display: none;">
<div class="layadmin-user-login-main">
<div class="layadmin-user-login-box layadmin-user-login-header">
<h2>后台管理系统</h2>
</div>
<div class="layadmin-user-login-box layadmin-user-login-body layui-form">
@CSRF
<div class="layui-form-item">
<label class="layadmin-user-login-icon layui-icon layui-icon-username"
for="LAY-user-login-username"></label>
<input type="text" name="username" id="username" lay-verify="required" placeholder="用户名"
class="layui-input">
</div>
<div class="layui-form-item">
<label class="layadmin-user-login-icon layui-icon layui-icon-password"
for="LAY-user-login-password"></label>
<input type="password" name="password" id="password" lay-verify="required" placeholder="密码"
class="layui-input">
</div>
<div class="layui-form-item">
<div class="layui-row">
<div class="layui-col-xs7">
<label class="layadmin-user-login-icon layui-icon layui-icon-vercode"
for="LAY-user-login-vercode"></label>
<input type="text" name="verity" id="verify" placeholder="验证码" class="layui-input" maxlength="4">
</div>
<div class="layui-col-xs5">
<div style="margin-left: 10px;">
<img id="img" class="verifyImg layadmin-user-login-codeimg" id="LAY-user-get-vercode"
onclick="this.src=this.src+'?c='+Math.random();"
src="/admin/verify" />
</div>
</div>
</div>
</div>
<div class="layui-form-item">
<button class="layui-btn layui-btn-fluid layui-bg-blue" onclick="login()" id="login">登录</button>
</div>
</div>
</div>
</div>
<script type="text/javascript">
//加载layer弹窗模块(会自动加载jquery)
layui.use(['layer'], () => {
ly = layui.layer;
$ = layui.jquery;
});
//登录校验
function login() {
let username = $("#username").val();
let password = $("#password").val();
let verify = $("#verify").val();
if(!username || !password){
ly.msg("请输入用户名或者密码!");
return false;
}
if(!verify){
ly.msg("请输入验证码!");
return false;
}
send_ajax();
}
// 提交表单数据
function send_ajax(){
$.ajax({
type: "POST",
url: "/admin/chklogin",
dataType: "json",
data: {
username:$("#username").val(),
password:$("#password").val(),
verify:$('#verify').val(),
_token:$('input[name="_token"]').val()
},
success: function(data){}
});
}
</script>
</body>
</html>
5、User.php(app\User.php)
//指定数据表名称
protected $table = 'admin';
用户名或密码空
验证码错误
登录成功
总结
老师讲课时并没有说密码是以什么方式加密保存的,使用attempt登录认证一直返回错误,大坑啊 ~ 折腾了几个小时 ~
老师提高验证码类我把方法放到了基类控制器中,使用
self::create();
调用;CSS文件没放了,借用layui admin的例子。