防止用户未经授权访问网页

时间:2018-10-27 15:40:53

标签: php laravel laravel-5

如何防止用户通过URL浏览访问我的网页。我的意思是我需要在访问任何网页之前检查用户是否已登录。该应用程序不应仅通过url允许用户访问该页面。

我是否必须在每个控制器中签入身份验证,否则还有其他方法吗?

假设我有一个控制器DistributorController。现在,这些控制器内部的方法是

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Session;
use App\Distributor;

class DistributorController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
    }

    function fetchData()
    {
        $distributors = Distributor::all()->toArray();
        return compact('distributors');
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('pages.distributors', $this->fetchData());
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        try{
            // code block
        }
        catch (\Exception $e) {
            // code block
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}

2 个答案:

答案 0 :(得分:1)

web.php文件中,您可以在其中定义路线,可以使用Auth中间件对路线进行分组并包围它们。您可以阅读更多here

答案 1 :(得分:0)

我认为您可以例如检查用户会话

if (!$_SESSION['id']){              // if user session is not found
                     header("location:http://yoursite.index.php"); //redirect anywhere
       }
  else { 
           // Your code 'view page'  
       }

希望我的答案能解决它:)

相关问题