Laravel 5.4:如何保护API路由 [英] Laravel 5.4: how to protect api routes

查看:209
本文介绍了Laravel 5.4:如何保护API路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个react应用,它从laravel api中获取数据,就像在route/api.php中这样定义:

I have a react app that fetch datas from laravel api defined like so in routes/api.php:

// this is default route provided by laravel out of the box
Route::middleware('auth:api')->get('/user', function (Request $request) {
            return $request->user();
        });

// ItemController provides an index methods that list items with json
Route::resource('items', 'Api\ItemController', array('except' => array('create','edit')));

// this is to store new users
Route::resource('users', 'Api\UserController', array('only' => array('store')));

例如 http://example.com/api/items 返回预期的数据,但这真的是不安全的,因为任何人都可以通过邮递员访问它.

for example http://example.com/api/items returns the data as intended but it's really insecure since anyone could access it through postman.

如何使这些路由仅在应用程序内部可用?

由于我是新手,所以我不知道是否需要设置api_token以及如何设置?

As I'm new to it I don't understand if I need to set up api_token and how?

我需要设置护照吗?

与auth:api中间件有关吗?

Is is related to auth:api middleware?

这听起来确实很基础,但是任何帮助或教程建议将不胜感激

It may sounds really basic but any help or tutorial suggestions would be greatly appreciated

以经典的会话身份验证结束.在web.php中移动了路线.在ajax请求中传递csrf令牌.实际上,我不需要RESTful API.仅当您的API为无状态时,才需要令牌身份验证.

End up with a classic session auth. Moved routes inside web.php. Pass csrf token in ajax request. Actually i didn't need a RESTful API. You only need token auth when your API is stateless.

推荐答案

您可以使用 JWT 使它正常工作很容易.您基本上是通过请求用户名/密码并在需要身份验证的每个请求中传递该令牌来生成令牌的,您的URL看起来像 http://example.com/api/items?token=SOME-TOKEN .没有适当的令牌,他将无权执行此端点.

You could use JWT it's pretty easy to get it to work. You basically generate a token by requesting Username/Password and passing that token in every request that requires authentication, your URL would look like http://example.com/api/items?token=SOME-TOKEN. without a proper token, he doesn't have access do this endpoint.

如何使这些路线只能在应用程序内部访问?

How to make those routes only accessible inside the app?

如果您的意思是只有您的应用可以使用这些请求,则不能.基本上,API不知道谁在发送这些请求,他只能检查您提供的内容是否正确,并在一切正常的情况下继续进行操作.我建议您看看

If you mean only your app can use these requests, you can't. Basically the API doesn't know who is sending these requests, he can only check if what you are giving is correct and proceed with it if everything is in order. I'd suggest you to have a look at this question

这篇关于Laravel 5.4:如何保护API路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆