草庐IT

php - 如何防止 Laravel API 处理查询字符串上的参数?

coder 2024-05-05 原文

我想限制我的 Laravel API 在尝试对用户进行身份验证时将参数处理为查询字符串。我一直在尝试使用 POSTMAN,无论是将凭据放在主体上还是作为 url 中的查询字符串,我都能够从我的 API 获取 token 。

根据 Laravel 文档,我认为这是我想要避免的行为:

Retrieving Input Via Dynamic Properties

You may also access user input using dynamic properties on the Illuminate\Http\Request instance. For example, if one of your application's forms contains a name field, you may access the value of the field like so:

$name = $request->name;

When using dynamic properties, Laravel will first look for the parameter's value in the request payload. If it is not present, Laravel will search for the field in the route parameters.

我正在使用 Laravel 5.3PHP 7.1.0

这是使用查询字符串的 POST:

这是在正文中使用参数的 POST:

我已经使用 laravel-cors 配置了我的 CORS :

<?php

return [
   'defaults' => [
       'supportsCredentials' => false,
       'allowedOrigins' => [],
       'allowedHeaders' => [],
       'allowedMethods' => [],
       'exposedHeaders' => [],
       'maxAge' => 0,
       'hosts' => [],
   ],

   'paths' => [
       'v1/*' => [
           'allowedOrigins' => ['*'],
           'allowedHeaders' => ['Accept', 'Content-Type'],
           'allowedMethods' => ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'],
           'exposedHeaders' => ['Authorization'],
           'maxAge' => 3600,
       ],
   ],
];

我的路线(相关路线):

Route::group(
    [
        'domain' => getenv('API_DOMAIN'),
        'middleware' => 'cors',
        'prefix' => '/v1',
        'namespace' => 'V1'
    ],
    function() {
        /* AUTHENTICATION */
        Route::post(
            'signin',
            'AuthenticationController@signin'
        )->name('signin');

        Route::post(
            'signup',
            'AuthenticationController@signup'
        )->name('signup');
    }
);

当列出我的路线时 php artisan route:list 我得到:

------------------------------------------------------------------------------------------------------------------------------------
| Domain    | Method | URI           | Name       | Action                                                            | Middleware |
| localhost | POST   | api/v1/signin | api.signin | App\Http\Controllers\API\V1\AuthenticationController@signin       | api,cors   |
| localhost | POST   | api/v1/signup | api.signup | App\Http\Controllers\API\V1\AuthenticationController@signup       | api,cors   |
------------------------------------------------------------------------------------------------------------------------------------

我的AuthenticationController:

<?php

namespace App\Http\Controllers\API\V1;

use Illuminate\Http\Request;

use App\Http\Controllers\Controller;
use Tymon\JWTAuth\Exceptions\JWTException;
use App\Http\Requests;
use JWTAuth;

class AuthenticationController extends Controller
{
    public function __construct()
    {
        $this->middleware('jwt.auth', ['except' => ['signin', 'signup']]);
    }

    public function signin(Request $request)
    {
        $credentials = $request->only('email', 'password');
        try {
            if (! $token = JWTAuth::attempt($credentials)) {
                return response()->json(
                    [
                        'error' => 'invalid_credentials'
                    ],
                    401
                );
            }
        } catch (JWTException $e) {
            return response()->json(
                [
                    'error' => 'could_not_create_token'
                ],
                500
            );
        }
        return response()->json(compact('token'));
    }

    public function signup(Request $request)
    {
        try {
            $user = User::where(['email' => $request["email"]])->exists();
            if($user)
            {
                return Response::json(
                    array(
                        'msg' => "Email {$request->email} already exists"
                    ),
                    400
                );
            }
            $user = new User;
            $user->create($request->input());
            return Response::json(
                array(
                    'msg' => 'User signed up.'
                )
            );
        } catch (Exception $exception) {
            return Response::json(
                array(
                    'success' => false,
                    'exception' => $exception
                )
            );
        }
    }
}

我的内核:

<?php

namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * These middleware are run during every request to your application.
     *
     * @var array
     */
    protected $middleware = [
        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
        \Barryvdh\Cors\HandleCors::class,
    ];

    /**
     * The application's route middleware groups.
     *
     * @var array
     */
    protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],

        'api' => [
            'throttle:60,1',
            'bindings',
        ],
    ];

    /**
     * The application's route middleware.
     *
     * These middleware may be assigned to groups or used individually.
     *
     * @var array
     */
    protected $routeMiddleware = [
        'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'jwt.auth' => \Tymon\JWTAuth\Middleware\GetUserFromToken::class,
        'jwt.refresh' => \Tymon\JWTAuth\Middleware\RefreshToken::class,
    ];
}

然后我将相应的配置放在 config/app.php 上:

        ...
        /*
         * Package Service Providers...
         */
        Barryvdh\LaravelIdeHelper\IdeHelperServiceProvider::class,
        Collective\Html\HtmlServiceProvider::class,
        Laracasts\Flash\FlashServiceProvider::class,
        Prettus\Repository\Providers\RepositoryServiceProvider::class,
        \InfyOm\Generator\InfyOmGeneratorServiceProvider::class,
        \InfyOm\CoreTemplates\CoreTemplatesServiceProvider::class,

        /*
         * Application Service Providers...
         */
        App\Providers\AppServiceProvider::class,
        // App\Providers\BroadcastServiceProvider::class,
        App\Providers\AuthServiceProvider::class,
        App\Providers\EventServiceProvider::class,
        App\Providers\RouteServiceProvider::class,

        Tymon\JWTAuth\Providers\JWTAuthServiceProvider::class,
        Barryvdh\Cors\ServiceProvider::class,
        Asvae\ApiTester\ServiceProvider::class,
    ],

我不想使用 dingoapi .

我检查了这些资源:

最后但同样重要的是,我的 composer.json:

{
    "name": "laravel/laravel",
    "description": "The Laravel Framework.",
    "keywords": ["framework", "laravel"],
    "license": "MIT",
    "type": "project",
    "require": {
        "php": "^7.1.0",
        "laravel/framework": "5.3.*",
        "barryvdh/laravel-ide-helper": "v2.2.1",
        "laravelcollective/html": "v5.3.0",
        "infyomlabs/laravel-generator": "5.3.x-dev",
        "infyomlabs/core-templates": "5.3.x-dev",
        "infyomlabs/swagger-generator": "dev-master",
        "jlapp/swaggervel": "2.0.x-dev",
        "doctrine/dbal": "2.3.5",
        "league/flysystem-aws-s3-v3": "1.0.13",
        "tymon/jwt-auth": "0.5.9",
        "barryvdh/laravel-cors": "v0.8.2",
        "fzaninotto/faker": "~1.4",
        "caouecs/laravel-lang": "3.0.19",
        "asvae/laravel-api-tester": "^2.0"
    },
    "require-dev": {
        "fzaninotto/faker": "~1.4",
        "mockery/mockery": "0.9.*",
        "phpunit/phpunit": "~5.7",
        "symfony/css-selector": "3.1.*",
        "symfony/dom-crawler": "3.1.*"
    },
    "autoload": {
        "classmap": [
            "database"
        ],
        "psr-4": {
            "App\\": "app/"
        }
    },
    "autoload-dev": {
        "psr-4": {
            "Tests\\": "tests/"
        }
    },
    "scripts": {
        "post-root-package-install": [
            "php -r \"file_exists('.env') || copy('.env.example', '.env');\""
        ],
        "post-create-project-cmd": [
            "php artisan key:generate"
        ],
        "post-install-cmd": [
            "Illuminate\\Foundation\\ComposerScripts::postInstall",
            "php artisan optimize"
        ],
        "post-update-cmd": [
            "Illuminate\\Foundation\\ComposerScripts::postUpdate",
            "php artisan optimize"
        ]
    },
    "config": {
        "preferred-install": "dist"
    }
}

更新

感谢“Basheer Ahmed”给出的答案,他为我指出了正确的方向,我最终做了一个 Trait 来解析我想根据请求获得的 body 属性:

<?php
namespace KeepClear\Traits\Controllers;

trait ApiRequest
{
    /**
     * Parse all attributes and return an array with the present values only.
     *
     * @param array $attributes
     * @param Request $request
     *
     * @return Array
     */
    public function parseBody($attributes, $request)
    {
        $params = [];
        foreach ($attributes as $attribute) {
            $value = $request->request->get($attribute);
            if ($value) {
                $params[$attribute] = $value;
            }
        }
        return $params;
    }
}

此方法将主要用于 createupdate 操作,如下所示,在 AddressController 上:

<?php

namespace KeepClear\Http\Controllers\API\V1;

...

use KeepClear\Traits\Controllers\ApiRequest;

...

class AddressController extends Controller
{
    use ApiRequest;

    /**
     * Instantiate a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('jwt.auth');
    }

    ...

    /**
     * Create address for the specified user.
     *
     * @param Request $request
     * @param String $user_id
     *
     * @return Response
     */
    public function createUserAddress(Request $request, $user_id)
    {
        try {
            $attributes = ['city', 'county_province', 'zip_code'];
            $params = $this->parseBody($attributes, $request);
            User::find($user_id)->addresses()->create($params);
            return Response::json(
                array(
                    'message' => 'The address was successfully created.',
                    'success' => true
                )
            );
        } catch (Exception $exception) {
            return Response::json(
                array(
                    'success' => false,
                    'exception' => $exception
                )
            );
        }
    }

    ...

    /**
     * Update address for the specified user.
     *
     * @param Request $request
     * @param String $user_id
     * @param String $address_id
     *
     * @return Response
     */
    public function updateUserAddress(Request $request, $user_id, $address_id)
    {
        try {
            $attributes = ['city', 'county_province', 'zip_code'];
            $params = $this->parseBody($attributes, $request);
            Address::where(["user_id" => $user_id, "id" => $address_id])
                ->update($params);
            return Response::json(
                array(
                    'message' => 'The address was successfully updated.',
                    'success' => true
                )
            );
        } catch (Exception $exception) {
            return Response::json(
                array(
                    'success' => false,
                    'exception' => $exception
                )
            );
        }
    }
    ...
}

以这种方式并通过使用 $request->request->get('my_param'); 在测试该方法的工作原理后,我可以确定我只获得了 body 。

这是对那些方法的 AddressController 的测试:

<?php

namespace Tests\Api;

use Tests\TestCase;
...
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Faker\Factory;
...

class AddressControllerTest extends TestCase
{
    use ApiTestTrait;
    use DatabaseMigrations;
    use WithoutMiddleware;

    ...
    public function testMethodCreateUserAddress()
    {
        $admin = factory(Role::class, 'admin')->create();
        $user = $admin->users()->save(factory(User::class)->make());
        $uri = 'api/v1/users/' . $user->id . '/addresses';
        $faker = Factory::create();
        $attributes = array(
            'city' => $faker->city,
            'county_province' => $faker->state,
            'zip_code' => $faker->postcode
        );
        $this->json('POST', $uri, $attributes)
            ->seeStatusCode(200)
            ->seeJsonEquals(
                [
                    'message' => 'The address was successfully created.',
                    'success' => true
                ]
            );
    }

    ...

    public function testMethodUpdateUserAddress()
    {
        $admin = factory(Role::class, 'admin')->create();
        $user = $admin->users()->save(factory(User::class)->make());
        $address = $user->addresses()->save(factory(Address::class)->make());
        $uri = 'api/v1/users/' . $user->id . '/addresses/' . $address->id;
        $attributes = array(
            'city' => 'newCity',
            'county_province' => 'newCountyProvince',
            'zip_code' => 'newZipCode'
        );
        $this->json('PUT', $uri, $attributes)
            ->seeStatusCode(200)
            ->seeJsonEquals(
                [
                    'message' => 'The address was successfully updated.',
                    'success' => true
                ]
            );
        $updated_address = Address::find($address->id);
        $this->assertEquals($updated_address->city, 'newCity');
        $this->assertEquals(
            $updated_address->county_province,
            'newCountyProvince'
        );
        $this->assertEquals($updated_address->zip_code, 'newZipCode');
    }
    ...
}

最佳答案

任何附加到 url 栏的内容都被视为获取请求,并且可以通过 $_GET super 全局变量获得。我假设 laravel Request 请求将合并 post 和 get 请求,然后当您尝试调用通过 get 或 post 发送的任何参数时,您可以通过

$request->myparam

但如果你只是尝试

$request->request->get('my_param');

你不会得到类似的结果。

:)

关于php - 如何防止 Laravel API 处理查询字符串上的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42894124/

有关php - 如何防止 Laravel API 处理查询字符串上的参数?的更多相关文章

  1. ruby - 如何使用 Nokogiri 的 xpath 和 at_xpath 方法 - 2

    我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div

  2. ruby - 如何从 ruby​​ 中的字符串运行任意对象方法? - 2

    总的来说,我对ruby​​还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用

  3. Ruby 解析字符串 - 2

    我有一个字符串input="maybe(thisis|thatwas)some((nice|ugly)(day|night)|(strange(weather|time)))"Ruby中解析该字符串的最佳方法是什么?我的意思是脚本应该能够像这样构建句子:maybethisissomeuglynightmaybethatwassomenicenightmaybethiswassomestrangetime等等,你明白了......我应该一个字符一个字符地读取字符串并构建一个带有堆栈的状态机来存储括号值以供以后计算,还是有更好的方法?也许为此目的准备了一个开箱即用的库?

  4. ruby-on-rails - 在 Rails 中将文件大小字符串转换为等效千字节 - 2

    我的目标是转换表单输入,例如“100兆字节”或“1GB”,并将其转换为我可以存储在数据库中的文件大小(以千字节为单位)。目前,我有这个:defquota_convert@regex=/([0-9]+)(.*)s/@sizes=%w{kilobytemegabytegigabyte}m=self.quota.match(@regex)if@sizes.include?m[2]eval("self.quota=#{m[1]}.#{m[2]}")endend这有效,但前提是输入是倍数(“gigabytes”,而不是“gigabyte”)并且由于使用了eval看起来疯狂不安全。所以,功能正常,

  5. ruby-on-rails - unicode 字符串的长度 - 2

    在我的Rails(2.3,Ruby1.8.7)应用程序中,我需要将字符串截断到一定长度。该字符串是unicode,在控制台中运行测试时,例如'א'.length,我意识到返回了双倍长度。我想要一个与编码无关的长度,以便对unicode字符串或latin1编码字符串进行相同的截断。我已经了解了Ruby的大部分unicode资料,但仍然有些一头雾水。应该如何解决这个问题? 最佳答案 Rails有一个返回多字节字符的mb_chars方法。试试unicode_string.mb_chars.slice(0,50)

  6. python - 如何使用 Ruby 或 Python 创建一系列高音调和低音调的蜂鸣声? - 2

    关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。

  7. ruby-on-rails - 如何验证 update_all 是否实际在 Rails 中更新 - 2

    给定这段代码defcreate@upgrades=User.update_all(["role=?","upgraded"],:id=>params[:upgrade])redirect_toadmin_upgrades_path,:notice=>"Successfullyupgradeduser."end我如何在该操作中实际验证它们是否已保存或未重定向到适当的页面和消息? 最佳答案 在Rails3中,update_all不返回任何有意义的信息,除了已更新的记录数(这可能取决于您的DBMS是否返回该信息)。http://ar.ru

  8. ruby-on-rails - 'compass watch' 是如何工作的/它是如何与 rails 一起使用的 - 2

    我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t

  9. ruby - 将差异补丁应用于字符串/文件 - 2

    对于具有离线功能的智能手机应用程序,我正在为Xml文件创建单向文本同步。我希望我的服务器将增量/差异(例如GNU差异补丁)发送到目标设备。这是计划:Time=0Server:hasversion_1ofXmlfile(~800kiB)Client:hasversion_1ofXmlfile(~800kiB)Time=1Server:hasversion_1andversion_2ofXmlfile(each~800kiB)computesdeltaoftheseversions(=patch)(~10kiB)sendspatchtoClient(~10kiBtransferred)Cl

  10. ruby - ECONNRESET (Whois::ConnectionError) - 尝试在 Ruby 中查询 Whois 时出错 - 2

    我正在用Ruby编写一个简单的程序来检查域列表是否被占用。基本上它循环遍历列表,并使用以下函数进行检查。require'rubygems'require'whois'defcheck_domain(domain)c=Whois::Client.newc.query("google.com").available?end程序不断出错(即使我在google.com中进行硬编码),并打印以下消息。鉴于该程序非常简单,我已经没有什么想法了-有什么建议吗?/Library/Ruby/Gems/1.8/gems/whois-2.0.2/lib/whois/server/adapters/base.

随机推荐