i have a problem to get my auth User. When I call my route where the current user is in i become no Data in my Vue file.
Backend:
var app = express();
app.use(cors({
methods:['GET','POST'],
credentials: true,
}))
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(cookieParser('test'))
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(session({
secret: 'test',
resave: true,
saveUninitialized: true,
}))
app.use(passport.initialize());
app.use(passport.session());
const port = 3000
app.use(express.static('public'))
//Passport setup
const apiRoutes = require('./apiRoutes')
app.use('/api', apiRoutes)
Passport config:
passport.use(new LocalStrategy(
{
usernameField: 'username',
passwordField: 'password'
},
function(username, password, done) {
userModel.findOne({
username: username
}, (req, res) => {
const match = bcrypt.compare(password, res.password).then(result => {
if (result) {
return done(null, res, {message: 'hat geklappt'})
} else {
return done(null, false, {message: 'hat nicht geklappt'})
}
})
})
}
));
passport.serializeUser(function(user, done) {
done(null, user);
});
passport.deserializeUser(function(user, done) {
done(null, user);
});
Route:
router.get("/", (req, res) => {
let user = req.user;
res.json(
user
);
});
My API is not empty but i cant get the data from Axios get
API:
APi
and my Empty data field:
vue
i dont know what i can do because i have not so much experience and iam really thankfull for help
Thanks :)
set content-type: application/json in the header like this:
it's a sample
var axios = require('axios');
var data = JSON.stringify({"username":"username","password":"password"});
let domain = "localhost";
let port = "3000"
let url = `http://${local}:${port}/api`
var config = {
method: 'post',
url: '',
headers: {
'Content-Type': 'application/json'
},
data : data
};
axios(config)
.then(function (response) {
console.log(JSON.stringify(response.data));
})
.catch(function (error) {
console.log(error);
});
the request is not added to the question, but you can change your request base on my answer
Related
I want to learn how to use passport js, so I created a dummy project with front-end and express back-end, the front-end form is sending a post request to "/emailAndPassword" route on express.
the request is sent successfully but passport.use is not being called and the authenticate middleware is allway redirected to "/failure" route.
Can anybody help me, the code is here:
const express = require("express");
const cors = require("cors");
const passport = require("passport");
const LocalStrategy = require("passport-local").Strategy;
const session = require("express-session");
const app = express();
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(
session({
secret: "secret",
saveUninitialized: false,
resave: false,
})
);
passport.use(
new LocalStrategy(
{ usernameField: "username", passwordField: "password" },
function(username, password, done) {
return done(null, { username: "rest#test.com", password: "some-characters" });
}
)
);
app.use(passport.initialize());
app.use(passport.session());
app.get("/", (req, res) => {
res.send("success");
});
app.get("/failure", (req, res) => {
res.send("failure");
});
app.post(
"/emailAndPassword",
passport.authenticate("local", {
failureRedirect: "/failure",
successRedirect: "/",
}),
(req, res) => {
res.redirect("/")
}
);
app.listen(5000, () => {
console.log("listening...");
});
Try to put passport.use() function below passport.initialize()
Like:
app.use(passport.initialize())
app.use(passport.session())
passport.use(
new LocalStrategy(
{ usernameField: "username", passwordField: "password" },
function(username, password, done) {
return done(null, { username: "rest#test.com", password: "some-characters" });
}
)
)
Every time i try to register a new username and password i get this error. Error Message Im not sure if I am doing something wrong. I am trying to learn the different levels of authentication
my code is below
require('dotenv').config();
const express = require("express");
const bodyParser = require("body-parser");
const ejs = require("ejs");
const mongoose = require("mongoose");
const session = require('express-session');
const passport = require("passport");
const passportLocalMongoose = require("passport-local-mongoose");
const app = express();
app.use(express.static("public"));
app.set('view engine', 'ejs',);
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(session({
secret: 'suckbigd please',
resave: false,
saveUninitialized: true,
cookie: { secure: true }
}));
app.use(passport.initialize());
app.use(passport.session());
mongoose.connect("mongodb://localhost:27017/userDB", { useNewUrlParser: true });
// mongoose.set("useCreateIndex", true);
const userSchema = new mongoose.Schema({
email: String,
password: String
});
userSchema.plugin(passportLocalMongoose);
const User = new mongoose.model("User", userSchema);
passport.use(User.createStrategy());
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
app.get("/", function (req, res) {
res.render("home");
});
app.get("/login", function (req, res) {
res.render("login");
});
app.get("/register", function (req, res) {
res.render("register");
});
app.get("/secrets", function (req, res) {
if (req.isAuthenticated()) {
res.render("secrets");
} else {
res.render("/login");
}
});
app.post("/register", function (req, res) {
User.register({ username: req.body.username }, req.body.password, function (err, user) {
if (err) {
console.log(err);
res.redirect("/register");
} else {
passport.authenticate("local")(req, res, function () {
res.redirect("/secrets");
});
}
});
});
app.post("/login", function (req, res) {
const usetr = new User({
username: req.body.username,
password: req.body.password
});
req.login(user, function (err) {
if (err) {
console.log(err);
} else {
passport.authenticate("local")(req, res, function () {
res.redirect("/secrets");
});
}
})
});
app.listen(3000, function () {
console.log("Server started on port 3000.");
});
I thought I followed the course instructions right. I even watched the video and followed along but I am still getting this error. I am banging my head on the key board. I have been trying to fix this for 4 days now and still nothing. Someone please help.
This works fine when I am running it on Localhost3000(client) and localhost:3005(server). However once I publish my app to Heroku(server) and netlify(client) it for some reason tells me the req.session.steamuser when accessing /user is null even after it has been set in /api/auth/steam/return and I have tested that the req.session.steamuser=req.user accutally work.
Server.js
var express = require('express');
var passport = require('passport');
var session = require('express-session');
var passportSteam = require('passport-steam');
const cors = require("cors");
var SteamStrategy = passportSteam.Strategy;
var app = express();
const corsOptions = {
origin: ["https://stunning-bavarois-0eef55.netlify.app"],
credentials: true, //access-control-allow-credentials:true
methods: ["GET", "POST"],
};
app.use(cors(corsOptions));
passport.serializeUser((user, done) => {
done(null, user);
});
passport.deserializeUser((user, done) => {
done(null, user);
});
passport.use(new SteamStrategy({
returnURL: 'https://temtestt.herokuapp.com/api/auth/steam/return',
realm: 'https://temtestt.herokuapp.com/',
apiKey: 'MY SECRET API KEY'
}, function (identifier, profile, done) {
process.nextTick(function () {
profile.identifier = identifier;
return done(null, profile);
});
}
));
app.use(session({
secret: 'db5910cc8b9dcec166fda1d2c34860b6f8cd932cea641ea39924ed18fe6fc863',
resave: true,
saveUninitialized: true,
cookie: {
SameSite:"none",
maxAge: 3600000,
secure:true
}
}))
// Initiate Strategy
app.use(passport.initialize());
app.use(passport.session());
app.get('/', (req, res) => {
res.status(200);
res.send("Welcome to root URL of Server");
});
app.get("/user", (req, res) => {
if (req.session.steamuser) {
res.status(200).send(req.session.steamuser)
}
else {
res.send(false)
}
})
app.get('/api/auth/steam', passport.authenticate('steam', { failureRedirect: '/' }), function (req, res) {
res.redirect('/')
});
app.get('/api/auth/steam/return', passport.authenticate('steam', { failureRedirect: '/' }), function (req, res) {
req.session.steamuser = req.user;
res.redirect('https://stunning-bavarois-0eef55.netlify.app/')
});
app.listen(process.env.PORT || 3005);
Client
import { useEffect, useState } from 'react';
import './App.css';
import axios from 'axios';
function App() {
const [user,setUser]=useState(null);
useEffect(()=>{
async function getUser(){
const data = await axios.get("https://temtestt.herokuapp.com/user",{withCredentials:true});
setUser(data.data);
}
getUser();
},[]);
return (
<div className="App">
<h1>Hello</h1>
{(user===false||user===null)?<><p>Please log in</p>Login</>:<p>{user.displayName}</p>}
</div>
);
}
export default App;
As mentioned already it works fine when I do with localhost and returns correct values. But when I try with netlify and heroku it almost seems like it doesn't recognize the session key or something.
I tried to record sessions in the database through sequelize, to make it serverless, but req.user is always undefined, I tried every manual which I found on the internet, I do not understand why it not working.
I tried passport.js manual, express manuals, github gists.
Records in the database are successfully created, on successful authentication, but when I try hit /graphql endpoint, it does not fill req.user with user.
req.user should be restored based on session hash which is stored in database.
#!/usr/bin/env node
import express from 'express';
import session from 'express-session';
import { ApolloServer } from 'apollo-server-express';
import { typeDefs, resolvers } from './graphql';
import orm from './orm';
import compose from './dataloader/status.dataloader';
import passport from 'passport';
import { Strategy as GitHubStrategy } from 'passport-github';
import cors from 'cors';
const app = express();
const server = new ApolloServer({
typeDefs,
resolvers,
context: ({ req }) => {
const user = req.user;
console.log({ user });
return {
user,
orm,
dataloader: compose(orm),
};
},
});
passport.use(
new GitHubStrategy(
{
clientID: process.env.GITHUB_CLIENT_ID,
clientSecret: process.env.GITHUB_CLIENT_SECRET,
callbackURL: `/auth/github/callback`,
},
async (accessToken, refreshToken, profile, done) => {
const { provider, id: externalId, profileUrl, username, displayName, photos } = profile;
const photo = photos && photos[0] && photos[0].value;
const user = await orm.User.findOne({
include: [
{
attributes: [],
model: orm.UserProvider,
where: {
provider,
externalId,
},
},
],
raw: true,
}).then(async (v) => {
if (null !== v) {
return v;
}
v = await orm.User.create({
displayName,
photo,
});
await orm.UserProvider.create({
provider,
internalId: v.id,
externalId,
username,
profileUrl,
});
return v;
})
const session = await orm.UserSession.create({
internalId: user.id,
hash: accessToken,
});
return done(null, session);
}
)
);
passport.serializeUser(({ hash }, done) => {
console.log({ hash });
done(null, hash);
});
passport.deserializeUser(async (hash, done) => {
console.log({ hash });
const user = await orm.User.findOne({
include: [
{
attributes: [],
model: orm.UserSession,
where: {
hash,
},
},
],
raw: true,
});
done(null, user);
});
app.use(
cors({
origin: "*",
methods: "GET,POST",
preflightContinue: false,
optionsSuccessStatus: 204,
credentials: true,
})
);
app.use(session({ secret: 'test' }));
app.use(passport.initialize());
app.use(passport.session());
app.get(
'/auth/github',
passport.authenticate('github', { session: true })
);
app.get(
'/auth/github/callback',
passport.authenticate('github', { session: true }),
(req, res) => res.redirect('/')
);
app.use('/graphql', passport.authenticate('session', { session: true }));
// (req, res, next) => {
// debugger;
// // passport.
// console.log({
// req,
// session: JSON.stringify(req.session, ',', 4),
// cookie: JSON.stringify(req.cookie),
// user: req.user,
// });
// return next();
// });
server.applyMiddleware({ app, path: '/graphql' });
app
.listen(process.env.PORT, () => {
console.log(`GraphQL ready on: http://localhost:${process.env.PORT}/graphql`);
});
I have an express application behind CloudFlare. In development, the Set-Cookie header gets passed on login, but behind CloudFlare, the Set-Cookie header is not passed. Any suggestions? My config is:
```
import passport from 'passport';
import cookieParser from 'cookie-parser';
import session from 'express-session';
import { Strategy as LocalStrategy } from 'passport-local';
import localPassport from '../../db/sequelize/passport';
const secret = 'foo';
const authenticationMiddleware = (req, res, next) => {
console.log('authenticated', req.isAuthenticated());
if (req.isAuthenticated()) {
next();
} else if (req.url.includes('/rest/')) {
res.status(401).send('Unauthorized');
} else {
res.status(302).redirect('/admin/login');
}
};
const sessionSecurity = (app) => {
app.set('trust proxy', 1);
app.use(cookieParser(secret));
app.use(
session({
secret,
proxy: true,
saveUninitialized: false,
resave: false,
maxAge: null,
cookie: {
path: '/admin',
secure: process.env.NODE_ENV === 'production',
},
}),
); // session secret
app.use(passport.initialize());
app.use(passport.session());
passport.use(new LocalStrategy(localPassport.local));
passport.serializeUser((user, done) => {
done(null, user.id);
});
passport.deserializeUser(localPassport.deserializeUser);
app.post('/admin/login', (req, res, next) => {
passport.authenticate('local', (authErr, user) => {
if (authErr) return next(new Error(authErr));
if (!user) {
return res.sendStatus(401);
}
return req.logIn(user, (loginErr) => {
if (loginErr) return res.sendStatus(401);
return res.sendStatus(200);
});
})(req, res, next);
});
app.post('/admin/logout', (req, res) => {
req.logOut();
req.session.destroy(() => {
res
.clearCookie('connect.sid', { path: '/admin' })
.sendStatus(200);
});
});
app.get('/admin/rest/*', authenticationMiddleware);
app.get('/admin/rest/status', (req, res) => {
res.sendStatus(200);
});
};
```
This was caused because the server settings where set to cookie secure and the connection between CloudFlare and my server were not.
In setting of cloudflare (crypto tab), I turned on "Authenticated Origin Pulls" and in "app.js" (from my app) add this app.set('trust proxy', 1);
before app.use(session({...}) and my problem solved.