简体   繁体   English

Laravel 5.2:登录后,应用程序丢失了会话

[英]Laravel 5.2: After login the app lost session

I'm trying fix this for one entire day, searching many times and many ways in Google. 我正在整天尝试修复此问题,并在Google中进行了许多次搜索。

After I enter my username and password I get a 401 Unauthorized, but in the /storage/framework/session the file is created. 输入用户名和密码后,我得到401 Unauthorized,但在/ storage / framework / session中创建了文件。

Login page parts 登录页面部分

<meta name="csrf-token" content="{{ csrf_token() }}">

...

<form class="login-form" action="admin/login" method="post">
                <h3 class="form-title">Access Data</h3>
                <div class="alert alert-danger display-hide">
                    <button class="close" data-close="alert"></button>
                    <span>
                    Username or password invalid. </span>
                </div>
                <div class="form-group">
                    <!--ie8, ie9 does not support html5 placeholder, so we just show field title for that-->
                    <label for="username" class="control-label visible-ie8 visible-ie9">Username</label>
                    <div class="input-icon">
                        <i class="fa fa-user"></i>
                        <input class="form-control placeholder-no-fix" type="text" autocomplete="off" placeholder="Username" name="username"/>
                    </div>
                </div>
                <div class="form-group">
                    <label for="password" class="control-label visible-ie8 visible-ie9">Password</label>
                    <div class="input-icon">
                        <i class="fa fa-lock"></i>
                        <input class="form-control placeholder-no-fix" type="password" autocomplete="off" placeholder="Password" name="password"/>
                    </div>
                </div>
                <div class="form-actions">
                    <label class="checkbox">
                    <input type="checkbox" name="remember" value="1"/> Remember me </label>
                    <button type="submit" id="submit" class="btn blue pull-right">
                    Login <i class="m-icon-swapright m-icon-white"></i>
                    </button>
                </div>
                <input type="hidden" name="_token" value="{{ csrf_token() }}" />
            </form>

...

<script>
            $('#submit').on('click', function (e) {
                e.preventDefault();
                data = $('form').serialize();

                $.ajax({
                    'method': 'POST',
                    'url': 'admin/login',
                    'data': data,
                    'dataType': 'JSON',
                    'success': function (data) {
                        if (data.type === 'redirect') {
                            window.location.href = 'admin/dashboard';
                        } else {
                            console.log(data);
                        }
                    }
                });
            });
        </script>

In the end of jquery.min file 在jquery.min文件的末尾

$.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
});

Route.php Route.php

/*
|--------------------------------------------------------------------------
| Routes File
|--------------------------------------------------------------------------
|
| Here is where you will register all of the routes in an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/

Route::get('/', function () {
    return view('welcome');
});

/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| This route group applies the "web" middleware group to every route
| it contains. The "web" middleware group is defined in your HTTP
| kernel and includes session state, CSRF protection, and more.
|
*/
Route::group(['middleware' => ['web']], function () {
    //Route::group(['prefix' => 'admin'], function() {
        Route::get('admin', ['uses' => 'UsersController@getLogin']);
        Route::post('admin/login', ['uses' => 'UsersController@doLogin']);
        Route::post('admin/logout', ['uses' => 'UsersController@doLogout']);
    //});
});

Route::group(['middleware' => ['web', 'auth']], function () {
    //Route::group(['prefix' => 'admin'], function() {
        Route::get('admin/dashboard', function() {
            return view('admin/dashboard');
        });
    //});
});

UsersController.php UsersController.php

<?php

namespace App\Http\Controllers;

use Request, Validator, Redirect, Hash, Auth;
use Illuminate\Support\Facades\Input;
use App\Models\UsersAuth;
use App\Models\UsersModel;

class UsersController extends Controller {
    function getLogin() {
        return view('admin/index');
    }

    function doLogin() {
        $validator = Validator::make(Input::all(), [
            'username' => 'required',
            'password' => 'required|alphaNum|min:5'
        ]);

        if($validator->fails()) {
            /*...*/
        } else {
            if(Auth::attempt(['username' => Input::get('username'), 'password' => Input::get('password'), 'active' => '1'])) {
                if(Auth::check()) {
                    return json_encode(['type' => 'redirect']);
                }
            } else {
                return json_encode(['type' => 'danger', 'msg' => 'Username or password is invalid.']);
            }
        }
    }
}

Auth.php Auth.php

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Authentication Defaults
    |--------------------------------------------------------------------------
    |
    | This option controls the default authentication "guard" and password
    | reset options for your application. You may change these defaults
    | as required, but they're a perfect start for most applications.
    |
    */

    'defaults' => [
        'guard' => 'web',
        'passwords' => 'users',
    ],

    /*
    |--------------------------------------------------------------------------
    | Authentication Guards
    |--------------------------------------------------------------------------
    |
    | Next, you may define every authentication guard for your application.
    | Of course, a great default configuration has been defined for you
    | here which uses session storage and the Eloquent user provider.
    |
    | All authentication drivers have a user provider. This defines how the
    | users are actually retrieved out of your database or other storage
    | mechanisms used by this application to persist your user's data.
    |
    | Supported: "session", "token"
    |
    */

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

        'api' => [
            'driver' => 'token',
            'provider' => 'users',
        ],
    ],

    /*
    |--------------------------------------------------------------------------
    | User Providers
    |--------------------------------------------------------------------------
    |
    | All authentication drivers have a user provider. This defines how the
    | users are actually retrieved out of your database or other storage
    | mechanisms used by this application to persist your user's data.
    |
    | If you have multiple user tables or models you may configure multiple
    | sources which represent each model / table. These sources may then
    | be assigned to any extra authentication guards you have defined.
    |
    | Supported: "database", "eloquent"
    |
    */

    'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => App\Models\UsersAuth::class,
        ],

        // 'users' => [
        //     'driver' => 'database',
        //     'table' => 'users',
        // ],
    ],

    /*
    |--------------------------------------------------------------------------
    | Resetting Passwords
    |--------------------------------------------------------------------------
    |
    | Here you may set the options for resetting passwords including the view
    | that is your password reset e-mail. You may also set the name of the
    | table that maintains all of the reset tokens for your application.
    |
    | You may specify multiple password reset configurations if you have more
    | than one user table or model in the application and you want to have
    | separate password reset settings based on the specific user types.
    |
    | The expire time is the number of minutes that the reset token should be
    | considered valid. This security feature keeps tokens short-lived so
    | they have less time to be guessed. You may change this as needed.
    |
    */

    'passwords' => [
        'users' => [
            'provider' => 'users',
            'email' => 'auth.emails.password',
            'table' => 'password_resets',
            'expire' => 60,
        ],
    ],

];

UsersAuth.php UsersAuth.php

<?php

namespace App\Models;

use Illuminate\Foundation\Auth\User as Authenticatable;

class UsersAuth extends Authenticatable
{
    /**
    * Users db table.
    *
    * @var string
    */
    protected $table = '002';

    /**
    * URL to redirect after login.
    *
    * @var string
    */
    protected $redirectTo = 'admin/dashboard';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'username', 'email', 'password',
    ];

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];
}

And laravel.log is empty ('debug' => env('APP_DEBUG', true)). 而且laravel.log为空('debug'=> env('APP_DEBUG',true))。

Thanks a lot for helping me. 非常感谢您的帮助。

After two days searching for a solution I think in changing all database columns to default name like id, username, password, etc (before I was using 002_id, 002_username, 002_password, etc...)... After changes everything is working fine. 在寻找解决方案两天后,我想将所有数据库列更改为默认名称,例如id,用户名,密码等(在我使用002_id,002_username,002_password等之前)......更改之后,一切正常。

In Laravel you dosen't have the option to use your custom fields without mod the base Auth class? 在Laravel中,如果不修改基础Auth类,就无法选择使用自定义字段吗? Oo And for what is this errors without information? 哦,这是什么错误而没有信息? Like "TokenMismatchException"... 就像“ TokenMismatchException”一样...

如果您没有进行太多更改,请尝试再次运行php artisan make:auth

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM