While trying to log in a user with Firebase's log in with email and password, this error occurs:
https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key=AIzaSyCgebjp9UWGlH-gMBp0MVYJ8thoXqglt-Q
Failed to load resource: the server responded with a status of 400 ()
Here is my code:
import {initializeApp} from "https://www.gstatic.com/firebasejs/9.17.1/firebase-app.js"
import { getAuth, signInWithEmailAndPassword } from "https://www.gstatic.com/firebasejs/9.17.1/firebase-auth.js"
import { getDatabase } from "https://www.gstatic.com/firebasejs/9.17.1/firebase-database.js"
const firebaseConfig = {
// config is correct, removed for sake of privacy
};
initializeApp(firebaseConfig);
const db = getDatabase();
const auth = getAuth();
function Login() {
// this part returns the error
signInWithEmailAndPassword(auth, $("#email").val(), $("#password").val())
.then((userCredential) => {
// Signed in
const user = userCredential.user;
// ...
})
.catch((error) => {
const errorCode = error.code;
const errorMessage = error.message;
});
}
Related
I have upgraded from Firebase Admin 10 to 11 and now I am finding an error
Error: Cannot find module 'firebase-admin/auth'
Require stack:
- C:\Users\Quarton Family\Desktop\TipBossProjects\TipBoss2023\server\firebase\index.js
my code is:
const { initializeApp, cert } = require('firebase-admin/app')
import { getAuth } from 'firebase-admin/auth'
import serviceAccountKey from './serviceAccountKey.json'
const app = initializeApp({
credential: cert(serviceAccountKey),
})
const auth = getAuth(app)
export default auth
When I try to import auth to a middleware.js document I get the above error. Any help would be much appreciated.
import auth from '../firebase'
export const findOrCreateUser = async (req, res, next) => {
try {
const firebaseUser = await auth.verifyIdToken(req.headers.token)
} catch (err) {
console.log(err)
res.status(401).json({
err: 'Invalid or expired token',
})
}
}
For whatever reason, the token generated by jsonwebtoken never expires.
Here is my code so far.
auth.ts Middleware.
// Libs
import { Express, Request, Response, NextFunction } from "express";
import { PassportStatic } from "passport";
import { Strategy as JWTStrategy, ExtractJwt } from "passport-jwt";
// Users
import { usersDB } from "../users";
const setupAuth = (api: Express, passport: PassportStatic) => {
const strategy = new JWTStrategy(
{
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: "123456qwerty",
algorithms: ["HS256"],
},
(payload, cb) => {
try {
const { sub } = payload;
const user = usersDB.find((u) => u.username === sub);
if (user) {
return cb(null, user);
} else {
return cb(null, false);
}
} catch (e) {
return cb(e);
}
}
);
api.use(passport.initialize());
passport.use(strategy);
};
export default setupAuth;
Login route
import { Request, Response } from "express";
import { usersDB, validatePassword } from "../../users";
import { genJWT } from "../../utils/auth";
const login = (req: Request, res: Response) => {
const { username, password } = req.body;
const user = usersDB.find((u) => u.username === username);
if (!user) {
return res
.status(401)
.json({ status: "fail", message: "Invalid username or password" });
}
if (!validatePassword(password, user.salt, user.hash)) {
return res
.status(401)
.json({ status: "fail", message: "Invalid username or password" });
}
const token = genJWT(user.username);
res.status(200).json({ status: "success", token });
};
export default login;
And the jwt token generator
import jwt from "jsonwebtoken";
export const genJWT = (username: string) => {
const token = jwt.sign({ sub: username, iat: Date.now() }, "123456qwerty", {
expiresIn: "1min",
algorithm: "HS256",
});
return token;
};
Then the secured routes
// Lib
import { Express } from "express";
import { PassportStatic } from "passport";
// GET
import root from "./GET/root";
import currentUser from "./GET/current-user";
import privateContent from "./GET/private-content";
// POST
import register from "./POST/register";
import login from "./POST/login";
import logout from "./POST/logout";
const setupRoutes = (api: Express, passport: PassportStatic) => {
api.get("/", root);
api.get(
"/current-user",
passport.authenticate("jwt", { session: false }),
currentUser
);
api.get(
"/private-content",
passport.authenticate("jwt", { session: false }),
privateContent
);
api.post("/register", register);
api.post("/login", login);
api.post("/logout", logout);
};
export default setupRoutes;
So the API is working, able to generate jwt token, able to authenticate with the token. It is able to validate too if I modify the token. But the problem is I can forever use the token. It never expires.
Is there something I missed?
Thanks in advance.
Ok when I removed
iat: Date.now()
from the jwt.sign, now the token does expire. So never put iat, let jsonwebtoken generate it.
When I am trying to verify the accessToken and refresh the token from Google Passport.js OAuth 2. I get this error.
import { OAuth2Client } from "google-auth-library";
const client = new OAuth2Client(OAUTHCLIENTID);
const verify = async () => {
try {
const ticket = await client.verifyIdToken({
idToken: accessToken,
audience: OAUTHCLIENTID,
});
const payload = ticket.getPayload();
const userid = payload["sub"];
} catch (error) {
console.log(error);
}
};
Error: Wrong number of segments in token: ya29.B0ARrdaM-cx6tOHQiDplJxqWiaJtz1F0F6KOuwXL_R_SNdhsFS7m3mieUOP3hEYiCfU4N9-C42SmQkjmcFDN8FEbFNsh9oXVKpH6z1lAImMXsMv6ib2ziZMNIP_aowNC28t6lUb8qqj9XNcNr4tVboNtPSR_TywwNnWUtBVEFTQVRBU0ZRRl91NjFWcWRlTmhHUVk5dUdSbmFRTjNIbnlhdw0232
at OAuth2Client.verifySignedJwtWithCertsAsync
error image
Server Site
Getting Email query from server site, It's not connecting to my client site But it's working on my server site
app.get('/login', async (req, res) => {
const user = req.body;
const accessToken = jwt.sign(user, process.env.ACCESS_TOKEN_SECRET, {
expiresIn: '1d'
});
res.send({ accessToken });
});
Client Ste Login Function Part
This is my client site login part functional and callback part, There my email is showing in console but doesn't work in server which I show in picture.
import axios from 'axios';
import React from 'react';
import { useAuthState, useSignInWithEmailAndPassword } from 'react-firebase-hooks/auth';
import GoogleButton from 'react-google-button';
import { Link, useLocation, useNavigate } from 'react-router-dom';
import auth from '../Firebase.init';
const Login = () => {
const navigate = useNavigate();
const [signInWithEmailAndPassword, loading, error] = useSignInWithEmailAndPassword(auth);
const [user] = useAuthState(auth);
if (user) {
navigate('/');
}
const handleLogin = async e => {
alert('ok');
e.preventDefault();
const email = e.target.email.value;
const password = e.target.password.value;
await signInWithEmailAndPassword(email, password);
const { data } = await axios.post('http://localhost:5000/login', { email })
console.log(data);
console.log(email);
};
}
i wanted to create a login with facebook button, so i created this code:
import { getAuth, signOut,
onAuthStateChanged, FacebookAuthProvider, signInWithPopup } from "https://www.gstatic.com/firebasejs/9.0.2/firebase-auth.js";
const firebaseConfig = {
apiKey: "AIzaSyC3GLIN5TBmCDoTfy0dEOgOdvVvqNw-ric",
authDomain: "auth-project-38aaa.firebaseapp.com",
projectId: "auth-project-38aaa",
storageBucket: "auth-project-38aaa.appspot.com",
messagingSenderId: "431888894254",
appId: "1:431888894254:web:71bb9b250fbb8a21edd2bf",
measurementId: "G-6BBPCJ3814"
};
const app = initializeApp(firebaseConfig);
const auth = getAuth(app);
// login with facebook
const facebookProvider = new FacebookAuthProvider();
const signInWithFacebook = document.querySelector('#facebook-icon');
signInWithFacebook.addEventListener('click', (e) => {
e.preventDefault();
signInWithPopup(auth, facebookProvider).then((result) => {
const user = result.user;
const credential = FacebookAuthProvider.credentialFromResult(result);
const accessToken = credential.accessToken;
})
.catch((error) => {
const errorCode = error.code;
const errorMessage = error.message;
const email = error.email;
const credential = FacebookAuthProvider.credentialFromError(error);
});
});
when i try to login with facebook it gives me this error message:
Facebook has detected that firebase sign in isn't using a secure connection to transfer information.
can you help to solve this problem, please?
For these tests you must run them with an SSL connection, if you are testing on localhost you are probably not using SSL.