What is Key value in PFX Certificate - k6

what will be the Key value for my PFX certificate, i am using password as string and then getting error
failed to find any PEM data in certificate input -
Also want to know is there any sample code to pass key,
What would be key for my certificate, as it have only password.
Sample code :
import https from "k6/http";
export let options = {
tlsAuth: [ {
domains: ["example.com"],
cert: open("./TESTGCY.PFX"),
key:'saxobank0'
} ]
};
export default function() {
var url = "url/AooLive/Login.svc";
var payload = JSON.stringify({ UserName: "TESTGCY", Password: "xxxxx" });
var params = { headers: { "Content-Type": "application/json" } }
var res= https.post(url, payload, params);
console.log("Response time was " + String(res.timings.duration) + " ms");
var ses= https.get(url, payload, params);
};

Related

Sendgrid works locally with Nextjs but not when I host it on Vercel

I get this to work locally, but get a Response Error: Unauthorized on Vercel.
I've created a Single Sender Verification on Sendgrid which is verified.
I've tried creating a new API key on Sendgrid but it still dosen't work.
I'm out of options.
This is my code in the api route:
import type { NextApiRequest, NextApiResponse } from "next";
const sgMail = require("#sendgrid/mail");
type EmailData = {
to: string;
from: string;
subject: string;
text: string;
html: string;
};
type DataResponse = {
data?: any;
success: boolean;
error?: string;
};
const emailAddress = process.env.SENDGRID_EMAIL as string;
const emailAddressTo = process.env.SENDGRID_EMAIL_TO as string;
sgMail.setApiKey(process.env.SENDGRID_API_KEY as string);
export default async function _(req: NextApiRequest, res: NextApiResponse<DataResponse>) {
if (req.method !== "POST") {
res.status(400).json({ success: false, error: "Invalid request" });
return;
}
const data = JSON.parse(req.body);
const { name, email, phone = "", message = "" } = data;
console.log("sgMail", sgMail);
console.log("--------------");
console.log("process.env.SENDGRID_API_KEY", process.env.SENDGRID_API_KEY);
console.log("--------------");
console.log("SENDGRID_EMAIL", process.env.SENDGRID_EMAIL);
console.log("--------------");
console.log("SENDGRID_EMAIL_TO", process.env.SENDGRID_EMAIL_TO);
console.log("--------------");
const text = `
Name: ${name} \r\n
Email: ${email} \r\n
Phone: ${phone} \r\n
message: ${message} \r\n
`;
let emailData: EmailData = {
to: emailAddressTo,
from: emailAddress,
subject: "Form submission",
text: text,
html: `<div>${text.replace(/\r\n/g, "<br>")}</div>`,
};
try {
await sgMail.send(emailData);
} catch (error) {
console.log(error);
res.status(400).json({ success: false, error: "Error while sending email" });
return;
}
res.status(200).json({ success: true, data: {} });
}
This is the log from the server with the error messages:
sgMail MailService {
client: Client {
auth: 'Bearer HIDDEN BUT ITS THERE',
impersonateSubuser: '',
defaultHeaders: {
Accept: 'application/json',
'Content-Type': 'application/json',
'User-Agent': 'sendgrid/7.7.0;nodejs'
},
defaultRequest: {
baseUrl: 'https://api.sendgrid.com/',
url: '',
method: 'GET',
headers: {},
maxContentLength: Infinity,
maxBodyLength: Infinity
}
},
substitutionWrappers: [ '{{', '}}' ],
secretRules: [],
MailService: [class MailService]
}
--------------
process.env.SENDGRID_API_KEY HIDDEN BUT ITS THERE
--------------
SENDGRID_EMAIL HIDDEN BUT ITS THERE
--------------
SENDGRID_EMAIL_TO: HIDDEN BUT ITS THERE
--------------
ResponseError: Unauthorized
at node_modules/#sendgrid/client/src/classes/client.js:146:29
at processTicksAndRejections (node:internal/process/task_queues:96:5) {
code: 401,
response: {
headers: {
server: 'nginx',
date: 'Sun, 19 Feb 2023 20:57:56 GMT',
'content-type': 'application/json',
'content-length': '97',
connection: 'close',
'access-control-allow-origin': 'https://sendgrid.api-docs.io',
'access-control-allow-methods': 'POST',
'access-control-allow-headers': 'Authorization, Content-Type, On-behalf-of, x-sg-elas-acl',
'access-control-max-age': '600',
'x-no-cors-reason': 'https://sendgrid.com/docs/Classroom/Basics/API/cors.html',
'strict-transport-security': 'max-age=600; includeSubDomains'
},
body: { errors: [Array] }
}
}
Vercel deployments use dynamic IP addresses due to the dynamic nature of the platform and in Sendgrid their IP Access management was on, which meant that all requests from Vercel were blocked..
SOLUTION:
You can disable IP Access Management to reopen account access to any IP address and no longer maintain a list of allowed addresses.
From the Settings > IP Access Management page, click Disable Allow List.
A dialog will open asking you to confirm the decision. Click Disable.

how to pass api-key to public api and aws agnostic aws signature for private api as authorization in graphql and next js framework

import { ApolloClient, createHttpLink, InMemoryCache } from "#apollo/client";
import { _getCookies } from "#utils/cookies";
import createAwsClient from 'agnostic-aws-signature';
import { setContext } from "apollo-link-context";
// fetching tokens received from cognito after login and creating signature
const sessionToken = _getCookies("sessionToken")
const secretAccessKey = _getCookies("secretAccessKey")
const accessKeyId = _getCookies("accessToken")
const expiration = _getCookies('expiration')
const awsClient = createAwsClient(accessKeyId, secretAccessKey, sessionToken, {
serviceName: "appsync",
region: process.env.COGNITO_REGION, // Your AWS resource region
endpoint: process.env.APPSYNC_ENDPOINT, // Your AWS resource url
});
const publicAPI = [
"getFaq",
"getMedia",
"getCategory",
"listVehicleColors",
"getLocationByPIN",
"listAccessories",
"verifyEmailToken"
]
const customFetch = (uri, options) => {
// check if values exists in public API
const addAPIKeyIf = publicAPI.map(val => options.body.includes(val)).reduce((a, b) => a || b, false);
// Sign our Request to allow User access to AWS resource
const signedRequest = awsClient.signRequest({
method: options.method, // Method of your request
headers: {
// Whatever headers you need to send to the resource
// accept: '*/*',
// 'content-type': 'application/json;application/x-www-form-urlencoded;charset=utf-8',
},
body: options.method == "POST" ? options.body : {}, // Whatever body you need to send to the resource
});
// if api is public add x-api-key or else remove it
addAPIKeyIf ? "" : delete options.headers["x-api-key"]
options.headers = { ...options.headers, ...signedRequest.headers }
return fetch(uri, options)
}
const httpLink = createHttpLink({
uri: process.env.APPSYNC_ENDPOINT,
fetch: accessKeyId ? customFetch : null,
});
const authLink = setContext((_, { headers }) => {
return {
headers: {
...headers,
"x-api-key": process.env.API_KEY
}
};
});
const client = new ApolloClient({
link: authLink.concat(httpLink),
cache: new InMemoryCache(),
defaultOptions:{
watchQuery: {
fetchPolicy: 'no-cache'
},
query: {
fetchPolicy: 'no-cache'
}
}
});
export default client;
I am storing the Cognito tokens as cookies and creating signature using aws-agnostic-signature
this is all working. and we are mapping out the public api and if addApiKeyif is true, we are adding the X-api-key, else deleting it from headers. so, our requirement is, if its public api ,we have to pass x-api-key, if its private we have to pass aws signature as authorization, but currently all the Api's are taking api-key as authorization.

How to get logged user in vuejs

I made a jwt authetication using asp.net core and vuejs
this is my auth controller :
[Route("Login")]
[HttpPost]
public IActionResult Login(LoginArgument loginArgument)
{
var user = _userService.GetByEmail(loginArgument.Email);
if (user == null) return BadRequest(error: new { message = "Invalid credential : verify email" });
if (!BC.BCrypt.Verify(text: loginArgument.Password, hash: user.Password))
{
return BadRequest(error: new { message = "Invalid credential : verify password" });
}
var jwt= _jwtService.Generate(user.Id);
Response.Cookies.Append(key: "jwt", value: jwt, new Microsoft.AspNetCore.Http.CookieOptions
{
HttpOnly=false,
SameSite=Microsoft.AspNetCore.Http.SameSiteMode.None
}) ;
return Ok(user);
}
[Route("User")]
[HttpGet]
public IActionResult User()
{
try
{
var jwt = Request.Cookies["jwt"];
var token = _jwtService.Verify(jwt);
int userId = int.Parse(token.Issuer);
var user = _userService.GetById(userId);
return Ok(user);
}
catch (Exception)
{
return Unauthorized();
}
}
and this is the login in vue
<script lang="ts">
import { reactive } from 'vue';
import { useRouter } from "vue-router";
export default {
name: "Login",
setup() {
const data = reactive({
email: '',
password: ''
});
const router = useRouter();
const submit = async () => {
await fetch('https://localhost:44391/api/Auth/Login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
body: JSON.stringify(data)
});
await router.push('/Countries');
}
return {
data,
submit
}
},
}
the login part is working in front and back sides perfectly and i can see the cookies
the problem is when i try to get the logged user. in back side i can get it successfully but in front it says that no user is logged
here is the loggedUser vue
<script lang="ts">
import { onMounted, ref } from 'vue';
export default {
name: "LoggedUser",
setup() {
const message = ref('You are not logged in!');
onMounted(async () => {
const response = await fetch('https://localhost:44391/api/Auth/User', {
headers: { 'Content-Type': 'application/json' },
credentials: 'include'
});
const content = await response.json();
message.value = `hi ${content.name}`;
});
return {
message
}
}
}
Here is the errors i got when i inspect the page :
this issues appear the moment of login
1- Mark cross-site cookies as Secure to allow setting them in cross-site contexts
2- Migrate entirely to HTTPS to have cookies sent to same-site subresources
this one appears when i call loggedUser in front even so it works in the back side
{type: "https://tools.ietf.org/html/rfc7235#section-3.1", title: "Unauthorized", status:
401,…}
status: 401
title: "Unauthorized"
traceId: "00-b4a9f6fee8dff6439952ded0bb50005d-43c9aee84c454b40-00"
type: "https://tools.ietf.org/html/rfc7235#section-3.1"
You need to send the access token in the request headers
Example:
let token = '???'
const response = await post('localhost/api/auth/user', {
headers: {
'Content-Type': 'application/json'
'Authorization' : 'Bearer '+ token
}
});

Why dio posts empty form data?

I have a function to upload an image but the server does not receive anything and I get 500 status code. I'm sure that the server is fine. It works when I send a post request from the postman!
This is my function:
uploadPrescriptionToAll(File file, data) async {
String convertedFilePath = await convertImage(file);
String token = await getToken();
Response response;
Dio dio = Dio();
dio.options.baseUrl = "http://x.x.x.x:x";
FormData formData = FormData.from({
"image":
UploadFileInfo(new File(convertedFilePath), "image.jpg"),
"data": data,
});
try {
response = await dio.post("/api/images",
data: formData,
options: Options(headers: {
"Authorization": token,
"Content-Type": "multipart/form-data"
}));
} catch (e) {
print("Error Upload: " + e.toString());
}
print("Response Upload:" + response.toString());
}
how can I post the file (form-data) correctly? Is there another way to do it?
Using Dio It's very simple by using : FormData.fromMap()
searchCityByName(String city) async {
Dio dio = new Dio();
var a = {"city": city};
var res = await dio.post(apiSearchState, data:FormData.fromMap(a));
}
In short, you should pass a Map<String, dynamic> object to dio.post()'s data field. For example:
response = await dio.post("/api/images",
data: {"image": "image.jpg", "data": data});
See: https://github.com/flutterchina/dio/issues/88 for details

Meteor login through different server

I want to let my meteor users login through my react-native app.
I have one website built by Meteor/reactjs and the other is an App using android react-native and they both share the same Mongo database.
My meteor website uses bcrypt (meteor accounts-password), and my react-native app where I tried to use SHA256 and bcrypt so when I log in through my react-native app which is connected to the database, the hashed passwords do not match and I get an error.
I'm just getting really confused as to how to hash my react-native password to get it to the match the meteor users' hashed password. Any help would be great, cheers.
This is the front end
sendAjax = () => {
const m = encodeURIComponent(this.state.email);
const p = encodeURIComponent(this.state.password);
const hashDigest = sha256(p);
const requestBody = `email=${m}&password=${hashDigest}&mphone`;
//POST
fetch("http://**************/users/auth", {
method: "POST",
mode: "cors",
headers: {
"Accept": "application/json",
"Content-Type": "application/x-www-form-urlencoded"
},
body: requestBody
}).then(function (res, next) {
console.log("fetch request ", JSON.stringify(res.ok));
if(res.ok){
res.json().then(function (json) {
console.info(json);
console.info(json.verifystate);
if(json.verifystate){
Alert.alert("Login success");
Actions.leaderBoard();
}else{
Alert.alert("Login fail, please try again");
}
});
}else{
Alert.alert('Noted','request failed',[{text: 'confirm', onPress: () => console.log('OK Pressed!')},]);
next();
}
})
.catch(function (e) {
console.log("fetch fail");
Alert.alert('Noted','system error',[{text: 'confirm', onPress: () => console.log('OK Pressed!')},]);
});
}
This is my backend
app.post('/users/auth', function(req, res) {
loginData(db, req.body.email, req.body.password, function(result){
if(result == 1){
console.log("find the result!");
res.send({"verifystate":true});
}else{
console.log('cannot find it');
}
});
});
......
var loginData = function(db, email, myPlaintextPassword, mphone, callback){
var collectionUser = db.collection('users');
bcrypt.genSalt(saltRounds, function(err, salt) {
bcrypt.hash(myPlaintextPassword, salt, function(err, hash) {
var queryStr = {"emails.address": email, "services.password.bcrypt": hash};
collectionUser.count(queryStr, function(err, result) {
if(err)
{
console.log('Error2:'+ err);
}
callback(result);
});
});
});
};

Resources