jwt token return null - javascript

i try to get a user id by token,
the token is pass by the header Authorization,
when i use ExtractJwt.fromAuthHeaderWithScheme("jwt")(req)
i get back the token as null
here is pass the token to the header.
const token = localStorage.getItem("id_token");
export const insertMovie = (payload) => {
return api.post(`/movie`, payload, {
headers: { "Authorization": `${token}` },
});
};
here i try to verify to token
var User = require("../models/user-model");
var Movie = require("../models/movie-model");
var bcrypt = require("bcrypt");
var jsonwt = require("jsonwebtoken");
var key = require("../db/myUrl");
var ExtractJwt = require("passport-jwt");
createMovie = async (req, res) => {
const movieDetails = req.body.movie;
const token = ExtractJwt.ExtractJwt.fromAuthHeaderWithScheme("jwt")(req);
const decoded = jsonwt.verify(token, key.secret);
const userId = decoded.userId;
console.log(decoded);
}

When you try to
ExtractJwt.fromAuthHeaderWithScheme("jwt")
you need to add the token to the header like so:
headers: { "Authorization": `jwt ${token}` },
from the docs:
fromAuthHeaderWithScheme(auth_scheme) creates a new extractor that looks for the JWT in the authorization header, expecting the scheme to match auth_scheme.

You’ve doubled up ExtractJwt but also if you’re declaring a scheme “jwt” that needs to be appended to the token
headers: { Authorization: `jwt ${token}` }
Otherwise change fromAuthHeaderWithScheme to just fromAuthHeader to fromHeader(‘Authorization')
Also I’m not sure if you can use passport directly inside an endpoint like this - I always thought it needed to be used as middleware.

Related

How to set axios header dynamically according to access_token expired and url

I am new to using Axios configuration. **So I am wondering if it is possible to set axios header dynamically?**
Because the end points I am calling right now need a Authentication and different authentication for different api, so I want make a change to the created axios instance’s header when token is expired and with different URL.
Here is my current code:
in config.js
import axios from 'axios'
// to get Authorization for api_1
const {access_token_1} = axios.get('url/access_token_1')
// to get Authorization for api_2
const {access_token_2} = axios.get('url/access_token_2')
export const instance = axios.create({
headers: { Authorization: `Bearer ${access_token_1}` },
})
My Api_1 and 2 call
//Api_1
export const getCountry = async (country: string) => {
const response = await instance.get(
`/sas/${country}`
)
return response.data
}
//Api_2
export const getCity = async (city: string) => {
const response = await instance.get(
`/sps/${city}`
)
return response.data
}
I know header can be set again by certain method, but how could I set it again only when it’s expired and set the instance with right authentication for certain Api
Have a look at this documentation, you can create/update headers and pass them to your axios instance. I think this examples might help a little
axios.defaults.baseURL = 'https://api.example.com';
// Important: If axios is used with multiple domains, the AUTH_TOKEN will be sent to all of them.
// See below for an example using Custom instance defaults instead.
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
const options = {
method: 'POST',
headers: { 'content-type': 'application/x-www-form-urlencoded' },
data: qs.stringify(data),
url,
};
axios(options);
axios.get('https://example.com/getSomething', {
headers: {
Authorization: 'Bearer ' + token //the token is a variable which holds the token
}
})

Trying to get access token for Paylocity Web API in Node.js but getting error "invalid_client"

I have been trying to retreive the access token for the paylocity API. I am able to get it through postman with the client id and client secret however when I try and retrieve it with Node.js I get the message {"error":"invalid_client"}.
Here is my code
const apikey = {user name};
const secret = {password};
const url = "https://api.paylocity.com/IdentityServer/connect/token";
const authorizationTokenInBase64 = Buffer.from(
`${apiKey}:${secret}`
).toString("base64");
const body = "grant_type=client_credentials&scope=WebLinkAPI";
let config = {
headers: {
Authorization: `Basic ${authorizationTokenInBase64}`,
"Content-Type": `application/x-www-form-urlencoded`,
},
};
try {
const response = await axios.post(url, body, config);
} catch (error) {
console.log("error", error.response.data);
}

Axios headers being sent as payload

I'm using axios to send a post request, here's my code:
const getHeaders = (token) => {
const headers = {
"content-type": "application/json",
}
if (token !== undefined) headers.Authorization = `Bearer ${token}`;
return headers;
}
const post = async ({ url, body = {}, token }) => {
const requestObject = {
headers: getHeaders(token),
...body
}
console.log(requestObject);
return await axios.post(url, requestObject);
}
This works when there's no token (for example, the login request), it sends it alright. However, for the next request, I pass a token to request the user details (for example), but when I look at the Chrome network tab, I see this:
So, the headers are being sent as the payload, but then, in the request headers, the "Authorization: Bearer ..." is not there. What am I doing wrong?
If you want to send options you need a third argument....
const post = ({ url, body = {}, token }) => {
const options = {
headers: getHeaders(token)
}
return axios.post(url,body, options);
}
Also async/ await makes no sense here

How to access Express HTTP Request from Apollo Link Context, in a NextJS App?

I'm building a NextJS app, and I'm trying the access a cookie so I can use it to set a Http Header for GraphQL Request, I am using apollo-link-context. This is the code to create the ApolloClient
function createApolloClient(initialState = {}) {
const httpLink = new HttpLink({ uri: `${baseUrl}/graphql`, credentials: 'same-origin', fetch })
const authLink = setContext((_, prevCtx) => {
let token = ''
if (typeof window === 'undefined') token = getCookieFromServer(authCookieName, REQ)
else token = getCookieFromBrowser(authCookieName)
return ({ headers: { 'Auth-Token': token } })
})
const client = new ApolloClient({
ssrMode: typeof window === 'undefined',
cache: new InMemoryCache().restore(initialState),
link: authLink.concat(httpLink)
})
return client
}
The issue here is that the getCookieFromServer function expects an Express Request as the second argument, so it can extract the cookie from req.headers.cookie, and I have no idea where I can get it from there.
I finally found a way. Whenever I send a request from the server (in PageComponent.getInitialProps), I set the header in the context, then I can access it from setContext:
PageComponent.getInitialProps = async (ctx) => {
...
const token = getCookieFromServer(authCookieName, ctx.req)
const { data } = await client.query({
query,
context: { headers: { 'Auth-Token': token } }
})
...
}
Then in setContext:
const authLink = setContext((_, prevCtx) => {
let headers = prevCtx.headers || {}
if (!headers['Auth-Token']) {
const token = getCookieFromBrowser(authCookieName)
headers = { ...headers, 'Auth-Token': token }
}
return ({ headers })
})
So if the header is already present in the previous context (which is the case when sent from the server), just use it. If it is not present (when sent from the browser), get the cookie from the browser and set it.
I hope it will help somebody one day.

Making a x-www-form-urlencoded request with axios

const { user } = require('./config');
const axios = require('axios');
const Querystring = require('querystring');
let body = Querystring['stringify']({
email: 'MY EMAIL#email.com',
password: 'pass'
})
const config = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}
axios['post']('https://minecraftservers.org/login', body, config)
['then'](response => console.log(response))
Im trying to login through a website
it doesn't have an api
the headers are correct
if you're wandering how i knew this, i used chrome dev tools
like reverse engineer
content-type: application/x-www-form-urlencoded
that's the header they used when i tried to login to the site
this is what i get when i logged in through the site and not the code, it works there.
You can use URLSearchParams
const params = new URLSearchParams();
params.append('firstName', 'paul');
params.append('lastName', 'fred');
axios.post('/user', params);
It avoids adding another library.
I guess systax is your problem. Do you have any difficulties other than the syntax?
const { user } = require('./config');
const axios = require('axios');
const Querystring = require('querystring');
let body = Querystring['stringify']({
email: 'MY EMAIL#email.com',
password: 'pass'
})
const config = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}
axios.post('https://minecraftservers.org/login', body, config)
.then(response => console.log(response))
Try
axios.post('https://minecraftservers.org/login', body, config)
.then(response => console.log(response))

Categories