401 error while using #react-oauth/google - javascript

const googleLogin = useGoogleLogin({.
flow: 'auth-code',
onSuccess: async (codeResponse) => {
const response = await axios.post(
'my backend api '
{
accessToken: codeResponse.code,
oAuthAgency: 2,
}
);
console.log(codeResponse);
},
onError: (errorResponse) => console.log(errorResponse),
});
This is React Oauth2 grammar. I want to do by authorization code flow
sending authorization code to backend for getting access token.
I'm working on this for two days. Please help me.

Related

Stripe Webhook error 400 with netlify functions

I have set up payments with stripe using Netlify function by following this article https://www.netlify.com/blog/2020/04/22/automate-order-fulfillment-w/stripe-webhooks-netlify-functions/ and in my Stripe dashboard I get error saying that:
Webhook Error: No signatures found matching the expected signature for payload. Are you passing the raw request body you received from Stripe? https://github.com/stripe/stripe-node#webhook-signing
Now I am not sure if the user gets confirmation email, Sendgrid does not show any activity, however it has not shown any when I was testing this flow previously, and although I received confirmation email. Unfortunately back then I pressed resend by my webhook activity details in Stripe dashboard, and I am not sure if I should be resending those or do they go through. Would anyone be able to tell me what is wrong with my code?
const stripe = require("stripe")(process.env.STRIPE_SECRET_KEY);
const sgMail = require("#sendgrid/mail");
sgMail.setApiKey(process.env.SENDGRID_API_KEY);
exports.handler = async ({ body, headers }) => {
try {
const stripeEvent = stripe.webhooks.constructEvent(
body,
headers["stripe-signature"],
process.env.STRIPE_WEBHOOK_SECRET
);
if (stripeEvent.type === "charge.succeeded") {
const emailTo = stripeEvent.data.object.billing_details.email;
const msg = {
to: emailTo,
from: process.env.FROM_EMAIL_ADDRESS,
subject: `Thanks!`,
html: `elox`,
};
await sgMail.send(msg);
}
return {
statusCode: 200,
body: JSON.stringify({ received: true }),
};
} catch (err) {
console.log(`Stripe webhook failed with ${err}`);
return {
statusCode: 400,
body: `Webhook Error: ${err.message}`,
};
}
};
Thanks!
I got the same issue.
Locally with the stripes-cli everything works fine.
It seems that the lambda didn't hand over the raw body to the stripes.webhook.constructEvent.
Therefore my solution was to change the method signature to the following and use the event.body object.
exports.handler = async(event, context ) => {
try {
const stripeEvent = stripe.webhooks.constructEvent(
event.body,
event.headers['stripe-signature'],
endpointSecret
);....

How can I access the token which is saved in the header using angular

I am sending the 'auth-token' which is generated with JWT to the frontend which is built in angular. The backend is built in nodejs. when I try to access the auth-token variable from the frontend it is saying syntax error. How can access this header token in my angular code?
Frontend Request in the component
onSubmit(){
if(!this.signinForm.valid){
return;
}
const userDetails: SigninAccount = {
email: this.signinForm.controls.email.value,
password: this.signinForm.controls.password.value
}
this.loginservice.loginUser(userDetails).subscribe(
data => { console.log(data);
this.router.navigate(['/'])
},
error => { console.log(error.error)}
)
}
Frontend service and the headeroptions
const loginhttpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
})
}
loginUser(user: SigninAccount): Observable<SigninAccount> {
const makeReqURL = `${this.apiURL}/login`;
const loginUser = this.http.post<SignupAccount>(makeReqURL, user, httpOptions)
return loginUser;
}
Backend response
const userToken = jwt.sign({ _id: user._id }, process.env.TOKEN);
res.header('auth-token', userToken).send(userToken)
Screenshot of the image in the browser and the syntax error message which is given because of the console.log(data).
the "text" has the JWT token too which is the same as the "auth-token" but don't know how to access it in the code and I don't know what is the syntax error either.
Please help. Thank you very much in advance.
There must be some syntax issue in backend code that's why you getting the error. Use some linter like EsLint which can help detecting the error.
How to access the authToken?
Here is your new backend code.
don't set token in header instead send as a json.
const userToken = jwt.sign({ _id: user._id }, process.env.TOKEN);
res.json({token: userToken});
The frontend code is correct you gonna get your token in console.
this.loginservice.loginUser(userDetails).subscribe(
data => {
console.log(data);
const token = data.token;
//Save to localStorage
localStorage.setItem('token',token);
this.router.navigate(['/']);
},
error => { console.log(error.error)}

Authenticated requests after sign in with React Query and NextAuth

I'm having troubled sending an authenticated request to my API immediately after signing in to my Nextjs app using NextAuth. The request that is sent after signing in returns data for and unauthenticated user.
I believe the issue is that React Query is using a previous version of the query function with an undefined jwt (which means its unauthenticated). It makes sense because the query key is not changing so React Query does not think it's a new query, but, I was under the impression that signing in would cause loading to be set to true temporarily then back to false, which would cause React Query to send a fresh request.
I've tried invalidating all the queries in the app using queryClient, but that did not work. I've also used React Query Devtools to invalidate this specific query after signing in but it still returns the unauthenticated request. Only after refreshing the page does it actually send the authenticated request.
// useGetHome.js
const useGetHome = () => {
const [session, loading] = useSession();
console.log(`session?.jwt: ${session?.jwt}`);
return useQuery(
'home',
() => fetcher(`/home`, session?.jwt),
{
enabled: !loading,
},
);
}
// fetcher
const fetcher = (url, token) => {
console.log(`token: ${token}`);
let opts = {};
if (token) {
opts = {
headers: {
Authorization: `Bearer ${token}`,
},
};
}
const res = await fetch(`${process.env.NEXT_PUBLIC_BACKEND_URL}${url}`, opts);
if (!res.ok) {
const error = await res.json();
throw new Error(error.message);
}
return res.json();
}
// Home.js
const Home = () => {
const { data: home_data, isLoading, error } = useGetHome();
...
return(
...
)
}
Attached is the console immediately after signing in. You can see the the session object contains the jwt after signing in, but in the fetcher function it is undefined.
console after signing in
Any help here is appreciated. Is there a better way to handle authenticated requests using React Query and NextAuth? Thank you!
I have tried a similar situation here and struggled the same thing but the enabled property worked fine for me and it is good to go right now.
https://github.com/maxtsh/music
Just check my repo to see how it works, that might help.

coinmarketcap api integration - 401 error - JavaScript

I am trying to integrate coinmarketcap api but cannot really get the data. I registered, got the API key, and wrote the following method to fetch the data:
let getPostsList = async () => {
const options = {
method: 'GET',
headers: {
'X-CMC_PRO_API_KEY': 'api-key-goes-here'
},
mode: 'no-cors'
};
try {
const response = await fetch(`https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest`, options);
const json = await response.body;
// console.log(json)
return json
} catch (err) {
console.log('Error: ', err)
}
};
All I get is 401 error, like this:
GET https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest
401
Any suggestions what I should fix? Docs says that 401 is likely connected to API key, but they say to provide it in the headers like the above...
From what I've tested after getting my own API key, the no-cors mode is problematic. You will need to use CORS, where https://cors-anywhere.herokuapp.com/ comes into handy.
Just send the request like this :
const options = {
method: 'GET',
headers: {
'X-CMC_PRO_API_KEY': 'api-key-goes-here'
},
};
try {
const response = await fetch(`https://cors-anywhere.herokuapp.com/https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest`, options);

Refresh token with Graph OAuth v2.0

I'm requesting a user's info via Microsoft Graph. I use the 2.0 endpoint.
This is my login function:
login() {
hello('msft').login({scope: Configs.scope}).then(
() => {
this.zone.run(() => {
this.meService.getMe().subscribe(data => {
localStorage.setItem('username', data.mail);
localStorage.setItem('jobtitle', data.jobTitle);
localStorage.setItem('loggedin', 'yes');
},
err => {
console.log(err);
},
() => {
this.router.navigate(['/home']);
});
});
},
e => console.error(e.error.message)
);
}
This is my init function:
initAuth() {
this.redirect_uri = window.location.href;
hello.init({
msft: {
id: Configs.appId,
oauth: {
version: 2,
auth: 'https://login.microsoftonline.com/common/oauth2/v2.0/authorize'
},
scope_delim: ' ',
form: false
},
},
{redirect_uri: window.location.href}
);
}
And here I am getting the access token:
getAccessToken() {
const msft = hello('msft').getAuthResponse();
console.log(msft);
const accessToken = msft.access_token;
return accessToken;
}
I get an access token, via which I can login. However, I get no refresh token. From what I read, you get the refresh and the access token via the /token endpoint. As far as I can see, I only use the /authorize endpoint and it works?
This poses a problem. I can't refresh my token!
A response looks like this:
access_token:
"This is private, but it's a very long string"
client_id:"e6c987d2-8bdc-4f1a-bafc-04ba3d51f340"
display:"popup"
expires:1524649746.548
expires_in:3599
network:"msft"
redirect_uri:"http://localhost:4200/"
scope:"basic,User.Read"
session_state:"89a68bd2-5ae5-4df2-88d0-d28718fd10bc"
state:""
token_type:"Bearer"
Any help would be appreciated!
Since you're using the Implicit grant, you cannot use Refresh Tokens. They're only supported using the Authorization Code grant.
In order to use Refresh Tokens, you'll need to switch to the Authorization Code grant and implement the server-side code to process the authorization code into an access token. You'll also need to request the scope offline_access which triggers the generation of a refresh_token.

Categories

Resources