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



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

我必须检查每个控制器以进行身份验证,还是有其他方法?

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

<?php
namespace AppHttpControllers;
use IlluminateHttpRequest;
use Session;
use AppDistributor;
class DistributorController extends Controller
{
/**
* Display a listing of the resource.
*
* @return IlluminateHttpResponse
*/
public function index()
{
//
}
function fetchData()
{
$distributors = Distributor::all()->toArray();
return compact('distributors');
}
/**
* Show the form for creating a new resource.
*
* @return IlluminateHttpResponse
*/
public function create()
{
return view('pages.distributors', $this->fetchData());
}
/**
* Store a newly created resource in storage.
*
* @param  IlluminateHttpRequest  $request
* @return IlluminateHttpResponse
*/
public function store(Request $request)
{
try{
// code block
}
catch (Exception $e) {
// code block
}
}
/**
* Display the specified resource.
*
* @param  int  $id
* @return IlluminateHttpResponse
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param  int  $id
* @return IlluminateHttpResponse
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* @param  IlluminateHttpRequest  $request
* @param  int  $id
* @return IlluminateHttpResponse
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param  int  $id
* @return IlluminateHttpResponse
*/
public function destroy($id)
{
//
}
}

在定义路由的web.php文件中,可以使用Auth中间件对路由进行分组和环绕。你可以在这里阅读更多

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

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

希望我的答案能解决这个问题:(

最新更新