簡體   English   中英

Laravel 5.2 Auth登錄有效,Auth :: check失敗

[英]Laravel 5.2 Auth login works, Auth::check fails

我知道這是laravel 5.2的常見問題,但是我一直在搜索數小時,無法弄清這一點。

目前,我想通過登錄表單進行簡單的身份驗證。 我正在使用一個附加到laravel AuthController的自定義數據庫。 我有一個表單發布到auth / login並正確驗證,因為它重定向回所需的路由,即主頁。 但是,當我嘗試在該路由上調用Auth :: check()時,它總是返回false,就像未定義一樣。 現在,我完全意識到必須為路由使用“網絡”中間件來保存會話數據。 我已經嘗試過,如此處所示, Laravel 5.2 Auth not Working ,可悲的是沒有為我修復它。 然后,我意識到我正在使用laravel的5.2.32版本,這意味着我什至不需要定義“網絡”中間件,因為默認情況下,它已通過5.2.27版使用,因為一旦網絡就可以接收錯誤消息中間件已刪除。

這個問題整天困擾着我,身份驗證完全通過並重定向。 但是,一旦我重定向,Auth就無法使用。 如果我至少能對這段代碼有新的了解,將不勝感激。

****** routes.php ********************************

// Route::group not necessary after version 5.2.27 of laravel on by default, simply here for display purposes.
Route::group(['middleware' => 'web'], function () {

    Route::get('/', function(){

        if(Auth::check()){
            echo "logged in";
        }

    return view('pages.home');
    }); 


    Route::get('channels/{channel}', function($channel) 
    {     
        return view('pages.channels', ['channel' => $channel] );
    });
    Route::get('events', function() 
    {    
        return view('pages.events');
    });
    Route::get('news', function() 
    {    
        return view('pages.news');
    });
    Route::get('contact', function() 
    {    
        return view('pages.contact');
    });

    // Login Form routes
    Route::get('login', function(){

        return view('pages.login');

    });

    // Just Get login working, instead of using Route::auth()
    Route::post('auth/login', 'Auth\AuthController@login');
});

***** login.blade.php ******************************我的表格

@extends('layouts.master')

@section('content')
<div class="text-center col-md-4 col-md-offset-4">
    <h1>Login</h1>

    <ul>
        @foreach($errors->all() as $error)
            <li>{{ $error }}</li>
        @endforeach
    </ul>

    {!! Form::open(array('url' => '/auth/login', 'class' => 'form')) !!}

    <div class="form-group">
        {!! Form::label('Username') !!}
        {!! Form::text('username', null, 
            array('required', 
                  'class'=>'form-control', 
                  'placeholder'=>'Your username')) !!}
    </div>

    <div class="form-group">
        {!! Form::label('Password') !!}
        {!! Form::text('password', null, 
            array('required', 
                  'class'=>'form-control', 
                  'placeholder'=>'Your password')) !!}
    </div>

    <div class="form-group">
        {!! Form::submit('Login', 
          array('class'=>'btn btn-primary')) !!}
    </div>
    {!! Form::close() !!}
    <div>
        Don't have an account? <a href="">Sign up.</a>
    </div>
</div>

@endsection

******* New_Client.php **********************自定義數據庫模型

namespace App;

// http://laravel-recipes.com/recipes/11/changing-your-authentication-model
// model change to https://laravel.com/docs/5.0/upgrade

use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Authenticatable;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Foundation\Auth\Access\Authorizable;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;

class New_Client extends Model implements AuthenticatableContract, AuthorizableContract, CanResetPasswordContract
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'new_client';

    /*Turn off timestamps, as we do not have them*/
    public $timestamps = false;

    use Authenticatable, Authorizable, CanResetPassword;
}

*注意,我已經在提供程序->用戶->模型下的config / auth.php中附加了此模型

最后是AuthController.php本身,它的默認默認控件是laravel打包的。 但是,只會更改loginPath,redirectPath和username變量。

<?php

namespace App\Http\Controllers\Auth;

use App\New_Client;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;

// temp

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class AuthController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Registration & Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users, as well as the
    | authentication of existing users. By default, this controller uses
    | a simple trait to add these behaviors. Why don't you explore it?
    |
    */

    use AuthenticatesAndRegistersUsers, ThrottlesLogins;

    /**
     * Where to redirect users after login / registration.
     *
     * @var string
     */
    protected $redirectTo = '/';

    /**
    * Redirect user after failed login
    */
    protected $loginPath = '/login';

    // Override email required field with this 
    //https://stackoverflow.com/questions/28584531/modify-existing-authorization-module-email-to-username
    protected $username = 'username';

    /**
     * Create a new authentication controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware($this->guestMiddleware(), ['except' => 'logout']);
    }

    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array  $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    protected function validator(array $data)
    {
        return Validator::make($data, [
            'username' => 'required|max:255',
            'password' => 'required|min:6',
        ]);
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return User
     */
    protected function create(array $data)
    {
        return User::create([
            'username' => $data['name'],
            'password' => bcrypt($data['password']),
        ]);
    }
}

*這是完全不相關的,但我還刪除了行return $ this-> hasher-> check($ plain,$ user-> getAuthPassword()); 並將其替換為return($ plain == $ user-> getAuthPassword()); 在EloquentUserProvider.php中,因為目前我的密碼尚未進行哈希處理,一旦測試完成,密碼將被退回。 我知道這不會影響當前的問題,但是我知道為什么我不能在路由中引用Auth

編輯:這是我們要進行身份驗證的數據庫。 我們有用戶名,密碼,甚至還有文檔https://laravel.com/docs/5.2/authentication#introduction-database-considerations中指示的Remember_token

CREATE TABLE `new_client` (
  `client_idx_NW` int(11) NOT NULL,
  `ID` int(11) NOT NULL DEFAULT '450',
  `username` varchar(60) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
  `password` varchar(100) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
  `first_name` varchar(20) NOT NULL DEFAULT 'John',
  `surname_name` varchar(20) NOT NULL DEFAULT 'Smith',
  `organization_name` varchar(20) NOT NULL DEFAULT 'Sony',
  `phone_number` varchar(20) NOT NULL DEFAULT '6476231234',
  `address_street` varchar(256) NOT NULL DEFAULT '230-140 Cresent Road',
  `city` varchar(20) NOT NULL DEFAULT 'Burlington',
  `province` varchar(20) NOT NULL DEFAULT 'Ontario',
  `country` varchar(20) NOT NULL DEFAULT 'Canada',
  `postal_code` varchar(20) NOT NULL DEFAULT 'l7l4C3',
  `email_address` varchar(20) NOT NULL DEFAULT 'JohnSmith@sony.ca',
  `credit_card_number` varchar(20) NOT NULL,
  `expiry_date` date NOT NULL,
  `security_code` varchar(20) NOT NULL,
  `accepted` tinyint(1) NOT NULL,
  `remember_token` varchar(100) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

問候

所以我最終想出了解決方案,我只是希望這不會被否決。 但是,哦,好了,在我的模型上,我從未指出過主鍵,因此在檢索用戶時這是不可能的。

要為我修復,只需要此行

 protected $primaryKey = 'client_idx_NW';

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM