Open HimanshuZade10 opened 6 years ago
@HimanshuZade10 You need to compare your code to the Github Files, there have been several changes to the Files since the Video. I submitted the changes to Upgrade to Angular 5 and fix other errors. This is the Passport.Js file that is in the Github Repo for Brad. As you follow the videos, check your files to the files in the repo for any changes. I can see from the CODE you posted you are using old procedures. For EXAMPLE at User.getUserByID(jwt_payload.data._id. (err,user) => (it is not payload.sub anymore)
const ExtractJwt = require('passport-jwt').ExtractJwt;
const User = require('../models/user');
const config = require('../config/database');
module.exports = function(passport) {
let opts = {};
opts.jwtFromRequest = ExtractJwt.fromAuthHeaderWithScheme('jwt');
opts.secretOrKey = config.secret;
passport.use(new JwtStrategy(opts, (jwt_payload, done) => {
User.getUserById(jwt_payload.data._id, (err, user) => {
if(err) {
return done(err, false);
}
if(user) {
return done(null, user);
} else {
return done(null, false);
}
});
}));
}```
@HimanshuZade10 .... hi......even i am struck in this getting unauthorized because in passport.js the function in passport is working and i can't get payload details. i.e: console.log(jwt_payload); i think we r struck in this below code: passport.use(new JwtStrategy(opts, (jwt_payload, done) => { User.getUserById(jwt_payload.data._id, (err, user) => { if(err) { return done(err, false); } if(user) { return done(null, user); } else { return done(null, false); } });
})); }
and the your code version of passport.js is older one User.getUserById({id:jwt_payload.sub}, function(err, user) here,you are using id has a jwt_payload and your specifing user:id in user.js,even i have a confusion with this.... change this to User.getUserById(jwt_payload._data._id, (err, user) => actually we want to know what is payload is giving but it's not giving payload details
@tomcatbuzz thanks for your help... @Vinay-Shankar... yeah our problem are same and i used .sub because it worked for me and, even i tested it with new changes and all the suggestion but it was not working.... still working on the code... let's see...
@HimanshuZade10 unauthorized in authenicate issue is solved jwt_payload is giving in the form of data i.e...code: payload { data: { _id: '5ac6222d0d6b1f41c8ed386b', name: 'abc', email: 'abcd@gmail.com', username: 'abcd18', password: '$2a$10$Us1XSSg9o9OfGrYhrotE8.3wwreUnDSjPLm4zH4Li0cYiRTpzXM7O', __v: 0 }, iat: 1522937438, exp: 1522937738 } so.....please change code in passport.js const JwtStrategy = require('passport-jwt').Strategy; const ExtractJwt = require('passport-jwt').ExtractJwt; const User = require('../models/user'); const config = require('../config/database');
module.exports = function(passport) { let opts = {}; opts.jwtFromRequest = ExtractJwt.fromAuthHeaderWithScheme('jwt'); opts.secretOrKey = config.secret; passport.use(new JwtStrategy(opts, (jwt_payload, done) => { //console.log('payload received', jwt_payload); User.getUserById(jwt_payload.data._id, (err, user) => { if(err) { return done(err, false); }
if(user) { return done(null, user); } else { return done(null, false); } }); })); }
i am also getting same error when i with postman its working but after making request to /profile its giving error unauthorised
i found the solution after struggling it with 1day . add the following things in your auth.service.ts
file.
import httpheaders like this import { HttpClient,HttpHeaders} from '@angular/common/http';
then add the following also
getProfile(){
this.loadToken();
let headers = new HttpHeaders({
'Authorization':this.authToken,
'Content-Type':'application/json'
});
return this.http.get('http://localhost:3000/users/profile',{headers:headers});
}
no need to add map operator
in updated angular and use Http
is replaced with HttpClient
.
the problem was service file was not able to send the token
in header file in http so it was giving responce as unauthorizes
.it got solved by above method.
Thanks @mukeshphulwani66, I had the same issue, for some reason appending to the headers like Brad does in the tutorial didn't work, instead I initialised the header like you did and it works
i did as the author, but i can still have the problem, i am not sure the config.secret, but i think it does not any have a effect in code
const JwtStrategy = require('passport-jwt').Strategy;
const ExtractJwt = require('passport-jwt').ExtractJwt;
const User = require('../models/user');
const config = require('../config/databases');
module.exports = function(passport) {
let opts = {};
opts.jwtFromRequest = ExtractJwt.fromAuthHeaderWithScheme('jwt');
opts.secretOrKey = config.secret;
passport.use(new JwtStrategy(opts, (jwt_payload, done) => {
console.log('jwt_payload: ' + jwt_payload)
User.getUserById(jwt_payload.data._id, (err, user) => {
if (err) {
return done(err, false);
}
if (user) {
return done(null, user);
} else {
return done(null, false);
}
});
}));
}
i found my error in
before
res.json({
code: '0000',
token: 'JWT' + token,
user: {
id: user._id,
name: user.name,
email: user.eamil,
username: user.username
}
});
after
res.json({
code: '0000',
token: 'JWT ' + token, // you need have a blank
user: {
id: user._id,
name: user.name,
email: user.eamil,
username: user.username
}
});
The repeated "Unauthorized" problem for video 4 took me half a day to work through. I had 2 problems:
passport.js:
const JwtStrategy = require('passport-jwt').Strategy;
const ExtractJwt = require('passport-jwt').ExtractJwt;
const User = require('../models/User');
const config = require('../config/database.js');
module.exports = function(passport){
let opts = {};
opts.jwtFromRequest = ExtractJwt.fromAuthHeaderWithScheme("jwt");
opts.secretOrKey = config.secret;
passport.use(new JwtStrategy(opts, (jwt_payload, done) => {
console.log(jwt_payload);
User.getUserById(jwt_payload.data._id, (err, user) => {
if(err){
return done(err, false);
}
if(user){
return done(null, user);
} else {
return done(null, false);
}
});
}));
}
and Users.js:
const express = require('express');
const router = express.Router();
const passport = require('passport');
const User = require('../models/User');
const config = require('../config/database');
const JWT = require('jsonwebtoken');
// register
router.post('/register', (req, res, next) => {
let newUser = new User({
name: req.body.name,
email: req.body.email,
username: req.body.username,
password: req.body.password
});
User.addUser(newUser, (err, user) => {
if(err){
res.json({success: false, msg: 'Failed to register user.'});
} else {
res.json({success: true, msg: 'User registered'});
}
});
});
// authenticate
router.post('/authenticate', (req, res, next) => {
const username = req.body.username;
const password = req.body.password;
User.getUserByUsername(username, (err, user) => {
if(err) throw err;
if(!user){
return res.json({success: false, msg: 'User not found'});
}
User.comparePassword(password, user.password, (err, isMatch) => {
if(err) throw err;
if(isMatch){
const token = JWT.sign({data: user}, config.secret, {
expiresIn: 604800 // 1 week
});
res.json({
success: true,
token: 'JWT ' + token,
user: {
id: user._id,
name: user.name,
username: user.username,
email: user.email
}
});
} else {
return res.json({success: false, msg: 'User not authenicated'});
}
});
});
});
// profile
router.get('/profile', passport.authenticate('jwt', {session:false}), (req, res, next) => {
res.json({user: req.user});
});
module.exports = router;
Hope this helps someone else.
Thanks, Brad, all in all, excellent series and tutorials.
I am facing same issue .getting error unauthorized
my code auth.service.ts :
getProfessionalProfile(){ let headers = new Headers(); console.log('before calling loadProfessionalToken method'); this.loadProfessionalToken(); console.log('after calling loadpPofessionalToken method'); headers.append('Authorization', this.professionaltoken); headers.append('Content-Type', 'application/json');
return this.http.get('http://localhost:9090/professionals/professionalprofile', { headers: headers })
.map(res => res.json());
} storeProfessionalData(token, user) { localStorage.setItem('id_token', token); localStorage.setItem('professional', JSON.stringify(user)); this.professionaltoken = token; this.professional = user; }
loggedInProfessional() { return tokenNotExpired('id_token'); }
loadProfessionalToken() { const token = localStorage.getItem('id_token'); this.professionaltoken = token; console.log('loaded professionaltoken' + token); }
logoutProfessional() { this.professionaltoken = null; this.professional = null; localStorage.clear(); }
And Passport.js file: module.exports = function(passport) { let opts = {}; // options is an object literal containing options to control how the token is extracted from the request or verified. opts.jwtFromRequest = ExtractJwt.fromAuthHeaderWithScheme('jwt'); opts.secretOrKey = config.secret;
// Passport uses the concept of strategies to authenticate requests.
passport.use(new JwtStrategy(opts, (jwt_payload, done) => {
console.log("JWT payload recieved", jwt_payload);
Professional.getProfessionalById(jwt_payload.data._id, (err, professional) => {
if (err) {
return done(err, false);
}
if (professional) {
console.log("inside get professional by id");
return done(null, professional);
} else {
return done(null, false);
}
});
}
Please Help me. Thanks in advanced
tried everything suggested earlier regarding this issue that's y thought of name adding it as a new issue... i tried everything even console.log(jwt_payload) but in postman i m getting unauthorized and terminal is not showing any error following is my passport.js file `const JwtStrategy=require('passport-jwt').Strategy; const ExtractJwt=require('passport-jwt').ExtractJwt; const User=require('../model/RegisterSchema'); const config=require('../config/database');
module.exports=function(passport){ let opts={}; opts.jwtFromRequest = ExtractJwt.fromAuthHeaderWithScheme('jwt'); opts.secretOrKey = config.secret; passport.use(new JwtStrategy(opts,(jwt_payload, done)=> { console.log(jwt_payload); User.getUserById({id:jwt_payload.sub}, function(err, user) { if (err) { return done(err, false); } if (user) { return done(null, user); } else { return done(null, false); } }); })); }
and my user.js code
router.post('/authenticate',(req,res,next)=>{ const username=req.body.username; const password=req.body.password;User.getUserByUsername(username,(err,user)=>{ if(err) throw err; if(!user){ return res.json({sucess:false,msg:'User not found'}); } User.comparePassword(password,user.password,(err,isMatch)=>{ if(err) throw err; if(isMatch){ const token=jwt.sign(user.toJSON(),config.secret,{ expiresIn:604800 //1week }); res.json({ sucess:true, token:'JWT'+token, user:{ id:user._id, name:user.name, username:user.username, email:user.email } }); }else{ return res.json({sucess:false,msg:'Wrong password'}); } }); }); });
router.get('/profile',passport.authenticate('jwt',{session:false}), (req, res, next) =>{ res.json({user:req.user}); });
module.exports=router;`