簡體   English   中英

Laravel 5.1管理員路由認證

[英]Laravel 5.1 Authentication for admin route

我是Laravel的新手,並且想要建立一個小的管理區域來創建和編輯數據。 我正在使用Laravel 5.1開箱即用的身份驗證,並遵循此文檔http://laravel.com/docs/master/authentication

我為所有后端路由添加了“ admin”前綴。 現在,如果我登錄,我將被重定向到正確的頁面。 但是,一旦我單擊一個鏈接或重新加載頁面,我就會被重定向到我的登錄頁面。

我想我的路線有問題...?

附加信息:

  • Laravel Framework版本5.1.17(LTS)
  • 我正在使用無業游民作為我的開發環境。 這是一個自定義框。 但是我已經嘗試過使用帶有此文件庫的Homestead,同樣的問題。
  • 沒有auth中間件,我的所有路由都可以訪問並且運行正常。

routes.php文件

// Frontend
Route::get('/', ['as' => 'home', 'uses' => 'ContentController@index']);
Route::resource('comment', 'CommentController', ['only' => ['create','store']]);

// Authentication
Route::get('admin/login', array('as' => 'admin.login', 'uses' => 'Auth\AuthController@getLogin'));
Route::post('admin/login', array('as' => 'admin.login', 'uses' => 'Auth\AuthController@postLogin'));
Route::get('admin/logout', array('as' => 'admin.logout', 'uses' => 'Auth\AuthController@getLogout'));

// Backend Admin with Authentication
Route::group(array('prefix' => 'admin', 'middleware' => 'auth', 'namespace' => 'Admin'), function()
{
    Route::post('content/sortlist', ['as' => 'admin.content.sortlist', 'uses' => 'ContentController@sortList']);
    Route::resource('content', 'ContentController', ['except' => ['show']]);
    Route::resource('comment', 'CommentController', ['only' => ['index','destroy']]);
});

PHP Artisan route:list的輸出

+--------+----------+------------------------------+------------------------+-------------------------------------------------------+------------+
| Domain | Method   | URI                          | Name                   | Action                                                | Middleware |
+--------+----------+------------------------------+------------------------+-------------------------------------------------------+------------+
|        | GET|HEAD | /                            | home                   | App\Http\Controllers\ContentController@index          |            |
|        | GET|HEAD | admin/comment                | admin.comment.index    | App\Http\Controllers\Admin\CommentController@index    | auth       |
|        | DELETE   | admin/comment/{comment}      | admin.comment.destroy  | App\Http\Controllers\Admin\CommentController@destroy  | auth       |
|        | POST     | admin/content                | admin.content.store    | App\Http\Controllers\Admin\ContentController@store    | auth       |
|        | GET|HEAD | admin/content                | admin.content.index    | App\Http\Controllers\Admin\ContentController@index    | auth       |
|        | GET|HEAD | admin/content/create         | admin.content.create   | App\Http\Controllers\Admin\ContentController@create   | auth       |
|        | POST     | admin/content/sortlist       | admin.content.sortlist | App\Http\Controllers\Admin\ContentController@sortList | auth       |
|        | PATCH    | admin/content/{content}      |                        | App\Http\Controllers\Admin\ContentController@update   | auth       |
|        | DELETE   | admin/content/{content}      | admin.content.destroy  | App\Http\Controllers\Admin\ContentController@destroy  | auth       |
|        | PUT      | admin/content/{content}      | admin.content.update   | App\Http\Controllers\Admin\ContentController@update   | auth       |
|        | GET|HEAD | admin/content/{content}/edit | admin.content.edit     | App\Http\Controllers\Admin\ContentController@edit     | auth       |
|        | GET|HEAD | admin/login                  | admin.login            | App\Http\Controllers\Auth\AuthController@getLogin     | guest      |
|        | POST     | admin/login                  | admin.login            | App\Http\Controllers\Auth\AuthController@postLogin    | guest      |
|        | GET|HEAD | admin/logout                 | admin.logout           | App\Http\Controllers\Auth\AuthController@getLogout    |            |
|        | POST     | comment                      | comment.store          | App\Http\Controllers\CommentController@store          |            |
|        | GET|HEAD | comment/create               | comment.create         | App\Http\Controllers\CommentController@create         |            |
+--------+----------+------------------------------+------------------------+-------------------------------------------------------+------------+

應用程序/ HTTP /控制器/認證/ AuthController.php

<?php

namespace App\Http\Controllers\Auth;

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

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;

    protected $redirectPath = 'admin/content';

    protected $loginPath = 'admin/login';

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

    /**
     * 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, [
            'firstname' => 'required|max:255',
            'lastname' => 'required|max:255',
            'email' => 'required|email|max:255|unique:users',
            'password' => 'required|confirmed|min:6',
        ]);
    }

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

應用程序/ HTTP /中間件/ Authenticate.php

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Contracts\Auth\Guard;

class Authenticate
{
    /**
     * The Guard implementation.
     *
     * @var Guard
     */
    protected $auth;

    /**
     * Create a new filter instance.
     *
     * @param  Guard  $auth
     * @return void
     */
    public function __construct(Guard $auth)
    {
        $this->auth = $auth;
    }

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if ($this->auth->guest()) {
            if ($request->ajax()) {
                return response('Unauthorized.', 401);
            } else {
                return redirect()->guest('admin/login');
            }
        }

        return $next($request);
    }
}

應用程序/ HTTP /中間件/ RedirectIfAuthenticated.php

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Contracts\Auth\Guard;

class RedirectIfAuthenticated
{
    /**
     * The Guard implementation.
     *
     * @var Guard
     */
    protected $auth;

    /**
     * Create a new filter instance.
     *
     * @param  Guard  $auth
     * @return void
     */
    public function __construct(Guard $auth)
    {
        $this->auth = $auth;
    }

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if ($this->auth->check()) {
            return redirect('admin/content');
        }

        return $next($request);
    }
}

在供應商/laravel/framework/src/Illuminate/Foundation/Auth/AuthenticatesUsers.php上的postLogin(此處未更改)

<?php

namespace Illuminate\Foundation\Auth;

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

trait AuthenticatesUsers
{
    use RedirectsUsers;

    /**
     * Show the application login form.
     *
     * @return \Illuminate\Http\Response
     */
    public function getLogin()
    {
        if (view()->exists('auth.authenticate')) {
            return view('auth.authenticate');
        }

        return view('auth.login');
    }

    /**
     * Handle a login request to the application.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function postLogin(Request $request)
    {
        $this->validate($request, [
            $this->loginUsername() => 'required', 'password' => 'required',
        ]);

        // If the class is using the ThrottlesLogins trait, we can automatically throttle
        // the login attempts for this application. We'll key this by the username and
        // the IP address of the client making these requests into this application.
        $throttles = $this->isUsingThrottlesLoginsTrait();

        if ($throttles && $this->hasTooManyLoginAttempts($request)) {
            return $this->sendLockoutResponse($request);
        }

        $credentials = $this->getCredentials($request);

        if (Auth::attempt($credentials, $request->has('remember'))) {
            return $this->handleUserWasAuthenticated($request, $throttles);
        }

        // If the login attempt was unsuccessful we will increment the number of attempts
        // to login and redirect the user back to the login form. Of course, when this
        // user surpasses their maximum number of attempts they will get locked out.
        if ($throttles) {
            $this->incrementLoginAttempts($request);
        }

        return redirect($this->loginPath())
            ->withInput($request->only($this->loginUsername(), 'remember'))
            ->withErrors([
                $this->loginUsername() => $this->getFailedLoginMessage(),
            ]);
    }

    /**
     * Send the response after the user was authenticated.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  bool  $throttles
     * @return \Illuminate\Http\Response
     */
    protected function handleUserWasAuthenticated(Request $request, $throttles)
    {
        if ($throttles) {
            $this->clearLoginAttempts($request);
        }

        if (method_exists($this, 'authenticated')) {
            return $this->authenticated($request, Auth::user());
        }

        return redirect()->intended($this->redirectPath());
    }

    /**
     * Get the needed authorization credentials from the request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    protected function getCredentials(Request $request)
    {
        return $request->only($this->loginUsername(), 'password');
    }

    /**
     * Get the failed login message.
     *
     * @return string
     */
    protected function getFailedLoginMessage()
    {
        return Lang::has('auth.failed')
                ? Lang::get('auth.failed')
                : 'These credentials do not match our records.';
    }

    /**
     * Log the user out of the application.
     *
     * @return \Illuminate\Http\Response
     */
    public function getLogout()
    {
        Auth::logout();

        return redirect(property_exists($this, 'redirectAfterLogout') ? $this->redirectAfterLogout : '/');
    }

    /**
     * Get the path to the login route.
     *
     * @return string
     */
    public function loginPath()
    {
        return property_exists($this, 'loginPath') ? $this->loginPath : '/auth/login';
    }

    /**
     * Get the login username to be used by the controller.
     *
     * @return string
     */
    public function loginUsername()
    {
        return property_exists($this, 'username') ? $this->username : 'email';
    }

    /**
     * Determine if the class is using the ThrottlesLogins trait.
     *
     * @return bool
     */
    protected function isUsingThrottlesLoginsTrait()
    {
        return in_array(
            ThrottlesLogins::class, class_uses_recursive(get_class($this))
        );
    }
}

我如何鏈接到master.admin刀片文件中的管理頁面(也許是罪魁禍首?)

<ul class="nav nav-sidebar">
<li {{ Request::is('admin/content') ? "class=active" : null }}><a href="{{ URL::route('admin.content.index') }}">Inhalte <span class="sr-only">(current)</span></a></li>
<li {{ Request::is('admin/comment') ? "class=active" : null }}><a href="{{ URL::route('admin.comment.index') }}">Kommentare <span class="sr-only">(current)</span></a></li>
</ul>

跟隨無數的Google鏈接,我已經檢查了storage / framework / sessions目錄權限,並檢查了會話是否持久。 在我看來如此。 我在config / session.php中從基於文件的會話切換到數據庫會話,一點都沒有改變。 laravel.log文件中也沒有任何內容。

我盡力了。 可能只是我沒有得到的某些配置。

謝謝你的幫助!

找到了解決方案。 我偶然發現了關於身份驗證的stackoverflow上的另一個問題,並發現了問題。

我用了

<li><a href="{{ Auth::logout() }}">Logout</a></li>

在我的刀片模板中注銷。 只要存在,就會出現上述行為。 我將其替換為以下內容

<li><a href="{{ URL::to('admin/logout') }}">Logout</a></li>

現在一切都按預期進行! 我仍然想知道為什么會這樣...但是也許這會幫助別人!

暫無
暫無

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

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