Home > Backend Development > PHP Tutorial > 20150720-Laravel login verification pitfalls

20150720-Laravel login verification pitfalls

WBOY
Release: 2016-08-08 09:20:37
Original
1725 people have browsed it

Record the pitfalls you have stepped on, and there will be fewer and fewer pitfalls in the future...

First create the table:

<code><span>php</span><span>artisan</span><span>migrate</span><span>:make_admin_table</span></code>
Copy after login

Then write the column settings of the table in the new file

<code><span><?</span>php

use Illuminate<span>\</span>Database<span>\</span>Schema<span>\</span>Blueprint;
use Illuminate<span>\</span>Database<span>\</span>Migrations<span>\</span>Migration;

class CreateAdminTable extends Migration {

    <span>/**
     * Run the migrations.
     *
     * @return void
     */</span><span>public</span> function up()
    {
        Schema<span>::create</span>(<span>'admin'</span>, function(<span>$table</span>)
        {
            <span>$table</span><span>-></span>increments(<span>'id'</span>);
            <span>$table</span><span>-></span><span>string</span>(<span>'staff_code'</span>, <span>32</span>)<span>-></span>nullable();           <span>//员工号</span><span>$table</span><span>-></span><span>string</span>(<span>'login_name'</span>, <span>32</span>)<span>-></span>nullable();           <span>//登录名</span><span>$table</span><span>-></span><span>string</span>(<span>'password'</span>, <span>32</span>)<span>-></span>nullabele();            <span>//登录密码</span><span>$table</span><span>-></span><span>string</span>(<span>'mail'</span>, <span>512</span>)<span>-></span>nullable();                <span>//电子邮箱</span><span>$table</span><span>-></span><span>string</span>(<span>'staff_name'</span>, <span>32</span>)<span>-></span>nullable();           <span>//员工姓名</span><span>$table</span><span>-></span><span>string</span>(<span>'sex'</span>, <span>10</span>)<span>-></span>nullable();                  <span>//性别</span><span>$table</span><span>-></span><span>string</span>(<span>'belong_to'</span>, <span>512</span>)<span>-></span>nullable();           <span>//所属部门</span><span>$table</span><span>-></span><span>string</span>(<span>'jobs'</span>, <span>512</span>)<span>-></span>nullable();                <span>//岗位</span><span>$table</span><span>-></span><span>string</span>(<span>'telephone'</span>, <span>32</span>)<span>-></span>nullable();            <span>//固定电话</span><span>$table</span><span>-></span><span>string</span>(<span>'mobile'</span>, <span>32</span>)<span>-></span>nullable();               <span>//手机号</span>
        });
    }

    <span>/**
     * Reverse the migrations.
     *
     * @return void
     */</span><span>public</span> function down()
    {
        Schema<span>::dropIfExists</span>(<span>'admin'</span>);
    }

}</code>
Copy after login

Create the Model model Admin:

<code>php ratisan <span>generate</span> modle Admin</code>
Copy after login

Add

<code><span><?php</span><span>use</span><span>Illuminate</span>\<span>Auth</span>\<span>UserTrait</span>;
<span>use</span><span>Illuminate</span>\<span>Auth</span>\<span>UserInterface</span>;
<span>use</span><span>Illuminate</span>\<span>Auth</span>\<span>Reminders</span>\<span>RemindableTrait</span>;
<span>use</span><span>Illuminate</span>\<span>Auth</span>\<span>Reminders</span>\<span>RemindableInterface</span>;

<span><span>class</span><span>Admin</span><span>extends</span> \<span>Eloquent</span><span>implements</span><span>UserInterface</span>, <span>RemindableInterface</span> {</span><span>use</span><span>UserTrait</span>, <span>RemindableTrait</span>;

    <span>protected</span><span>$fillable</span> = [];

    <span>protected</span><span>$table</span> = <span>'admin'</span>; <span>// 指定表名</span><span>protected</span><span>$primaryKey</span> = <span>'id'</span>; <span>// 指定主键名</span><span>protected</span><span>$hidden</span> = <span>array</span>(<span>'password'</span>);  <span>//密码字段</span><span>public</span><span>$timestamps</span> = <span>false</span>; <span>// 关闭 创建时间 与 更新时间 的自动维护</span><span>public</span><span><span>function</span><span>getRememberToken</span><span>()</span>{</span><span>return</span><span>$this</span>->rememberToken ;
    }

    <span>public</span><span><span>function</span><span>setRememberToken</span><span>(<span>$value</span>)</span>{</span><span>$this</span>->rememberToken = <span>$value</span> ;
    }

    <span>public</span><span><span>function</span><span>getRememberTokenName</span><span>()</span>{</span><span>return</span><span>$this</span>->reminder ;
    }
}</span></code>
Copy after login

to the generated file and explain, because login verification is required and laravel’s own Auth is used, so you need to add use and inherit the UserInterface and RemindableInterface interfaces and rewrite some methods
The specific ones are these few sentences

<code><span>use</span><span>Illuminate</span>\<span>Auth</span>\<span>UserTrait</span>;
<span>use</span><span>Illuminate</span>\<span>Auth</span>\<span>UserInterface</span>;
<span>use</span><span>Illuminate</span>\<span>Auth</span>\<span>Reminders</span>\<span>RemindableTrait</span>;
<span>use</span><span>Illuminate</span>\<span>Auth</span>\<span>Reminders</span>\<span>RemindableInterface</span>;

<span><span>class</span><span>Admin</span><span>extends</span> \<span>Eloquent</span><span>implements</span><span>UserInterface</span>, <span>RemindableInterface</span> {</span><span>use</span><span>UserTrait</span>, <span>RemindableTrait</span>;
    <span>/*******
    以下代码省略
    *******/</span><span>public</span><span><span>function</span><span>getRememberToken</span><span>()</span>{</span><span>return</span><span>$this</span>->rememberToken ;
    }

    <span>public</span><span><span>function</span><span>setRememberToken</span><span>(<span>$value</span>)</span>{</span><span>$this</span>->rememberToken = <span>$value</span> ;
    }

    <span>public</span><span><span>function</span><span>getRememberTokenName</span><span>()</span>{</span><span>return</span><span>$this</span>->reminder ;
    }
    }</code>
Copy after login

Then I continue to find the settings of the Auth file and modify the tables that need to be used
app/config/auth.php
Find the following fields and modify them into the tables you specify

<code><span><?php</span><span>return</span><span>array</span>(

<span>'driver'</span> => <span>'eloquent'</span>, <span>//验证方式,有database和eloquent两种</span><span>'model'</span> => <span>'Admin'</span>, <span>//所使用的model名</span><span>'table'</span> => <span>'admin'</span>, <span>//对应的表名</span><span>'reminder'</span> => <span>array</span>(

        <span>'email'</span> => <span>'emails.auth.reminder'</span>,

        <span>'table'</span> => <span>'password_reminders'</span>,

        <span>'expire'</span> => <span>60</span>,

    ),

);</span></code>
Copy after login

Then add the controller method:

<code><span>//获取登录页面</span><span>public</span> function get_web_login(){

        <span>return</span> View<span>::make</span>(<span>'web.web_login'</span>);

    }

    <span>//登录验证</span><span>public</span> function post_login(){
        <span>if</span> (Auth<span>::attempt</span>(<span>array</span>(<span>'login_name'</span><span>=></span>Input<span>::get</span>(<span>'login_name'</span>), <span>'password'</span><span>=></span>Input<span>::get</span>(<span>'password'</span>)))) {

            Notification<span>::success</span>(<span>'登录成功'</span>);

            <span>return</span> Redirect<span>::to</span>(<span>'/web/index'</span>)
            <span>-></span><span>with</span>(<span>'message'</span>, <span>'成功登录'</span>);
        } <span>else</span> {

            Notification<span>::warning</span>(<span>'用户名密码不正确'</span>);

            <span>return</span> Redirect<span>::to</span>(<span>'/web/login'</span>)
            <span>-></span><span>with</span>(<span>'message'</span>, <span>'用户名密码不正确'</span>)
                <span>-></span>withInput();
        }

    }</code>
Copy after login

Then the view file login.blade.php:

<code><span>@section</span>(<span>'title'</span>)登录 - <span>@parent</span><span>@stop</span><span>@section</span>(<span>'nav_1'</span>)
    <li <span>class</span>=<span>"active"</span>><a href=<span>"#"</span>>登录</a></li>
<span>@stop</span><span>@section</span>(<span>'selection'</span>)
    <div id=<span>"login"</span><span>class</span>=<span>"login"</span>>
        <form <span>class</span>=<span>"form"</span> role=<span>"form"</span> action=<span>"{{URL::route('web.web_login.post')}}"</span> style=<span>"width: 500px"</span> method=<span>"post"</span>>
            <span>@if</span> (Session::has(<span>'message'</span>))

                <div <span>class</span>=<span>"alert alert-error"</span>>{{ Session::get(<span>'message'</span>)}}</div>

            <span>@endif</span>
            <div <span>class</span>=<span>"form-group"</span>>
                <label <span>for</span>=<span>"login_name"</span>>登录名:</label>
                <input <span>type</span>=<span>"text"</span><span>class</span>=<span>"form-control"</span> id=<span>"login_name"</span> name=<span>"login_name"</span>>
                <label <span>for</span>=<span>"password"</span>>密码:</label>
                <input <span>type</span>=<span>"password"</span><span>class</span>=<span>"form-control"</span> id=<span>"password"</span> name=<span>"password"</span>>

            </div>
            <div align=<span>"left"</span>>
                <button <span>type</span>=<span>"submit"</span><span>class</span>=<span>"btn btn-info btn-lg"</span>><span <span>class</span>=<span>"glyphicon glyphicon-user"</span> aria-hidden=<span>"true"</span>></span>  登录</button>


            </div>
        </form>
    </div>
<span>@stop</span></code>
Copy after login

Finally update the route

<code>Route::get(<span>'/web/index'</span>, <span>array</span>(<span>'as'</span> => <span>'web.web_index'</span>, <span>'uses'</span> => <span>'App\Controllers\Api\WebController@get_web_index'</span>));
<span>//登录页面</span>
Route::get(<span>'/web/login'</span>, <span>array</span>(<span>'as'</span> => <span>'web.web_login'</span>, <span>'uses'</span> => <span>'App\Controllers\Api\WebController@get_web_login'</span>));
Route::post(<span>'/web/login'</span>, <span>array</span>(<span>'as'</span> => <span>'web.web_login.post'</span>, <span>'uses'</span> => <span>'App\Controllers\Api\WebController@post_login'</span>));
</code>
Copy after login

After completing the above work, I’m done I opened the database and randomly stuffed a piece of user data into it, then tried to log in, and then the problem came

No matter how I tried, the account password was wrong

I Googled it on Baidu, but I didn't find any results
In desperation, I can only look at the source code of laravel
The first thing to call is the attempt method to verify the username and password, so I jump into this function to take a look

<code><span>/**
         * Attempt to authenticate a user using the given credentials.
         *
         *<span> @param</span> array $credentials
         *<span> @param</span> bool $remember
         *<span> @param</span> bool $login
         *<span> @return</span> bool 
         *<span> @static</span>         */</span><span>public</span><span>static</span> function <span>attempt</span>($credentials = array(), $remember = <span>false</span>, $login = <span>true</span>){
            <span>return</span> \Illuminate\Auth\Guard::attempt($credentials, $remember, $login);
        }</code>
Copy after login

It’s not difficult to see that it just returns the result of the Guar::attempt method, so I continue to look in

<code><span>/**
     * Attempt to authenticate a user using the given credentials.
     *
     * @param  array  $credentials
     * @param  bool   $remember
     * @param  bool   $login
     * @return bool
     */</span><span>public</span> function attempt(<span>array</span><span>$credentials</span><span>=</span><span>array</span>(), <span>$remember</span><span>=</span><span>false</span>, <span>$login</span><span>=</span><span>true</span>)
    {
        <span>$this</span><span>-></span>fireAttemptEvent(<span>$credentials</span>, <span>$remember</span>, <span>$login</span>);

        <span>$this</span><span>-></span>lastAttempted <span>=</span><span>$user</span><span>=</span><span>$this</span><span>-></span>provider<span>-></span>retrieveByCredentials(<span>$credentials</span>);

        <span>// If an implementation of UserInterface was returned, we'll ask the provider</span><span>// to validate the user against the given credentials, and if they are in</span><span>// fact valid we'll log the users into the application and return true.</span><span>if</span> (<span>$this</span><span>-></span>hasValidCredentials(<span>$user</span>, <span>$credentials</span>))
        {
            <span>if</span> (<span>$login</span>) <span>$this</span><span>-></span>login(<span>$user</span>, <span>$remember</span>);

            <span>return</span><span>true</span>;
        }

        <span>return</span><span>false</span>;
    }</code>
Copy after login

We’re here , you can probably know that the login result should be controlled by the result returned by the hasValidCredentials method, so how is it implemented internally? Go in and take a look

<code><span>/**
     * Determine if the user matches the credentials.
     *
     *<span> @param</span>  mixed  $user
     *<span> @param</span>  array  $credentials
     *<span> @return</span> bool
     */</span><span>protected</span> function <span>hasValidCredentials</span>($user, $credentials)
    {
        <span>return</span> ! is_null($user) && $<span>this</span>->provider->validateCredentials($user, $credentials);
    }</code>
Copy after login

However, here is just a simple judgment to determine whether the $user parameter exists, so I continue to move to the validateCredentials method

<code><span>/**
     * Validate a user against the given credentials.
     *
     *<span> @param</span>  \Illuminate\Auth\UserInterface  $user
     *<span> @param</span>  array  $credentials
     *<span> @return</span> bool
     */</span><span>public</span> function <span>validateCredentials</span>(UserInterface $user, array $credentials);</code>
Copy after login

When I get here, I am a newbie in laravel and I can’t understand what it means, so I can only continue. Google, and really found some relevant information for me
Extended Auth functionality
After reading this post and understanding the above code
Follow the directory it says
/vender/laravel/framework/src/illuminate/Auth
So I found the file EloquentUserProvider.php
I found the specific implementation of the validateCredentials method inside it

<code><span>/**
     * Validate a user against the given credentials.
     *
     *<span> @param</span>  \Illuminate\Auth\UserInterface  $user
     *<span> @param</span>  array  $credentials
     *<span> @return</span> bool
     */</span><span>public</span> function <span>validateCredentials</span>(UserInterface $user, array $credentials)
    {
        $plain = $credentials[<span>'password'</span>];

        <span>return</span> $<span>this</span>->hasher->check($plain, $user->getAuthPassword());
    }</code>
Copy after login

Now it’s clear

When laravel verifies the password, it will hash the entered password and then compare it with the password stored in the database

However, I directly A clear text password is added to the database, so it is reasonable to see that the password is incorrect
Therefore, when storing the password field, be sure to remember to use

<code>Hash::make(<span>"<span>$passowrd</span>"</span>);</code>
Copy after login

to generate the hash string corresponding to the password...
Then I reported an error when I used this method to write the password hash string to the database. After checking, it turned out that the password field I set was too short, so I changed the password field length to 1024 words and the problem was solved
This trap has troubled me all morning... Record it for everyone's reference to avoid being scammed like me again
_ (:з ∠)_

I also found a bolg saying what it is like It should be used in the future to change laravel's default encryption method to a custom MD5 encryption method. Post it here for future reference. Laravel changes the default login password encryption method

(End)

Copyright statement: This article is the original article of the blogger and may not be reproduced without the permission of the blogger.

The above introduces the pitfalls encountered in 20150720-Laravel login verification, including the relevant content. I hope it will be helpful to friends who are interested in PHP tutorials.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template