CSRF token mismatch in L5 swagger apis - laravel

I am creating documentation for my laravel project but on Post request in swagger I am getting csrf mismatch.
/**
* #OA\Post(
* path="/api/admin/login",
* tags={"auth"},
* summary="Logs user into system",
* #OA\Parameter(
* name="email",
* in="query",
* description="The user name for login",
* required=true,
* #OA\Schema(
* type="string"
* )
* ),
* #OA\Parameter(
* name="password",
* in="query",
* required=true,
* #OA\Schema(
* type="string",
* )
* ),
* #OA\Response(
* response=200,
* description="successful operation",
* #OA\Header(
* header="X-Rate-Limit",
* description="calls per hour allowed by the user",
* #OA\Schema(
* type="integer",
* format="int32"
* )
* ),
* #OA\Header(
* header="X-Expires-After",
* description="date in UTC when token expires",
* #OA\Schema(
* type="string",
* format="datetime"
* )
* ),
* #OA\JsonContent(
* type="string"
* )
* ),
* #OA\Response(
* response=400,
* description="Invalid username/password supplied"
* )
* )
*/
I have tried to find a useful solution but unable to find the issue. When I try to post req in swagger link it give me error
"message": "CSRF token mismatch.",
"exception": "Symfony\Component\HttpKernel\Exception\HttpException",
"file": "/Users/apple/Applications/locum-app/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php",
"line": 383,

Related

How to combine a property and json response in Laravel + Swagger?

I have this a project that is using Laravel for the api and swagger for documentation
I have this method in my login controller:
/**
* Handle an incoming authentication request.
*
*
* #OA\Post(
* tags={"UnAuthorize"},
* path="/login",
* summary="User Login",
* #OA\RequestBody(
* #OA\MediaType(
* mediaType="application/json",
* #OA\Schema(
* type="object",
* ref="#/components/schemas/LoginRequest",
* )
* )
* ),
* #OA\Response(
* response="200",
* description="An example resource",
* #OA\JsonContent(
* type="object",
* #OA\Property(
* format="string",
* default="20d338931e8d6bd9466edeba78ea7dce7c7bc01aa5cc5b4735691c50a2fe3228",
* description="token",
* property="token"
* )
* ),
* #OA\JsonContent(ref="#/components/schemas/UserResource")
* ),
* #OA\Response(response="401", description="fail"),
* )
*
* #param \App\Http\Requests\Auth\LoginRequest $request
* #return \Illuminate\Http\JsonResponse
*/
public function store(LoginRequest $request)
{
$request->authenticate();
return response()->json(
[
"token" => $request->user()->createToken($request->email)->plainTextToken,
"user" => $request->user();
]
);
}
then, when I run this command: php artisan l5-swagger:generate ,it displays this error:
c:\myproject\vendor\zircote\swagger-php\src\Logger.php:40
36▕ $this->log = function ($entry, $type) {
37▕ if ($entry instanceof Exception) {
38▕ $entry = $entry->getMessage();
39▕ } ➜ 40▕ trigger_error($entry, $type);
41▕ };
42▕ }
When I remove this
#OA\JsonContent(ref="#/components/schemas/UserResource")
it works, but the user data is not displayed, maybe I should only return the token, and make another request with the token to get the information about the logged user. What can I do?, thanks
EDIT:
#OA\Response(
* response="200",
* description="An example resource",
* #OA\JsonContent(
* type="object",
* #OA\Property(
* format="string",
* default="20d338931e8d6bd9466edeba78ea7dce7c7bc01aa5cc5b4735691c50a2fe3228",
* description="token",
* property="token"
* ),
* #OA\Property(
* format="application/json",
* property="user",
* #OA\JsonContent(ref="#/components/schemas/UserResource")
* )
* ),
* )
I tried this, but it shows errors
Pretty close except...
use of 'format' instead of 'type'
you do not have to specify the content type if your property is already wrapped in #OA\JsonContent
you need to be careful with surplus trailing ','; doctrine can be picky with that
Here is my take which does work stand-alone (except for the missing #OA\Info):
<?php
use OpenApi\Annotations\OpenApi as OA;
/**
* #OA\Schema
*/
class LoginRequest{}
/**
* #OA\Schema
*/
class UserResource{}
/**
* Handle an incoming authentication request.
*
*
* #OA\Post(
* tags={"UnAuthorize"},
* path="/login",
* summary="User Login",
* #OA\RequestBody(
* #OA\MediaType(
* mediaType="application/json",
* #OA\Schema(
* type="object",
* ref="#/components/schemas/LoginRequest"
* )
* )
* ),
* #OA\Response(
* response="200",
* description="An example resource",
* #OA\JsonContent(
* type="object",
* #OA\Property(
* type="string",
* default="20d338931e8d6bd9466edeba78ea7dce7c7bc01aa5cc5b4735691c50a2fe3228",
* description="token",
* property="token"
* ),
* #OA\Property(
* property="user",
* ref="#/components/schemas/UserResource"
* )
* )
* ),
* #OA\Response(response="401", description="fail")
* )
*
*/
class Controller {}
The JsonContent you removed should be a property on the first JsonContent I think

Origin header is not working in L5 Swagger - Laravel

I am using "darkaonline/l5-swagger" version 8.0 laravel(v 8.12) package for api documentation. My PHP version is 8.0.2. I created api annotation for GET and POST request. The post request automatically send "Origin" header. The Get method is not sending "Origin" header by default.
Package link: https://github.com/DarkaOnLine/L5-Swagger
I need two things for this:
I want to change the default value of "Origin" header of POST request
I want to add custom "Origin" header in GET request
Below is my sample POST request
/**
* #OA\Post(
* path="/auth/login",
* summary="Login",
* description="This api will be used for login of all roles",
* operationId="authLogin",
* tags={"auth"},
* #OA\Parameter(
* name="Origin",
* in="header",
* description="Origin",
* required=true,
* example="http://example.com",
* schema={
* "type"="string"
* },
* style="simple",
* ),
* #OA\RequestBody(
* required=true,
* description="Pass user credentials",
* #OA\JsonContent(
* required={"email","password"},
* #OA\Property(property="email", type="string", format="email", example="user1#mail.com"),
* #OA\Property(property="password", type="string", format="password", example="PassWord12345"),
* ),
* ),
* #OA\Response(
* response=422,
* description="Wrong credentials response",
* #OA\JsonContent(
* #OA\Property(property="error",
* type="object",
* #OA\Property(property="message",
* type="string",
* example="Email required"
* ),
* #OA\Property(property="field",
* type="string",
* example="email"
* )
* ),
* ),
* ),
* #OA\Response(
* response=200,
* description="Login success",
* #OA\JsonContent(
* #OA\Property(property="data",
* type="object",
* #OA\Property(property="status", type="boolean", example=true),
* ),
* ),
* )
* )
*/
Below is my sample GET request
/**
* #OA\Get(
* path="/school-courses",
* summary="Get school courses",
* description="This api will be used to get all course of school",
* operationId="getSchoolCourse",
* tags={"frontend"},
* #OA\Parameter(
* name="Origin",
* in="header",
* description="Origin",
* required=true,
* example="http://example.com",
* schema={
* "type"="string"
* },
* style="simple",
* ),
* #OA\Response(
* response=200,
* description="Success",
* #OA\JsonContent(
* #OA\Items(
* #OA\Property(property="id", type="integer", example=1),
* #OA\Property(property="price", type="integer", example=29),
* #OA\Property(property="teacher_id", type="integer", example=null),
* #OA\Property(property="category_id", type="integer", example=null),
* #OA\Property(property="program_id", type="integer", example=null),
* #OA\Property(property="locale_id", type="integer", example=7),
* #OA\Property(property="status_id", type="integer", example=null),
* #OA\Property(property="level", type="integer", example=null),
* #OA\Property(property="created_by", type="integer", example=null),
* #OA\Property(property="lessons", type="integer", example=10),
* #OA\Property(property="created_at", type="string", example="2021-03-31T23:20:09.000000Z"),
* #OA\Property(property="updated_at", type="string", example="2021-03-31T23:20:09.000000Z"),
* #OA\Property(property="currency", type="object",
* #OA\Property(property="id", type="integer", example=1),
* #OA\Property(property="symbol", type="string", example="KZT"),
* #OA\Property(property="name", type="string", example="Kazakhstani Tenge"),
* #OA\Property(property="symbol_native", type="string", example="тңг."),
* #OA\Property(property="decimal_digits", type="integer", example=2),
* #OA\Property(property="rounding", type="integer", example=0),
* #OA\Property(property="code", type="string", example="KZT"),
* #OA\Property(property="name_plural", type="string", example="Kazakhstani Tenge"),
* #OA\Property(property="created_at", type="string", example="2021-03-31T23:20:09.000000Z"),
* #OA\Property(property="updated_at", type="string", example="2021-03-31T23:20:09.000000Z"),
* ),
* #OA\Property(property="course_locale", type="object",
* #OA\Property(property="id", type="integer", example=1),
* #OA\Property(property="locale_id", type="integer", example=1),
* #OA\Property(property="name", type="string", example="new nm 2"),
* #OA\Property(property="image", type="string", example="dummy.png"),
* #OA\Property(property="description", type="string", example="course description"),
* #OA\Property(property="image_url", type="string", example="http://127.0.0.1:8000/storage/dummy.png"),
* #OA\Property(property="created_at", type="string", example="2021-03-31T23:20:09.000000Z"),
* #OA\Property(property="updated_at", type="string", example="2021-03-31T23:20:09.000000Z"),
* ),
* #OA\Property(property="author", type="object",
* #OA\Property(property="id", type="integer", example=1),
* #OA\Property(property="name", type="string", example="user 2"),
* #OA\Property(property="email", type="string", example="user#example.com"),
* #OA\Property(property="description", type="string", example="course description"),
* #OA\Property(property="profile_image", type="string", example="http://127.0.0.1:8000/storage/dummy.png"),
* #OA\Property(property="created_at", type="string", example="2021-03-31T23:20:09.000000Z"),
* #OA\Property(property="facebook_url", type="string", example="http://facebook.com"),
* #OA\Property(property="twitter_url", type="string", example="http://twitter.com"),
* #OA\Property(property="instagram_url", type="string", example="http://instagram.com"),
* #OA\Property(property="status", type="string", example="Active"),
* ),
* ),
* ),
* ),
* )
*/
Below is my default controller annotation
/**
* #OA\Info(title="API Documentation", version="1.0")
* #OA\Schemes(format="http")
* #OA\SecurityScheme(
* securityScheme="bearerAuth",
* in="header",
* name="bearerAuth",
* type="http",
* scheme="bearer",
* bearerFormat="JWT",
* )
*/
I also noticed that when we add "Origin", it is showing in the CURL preview but its not adding in api request header.
Can someone please guide me on what i'm missing here?
Thanks in advance.

How can send multipart/form-data file in application/json in swagger php

I want to uplaod a file in swagger-php in the json requestBody How can upload with the help of
swagger anonations
Trying from lot of hours but not luck how can send and file in application/json array Can you help if any
information about this so then i will solve my problem i have not concept about this
when this code generate in the terminal also not have any error and not shown in the request body in the swagger ui
/**
* #OA\Post(
* path="/products/save",
* tags={"Product"},
* summary="Post bulk products",
* description="Return bulk products",
* #OA\RequestBody(
* required=true,
* description="Bulk products Body",
* #OA\JsonContent(
* #OA\Property(
* property="products",
* #OA\Items(
* #OA\Property(property="first_name", type="string"),
* #OA\Property(property="last_name", type="string"),
* #OA\Property(property="email", type="string"),
* #OA\Property(property="phone", type="string"),
* #OA\MediaType(
* mediaType="multipart/form-data",
* #OA\Schema(
* #OA\Property(
* property="resume",
* type="file",
* format="file"
* ),
* )
* )
* ),
* )
* )
* ),
* )
*/
#OA\RequestBody(
#OA\MediaType(
mediaType="multipart/form-data",
#OA\Schema(
allOf={
#OA\Schema(ref="#components/schemas/item"),
#OA\Schema(
#OA\Property(
description="Item image",
property="item_image",
type="string", format="binary"
)
)
}
)
)
),

Array of objects in Swagger

I am new to Swagger. I am using DarkaOnline Swagger UI (OAS3).
I have a JSON request body like this
{
"CurrentPuzzle": "1",
"OpenedLevel": "10",
"RewardPuzzlePiecess":
[
1,
2,
]
}
I need to define this in swagger model. What I tried so far is I defined the following in swagger controller :
/**
* #OA\Post(path="/gameData",
* tags={"user"},
* summary="Add Game Data of User",
* security={{"bearerAuth":{}}}, *
* description="",
* operationId="gameData",
* #OA\RequestBody(
* required=true,
* description="Created user object",
* #OA\JsonContent(
* type="object",
* #OA\Items(ref="#/components/schemas/Game")
* )
* ),
* #OA\Response(response="default", description="successful operation")
* )
*/
public function gameData()
{
}
In Game Model :
/**
* #OA\Property(
* type="object",
* #OA\Items(
* #OA\Property(
* type="integer",
* description="The puzzle",
* #OA\Schema(type="array")
* ),
* #OA\Property(
* type="integer",
* description="The level",
* #OA\Schema(type="integer")
* ),
* #OA\Property(
* type="array",
* description="The survey ID",
* #OA\Items(
* type="string",
* ),
* #OA\Schema(type="array")
* ),
* ),
* description="Store User Survey Results"
* )
* #var array
*/
public $SurveyDataList;
After running, I am getting only an empty object in swagger ui like this {}.
I found the solution ,
in my controller I defined my gameData function like this,
/**
* #OA\Post(path="/gameData",
* tags={"user"},
* summary="Add Game Data of User",
* security={{"bearerAuth":{}}}, *
* description="",
* operationId="gameData",
* #OA\RequestBody(
* required=true,
* description="Created user object",
* #OA\JsonContent(
* ref="#/components/schemas/Game"
* )
* ),
* #OA\Response(response="default", description="successful operation")
* )
*/
public function gameData()
{
}
And in model.. I defined 3 properties where two of them are of type numbers and thirs one as array with Items in it.
/**
* #OA\Property(
* property="CurrentPuzzle",
* type="number",
* enum="1",
* description="Store current puzzle"
* )
*/
/**
* #OA\Property(
* property="OpenedLevel",
* type="number",
* enum="1",
* description="Store current level"
* )
*/
/**
* #OA\Property(
* property="RewardPuzzlePiecess",
* type="array",
* * #OA\Items(
* type="number",
* description="The survey ID",
* #OA\Schema(type="number")
* ),
* description="Store reward index"
* )
*/

swagger try it out redirect to login

I mount my swagger api documentation (with login to protect my route of "api/documentation"). The documentation UI it's ok but when i want execute "try it out"... Ups! Something going wrong...
I found that the class "Authenticate" (extends Middleware) redirect to login if not find the header this.headers['Content-Type'] = 'application/json';. Then, i gone to the view (resources/view/vendor/l5-swagger/index.blade.php) and set the correct headers:
requestInterceptor: function() {
this.headers['Authorization'] = 'Bearer '+token;
this.headers['Content-Type'] = 'application/json';
this.headers['Accept'] = 'application/json';
return this;
}
The problem it's that when i "retry it out" the result it's a redirect to login again. And i pass the headers on the curl:
curl -X GET "http://127.0.0.1:8000/api/mediador/xxx" -H "accept: */*" -H "Authorization: Bearer tokenGenerated" -H "Content-Type: application/json" -H "Accept: application/json"
Here an example that how i documentate my calls at the comments:
/**
* Insertamos un nuevo mediador
* #param Request $request
* #return \Illuminate\Http\JsonResponse Respuesta formateada para la api del create
*
* #OA\Post(
* path="/api/mediador/",
* tags={"Mediador"},
* description="Insert data from mediador profile",
* #OA\RequestBody(
* required=true,
* #OA\MediaType(
* mediaType="application/json",
* #OA\Schema(
* type="object",
* required={"id_user_crm","email","nombre_usuario"},
* #OA\Property(
* property="id_user_crm",
* description="ID from sugar ",
* type="string"
* ),
* #OA\Property(
* property="email",
* description="Email from profile",
* type="string"
* ),
* #OA\Property(
* property="nombre_usuario",
* description="Name of user",
* type="string"
* )
* )
* )
* ),
* #OA\Response(response="200", description="This is ok"),
* #OA\Response(response="401", description="Not logged with OAUTH token"),
* #OA\Response(response="403", description="Wrong data or duplicated fields in DataBase"),
* )
Why redirect to login yet? How can i set the data
i found the solution from my problem:
Swagger try read as html if you doesn't give the Response with correct "mediaType". Here put a complete comment to work with Swagger ui:
/**
* #OA\Post(
* path="/api/mediador/",
* tags={"Mediador"},
* description="Insert data from mediador profile",
* #OA\RequestBody(
* required=true,
* #OA\MediaType(
* mediaType="application/json",
* #OA\Schema(
* type="object",
* required={"id_user_crm","email","nombre_usuario"},
* #OA\Property(
* property="id_user_crm",
* description="ID outside of this platform",
* type="string"
* ),
* #OA\Property(
* property="email",
* description="Email from profile",
* type="string"
* ),
* #OA\Property(
* property="nombre_usuario",
* description="Name of user",
* type="string"
* )
* )
* )
* ),
* #OA\Response(
* response="200", description="Inserted data from mediador profiles",
* content={
* #OA\MediaType(
* mediaType="application/json",
* #OA\Schema(
* #OA\Property(
* property="id",
* type="integer",
* description="The id generated"
* ),
* #OA\Property(
* property="id_user_crm",
* type="integer",
* description="The reference id with the other platform"
* )
* )
* )
* }
* ),
* #OA\Response(response="401", description="Not logged with OAUTH token"),
* #OA\Response(response="403", description="Wrong data or duplicated fields in DataBase"),
* )
*/
With this comment before the function, read the #OA\Response and search #OA\MediaType to know what type of response returns the API REST.

Resources