I using swagger and I add auth today. But even if I write any letter like " a " or "abc" or what its still entering. How can I check is it true token for use swagger? My code:
const options = {
definition: {
openapi: "3.0.0",
info: {
title: "İlaç Takip Sistemi API",
version: "2.0.0",
description: "ITS API Swagger",
},
servers: [
{
url: "http://localhost:3100",
},
],
components: {
securitySchemes: {
bearerAuth: {
type: "apiKey",
name: "x-auth-token",
scheme: "bearer",
in: "header",
},
},
},
security: [
{
bearerAuth: [],
},
],
},
apis: ["./app/routes.js"],
};
const specs = swaggerJsDoc(options);
app.use("/swagger", swaggerUI.serve, swaggerUI.setup(specs));
This is how i check Token :
jwt.verify(req.token, process.env.SECRETKEY, (err, authData) => {
if (err) {
res.sendStatus(401);
} else {
res.json(authData);
}
});
When i write my token to swagger then do my works in there but when i try from swagger its saying Unauthorized even my token is true and working while i trying in postman.
Change your security scheme as follows:
bearerAuth: {
type: "http",
scheme: "bearer",
},
This way the "Bearer" prefix will be added automatically to the tokens you enter in Swagger UI.
When using type: "apiKey" for Bearer authentication, you would have to include the "Bearer " prefix in the token value, that is, enter the token as Bearer abc123 in Swagger UI.
Related
Trying to create Laravel Api app that would be on a different domain with React as frontend app... when attempting to login, after fetching csrf-cookie, and making another request, I get the error:
{
"message": "Network Error",
"name": "AxiosError",
"config": {
"transitional": {
"silentJSONParsing": true,
"forcedJSONParsing": true,
"clarifyTimeoutError": false
},
"transformRequest": [
null
],
"transformResponse": [
null
],
"timeout": 0,
"xsrfCookieName": "XSRF-TOKEN",
"xsrfHeaderName": "X-XSRF-TOKEN",
"maxContentLength": -1,
"maxBodyLength": -1,
"env": {
"FormData": null
},
"headers": {
"Accept": "application/json, text/plain, */*",
"Content-Type": "application/json"
},
"withCredentials": true,
"method": "post",
"url": "http://localhost:8000/api/login",
"data": "{\"email\":\"test2#gmail.com\",\"password\":\"test\"}"
},
"code": "ERR_NETWORK",
"status": null
}
If I disable
\Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
In my Kernel.php file, everything works fine
This is how I send the request
function submitForm(e) {
e.preventDefault();
const body = {
email: email,
password: password,
};
axios.get(csrf).then((res) => {
console.log(res);
axios.post(login, body, {withCredentials:true}).then((res) => {
console.log(res);
});
});
}
But if i remove {withCredentials:true} I get this error:
message: "Request failed with status code 419"
"CSRF token mismatch."
Cors.php file:
'paths' => ['*'],
'allowed_methods' => ['*'],
'allowed_origins' => ['*'],
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => true,
Laravel sanctum does not allow browser authentications from different domain. It only works on apps on subdomains under one domain. I am assuming your react app is hosted on localhost:3000, your laravel app is hosted on localhost:8000. Those are completely different domains. If you take a closer look, Laravel will not issue a CSRF token and there is no csrf cookie stored in browser. Your option would be to host the apps on same domain. Lets say frontend.app.test for frontend and api.app.test for laravel backend. This can be done with packages like laravel valet.
I am trying to integrate paytm in react native. but the problem is when I tap on pay button (call call_api) but then processing screen is coming and suddenly app navigate to current screen where I define pay button. please help here is my code
call_api = () => {
fetch("https://XXXXXXXXXXXXXXX", {
method: "POST",
headers: {
Accept: "application/json, text/plain, */*",
"Content-Type": "application/json",
},
body: JSON.stringify([
{
mobile_no: "XXXXXx",
user_id: "XX",
patient_name: "XXXx",
},
]),
})
.then((returnValue) => returnValue.json())
.then((response) => {
console.log("this checksum api esponse" + JSON.stringify(response));
this.setState({ order_id: response[0].data.order_id });
this.setState({ checksum: response[0].data.checksumhash });
this.pay();
});
};
pay = () => {
const details = {
//mode: "Production", // 'Staging' or 'Production'
mode: "Production",
MID: "XXXXXXXXXXXXXXX",
INDUSTRY_TYPE_ID: "Retail",
WEBSITE: "APPSTAGING",
CHANNEL_ID: "WAP",
TXN_AMOUNT: "1", // String
ORDER_ID: this.state.order_id, // String
// EMAIL: email, // String
// MOBILE_NO: mobile, // String
CUST_ID: "CUSTOMER_1", // String
CHECKSUMHASH: `${this.state.checksum}`, //From your server using PayTM Checksum Utility
CALLBACK_URL:
"https://securegw.paytm.in/theia/paytmCallback?ORDER_ID=" +
`${this.state.order_id}`,
// CALLBACK_URL: `https://securegw-stage.paytm.in/theia/paytmCallback?ORDER_ID=<${this.state.order_id}>`,
};
Paytm.startPayment(details);
console.log(details);
};
Please make sure that you have Paytm Staging app installed on your device. You can get the same from the link mentioned on Paytm Developer Portal
I need to do a new api in order to send an email with sendgrid. I followed the official doc and other examples so I did:
config/plugins
module.exports = ({ env }) => ({
email: {
provider: 'sendgrid',
providerOptions: {
apiKey: env('SENDGRID_API_KEY'),
},
settings: {
defaultFrom: 'juliasedefdjian#strapi.io',
defaultReplyTo: 'juliasedefdjian#strapi.io',
},
},
});
then I did a new folder named email in api folder
api/email/config/routes.json
{
"routes": [
{
"method": "POST",
"path": "/email",
"handler": "email.index",
"config": {
"policies": []
}
}
]
}
finally under api/email/controllers/email.js
const { default: createStrapi } = require('strapi');
module.exports = {
index: async (ctx) => {
//build email with data from ctx.request.body
await createStrapi.plugins['email'].services.email.send({
to: 'email#email.com',
from: 'email#email.com',
replyTo: 'email#email.com',
subject: 'test',
text: 'test',
});
ctx.send('Email sent!');
},
};
The real problem is that /email api returns me a 403 even if I did this from the dashboard:
I have done many APIs with strapi but I have never sent emails with it.
Is there a way to add permissions from the code? I have to say that if I use GET method it works, but I need to do it with a POST method, which doesn't. Did I miss something?
According to the API documentation, to receive json as formData from a POST request, one must use body-parser. I have declared it in the gateway service but I can still not receive the formData in my action.
api.service.js
module.exports = {
name: "api",
mixins: [ApiGateway],
settings: {
port: process.env.PORT || 3000,
routes: [{
path: "/api",
aliases: {
"POST users": "users.insertUser",
},
//The API Documentation recomends using the body-parser here
bodyParsers: {
json: true,
urlencoded: { extended: true }
},
}],
// In some example they also set the body-parser here
bodyParsers: {
json: true,
urlencoded: { extended: true }
},
},
};
In the actions service.insertUser action I am supposed to receive the
req.body as ctx.params, however it is always empty
My users.service.js
actions: {
insertUser: {
handler(ctx) {
this.logger.info("posting", ctx.params); // -> prints {} instead of the formData
}
}
have you tried giving params
insertUser: {
auth: "required",
params: {
function_id: { type: "string" },
role_id: { type: "string" },
},
handler(ctx) { ctx.params.role_id
send post data with content-type:application/json
I am using Google Calendar library for Node.js to get calendar ID and events list from API. This is working as expected. But when I'm trying to insert or modify an event, I'm facing the common(!) error message "Missing end time".
I am trying to send a POST request using Request - Simplified HTTP client and not using Google Library or other package.
Here's my code snippet:
const request = require('request');
// Update Event Title
function insertEventIntoCalendar(calendarId,accessToken){
let endDateTime = {
dateTime: '2018-07-03T10:25:00.000-07:00',//end,
timeZone: 'Asia/Dhaka'
},
startDateTime = {
dateTime: '2018-07-03T10:00:00.000-07:00', //start,
timeZone: 'Asia/Dhaka'
},
url = "https://www.googleapis.com/calendar/v3/calendars/primary/events?access_token="+accessToken,
options = {
data: {
end: endDateTime,
start: startDateTime,
summery: 'ARG will win',
location: '800 Howard St., San Francisco, CA 94103',
attendees: [],
reminders: {
useDefault: true,
}
},
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + accessToken,
'Accept': 'application/json'
},
calendarId: 'primary'
}
request.post(url, options, function (err, res, body) {
console.log('err =>', err);
console.log('body =>', body);
})
}
And here is my console.log message:
err => null
body => {
"error": {
"errors": [
{
"domain": "global",
"reason": "required",
"message": "Missing end time."
}
],
"code": 400,
"message": "Missing end time."
}
}
Note: I've followed all questions and answers related to Google Calendar API and Node.js and still facing the same error. And I've not found any answers where Google Library is not used.
Please share your thoughts if you tried this way, otherwise you can suggest me a better way where I don't need any Config file to get or modify Google Calendar info.
The problem is in declaring the options variable. The documentation of Request - Simplified HTTP client is saying the json data of Request body should be named as 'json'. So the options variable should be,
options = {
url: url
json: {
end: endDateTime,
start: startDateTime,
summery: 'ARG will win',
location: '800 Howard St., San Francisco, CA 94103',
attendees: [],
reminders: {
useDefault: true,
}
}
}
and to send the POST request, the code should be:
request.post(options,function (err, res, body) {
console.log('err =>', err);
// console.log("res =>", res);
console.log("body =>", body);
})
I tried this way and it works :)
bonnopc answer solved it for me. For the people getting here searching for node js + Google Calendar API error, this also works there:
auth.getClient().then(a => {
calendar.events.patch({
json: {
summary: "bablabbla",
start: JSON.stringify(new Date()),
end: JSON.stringify(new Date())
},
auth: a,
calendarId: GOOGLE_CALENDAR_ID,
eventId: changedEvent.id
})
})