“New wheel” PHP CORS (cross origin resource sharing) solves the cross domain requirements of PHP project program setting.

Time:2022-5-9

Yes, everyone who may know about laravel knows that the simple setting of cross domain in laravel is of course a choicebarryvdh/laravel-corsThis bag.

cause

Yes, I’m really building the wheel again and again,barryvdh/laravel-corsThe package implementation is excellent, but it also has many problems. And my new wheelmedz/corsIt is not specifically to solve its problems, but to solve them by the way.medz/corsThe inspiration of the package comes from the company’s project. The company’s project is developed using the laravel framework, and the front end is completely separated. Therefore, it is necessary to set cross domain. Although the traditional nginx setting cross domain is trusted, the advantages of program setting cross domain are self-evident (multiple allowed cross domain domain domain names can be set to dynamically process information).

summary

medz/corsThis package can be used in all PHP projects. You only need some simple configuration. andHere we mainly talk about the application in laravel, because the built-in support temporarily makes a good exclusive treatment for laravel.

Intend to friendly support as follows

  • [x] PHP Native coding.
  • [x] Laravel
  • [x] PSR-7
  • [ ] Symfony
  • [ ] Yii2
  • [ ] Slim Framework

install

thankComposerWe all like it now, so you only need to use it in your project:

composer require medz/cors

Well, you’ve installed it.If you are laravel, now you have added cross domain to your program

Publish profile

function:

php artisan vendor:publish --provider="Medz\Cors\Laravel\Providers\LaravelServiceProvider" --force

If you are interested in the configuration, you can have a lookconfig/cors.phpConfiguration of. However, the following will focus on configuration.

to configure

In order to facilitate some configuration, individualboolintandstringType of configuration can be used.envSet environment variables:

Key describe
CORS_ALLOW_CREDENTIAILS bool, settingAccess-Control-Allow-Credentialsyestruestillfalse
CORS_ACCESS_CONTROL_MAX_AGE int, settingAccess-Control-Max-AgeThe default value is0, i.eclose
CORS_LARAVEL_ALLOW_ROUTE_PERFIX string, the matching rule of route matching pattern is used$request->isCheck, so you can refer torequest, default is*, representing all routes.
CORS_LARAVEL_ROUTE_GROUP_MODE bool, whether to enable the “single routing middleware” or “routing middleware group” mode. It is not enabled by default.

Then all configurations are as follows (it is recommended to have a look)config/cors.phpFile (comments for each configuration):

Key describe
allow-credentiails reference resourcesCORS_ALLOW_CREDENTIAILSto configure
allow-headers List the allowed header fields. The default is['*']For all, you can set, for example'[Content-Type', 'X-Requested-With']Only the above two header fields are allowed, depending on your project. Once it appears*Members, representatives allow all.
expose-headers Lists which headers can be exposed externally as part of the response. Default to[]
origins List the domain names allowed to cross domains. The default is['*'], representative set to*(as long as it appears)*Will be returned in the column*)For example, setting['https://laravel-china.org'], multiple can be set, and the program will process it automatically.
methods Lists the methods that allow cross domain requests. The default is['*']Represents all methods.
max-age Whether the results returned by the pre check request can be cached. The default is0It means that it cannot be cached. The unit is “second”. You can set how long the pre check request results are allowed to be cached.
laravel.allow-route-perfix reference resourcesCORS_LARAVEL_ALLOW_ROUTE_PERFIX
laravel.route-group-mode reference resourcesCORS_LARAVEL_ROUTE_GROUP_MODE

use

In fact, your laravel program relies on thismedz/corsYou can use it directly without any code modification. Because laravel has a magical feature, which is to launchOPTIONSWhen pre checking the request, the only middleware executed is “global middleware”, that isapp/Http/Kernel.phpinprotected $middlewareThe middleware is set, so it is aimed at laravelmedz/corsThe package is automatically added hereMedz\Cors\Laravel\Middleware\CorsMiddleware. You find that if you configure this middleware, it will not perform any other processing.

If you want to customize the execution order of the global middleware, you can manuallyMedz\Cors\Laravel\Middleware\CorsAdd to$middlewareYes.

Routing group mode

This is the solutionbarryvdh/laravel-corsOne of the pain points, becausebarryvdh/laravel-corsCross domain information settings will be added to all routes, which is really not required in practice. What we want is a specific routing group, or a specific route can support cross domain. Other routes cannot make cross domain requests. Therefore, this mode is available in the development of laravel.

The middleware used in group mode is calledMedz\Cors\Laravel\Middleware\ShouldGroup, for ease of use, you canapp/Http/Kernel.phpofprotected $routeMiddlewareGive it a short and memorable alias, for example:

protected $routeMiddleware = [
    'cors-should' => \Medz\Cors\Laravel\Middleware\ShouldGroup::class,
];

I named itcors-shouldNow, you can set cross domain permission in specific routes:

Route::middleware('cors-should')->get('test-cors', function () {});

Of course, you can also use a routing group. Just like the above single routing, please refer to the route document of laravel.

You can also set it directly to the middleware group. In this way, only a certain URI of the middleware group can be written, and cross domains are allowed. For example, the default two routing middleware groups of laravel havewebandapiTwo groups, firstwebThe group is definitely not what we want to cross domain, andapiWe may be completely separated from the front-end and back-end development. The front-end program is not in the domain of the current API server, resulting in cross domain. We can directlyapiGroup settings allowapiGroup cross domain:

protected $middlewareGroups = [
    /// ...
    'web' => [
        // ...
    ],
    'api' => [
        \Medz\Cors\Laravel\Middleware\ShouldGroup::class,
        // ...
    ],
];

Of course, you give it to meMedz\Cors\Laravel\Middleware\ShouldGroup::classIf the route middle price alias is set (for example:chors-should), you can:

protected $middlewareGroups = [
    /// ...
    'web' => [
        // ...
    ],
    'api' => [
        'cors-should',
        // ...
    ],
];

Note that the routing group mode is mixed with the “routing matching mode”

Route matching mode

In “configuration”ENVconstantCORS_LARAVEL_ALLOW_ROUTE_PERFIXOr in the configuration filelaravel.allow-route-perfixYes, this is the route matching mode. The default is*That is, match all.

The matching method of route matching pattern is to use the method in laravelIllumante\Http\Request::isMethod, please refer to the documentLaravel request documentTherefore, the rules set and the laravel request are in questionisThe method requirements are consistent. For example, we hopeapiCross domain routing is enabled only for prefixes: then set to:

api/*

Just, ⚠️ Note that the route matching mode, as mentioned in the “route group mode”, will be matched with the “route group mode”. For the sake of API, we use “routing group mode” to only allowapiThe routing of middleware group allows cross domain, and we set it at the same timeapi/v2/*According to the “route matching pattern” rule, onlyapi/v2/*The route can be, for exampleapi/v1/*AlsoapiFor the routing of middleware group, although the group mode is matched, the rules of “route matching mode” are not matched, soapi/v1/*There is no cross domain permission information for routing.

End

actuallymedz/corsNot only in the laravel project, you can use it in any PHP program, but the package will only have built-in preset support code of several mainstream frameworks, which you can useArrayMode to support all PHP programs.

Forgotten part

For some syntax reasons, this package can only be used in PHP>= 7.0And there will be no syntax compromise for the time being.

information

GitHub address:https://github.com/medz/cors

Well, new wheel, ask for a wave? Star 。