Unauthorization to protected route when request is made from Angular to NodeAngular HttpClient doesn't send headerHow is an HTTP POST request made in node.js?How to show data from mysql in nodejs with a refresh rateHow to detect a route change in Angular?Angular - Set headers for every requestAngular/RxJs When should I unsubscribe from `Subscription`Angular 4 HTTP GET not including JWT for Authorization in HTTP HeaderAngular2 login service jwt tokenAngular HTTP requestError 405 when sending post request from Angular to Asp.netWhy in React, my axios API call has Authorization Header which contains Bearer <token> but not being authorized and gives 401 error

Who pays for increased security measures on flights to the US?

What is this arch-and-tower near a road?

Should I warn my boss I might take sick leave

PhD: When to quit and move on?

Can a wizard delay learning new spells from leveling up to learn different spells later?

Magento 2 Professional Developer certification study guidelines

How frequently do Russian people still refer to others by their patronymic (отчество)?

What is meant by perfect, imperfect consonance and dissonance?

Why does the Batman "crack his knuckles" in "Batman: Arkham Origins"?

Contributing to a candidate as a Foreign National US Resident?

What can a novel do that film and TV cannot?

Milky way is orbiting around?

Why is the order of my features changed when using readFeatures in OpenLayers v4.6.5?

Has there ever been a cold war other than between the U.S. and the U.S.S.R.?

Maximum cross-correlation coefficient value for time delay estimation

How did שְׁלֹמֹה (shlomo) become Solomon?

Minimizing medical costs with HSA

How serious is plagiarism in a master’s thesis?

Will electrically joined dipoles of different lengths, at right angles, behave as a multiband antenna?

How to respond to someone who condemns behavior similar to what they exhibit?

Why did C++11 make std::string::data() add a null terminating character?

Chess problem: Make a crossword in 3 moves

What is the maximum amount of diamond in one Minecraft game?

how to convert Timestring to seconds



Unauthorization to protected route when request is made from Angular to Node


Angular HttpClient doesn't send headerHow is an HTTP POST request made in node.js?How to show data from mysql in nodejs with a refresh rateHow to detect a route change in Angular?Angular - Set headers for every requestAngular/RxJs When should I unsubscribe from `Subscription`Angular 4 HTTP GET not including JWT for Authorization in HTTP HeaderAngular2 login service jwt tokenAngular HTTP requestError 405 when sending post request from Angular to Asp.netWhy in React, my axios API call has Authorization Header which contains Bearer <token> but not being authorized and gives 401 error






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








0















User.js (backend)



//profile



router.get('/profile', passport.authenticate('jwt', session: false ), (req, res) => 
res.json(
user: req.user,
)
);


Angular



Login Component:



//onLoginSubmit() is a event Based function



onLoginSubmit()
const user =
username:this.username,
password:this.password


this._authService.authenticateUser(user).subscribe(data=>
console.log(data);
this._dataServiceData=data;

if(this._dataServiceData.success)
this._authService.storeUserData(this._dataServiceData.token,this._dataServiceData.user);
this._flahMessage.show('You are now Logged in !',cssClass:'alert-success',timeout:3000);
this._router.navigate(['dashboard']);
else
this._flahMessage.show(this._dataServiceData.msg,cssClass:'alert-danger',timeout:3000);
this._router.navigate(['login']);

);




On success The return of the data of subscribe is an object:



success:true



token:"bearer aGh..........Q2rEjhnZ6XjXVKmwNFoiWFjEJk"



Then if i am accessing the private Route e.g(profile) than it is unauthorizing it



Profile Component



export class ProfileComponent implements OnInit 
private _dataService:any=;
public user=;
constructor(private _authService:AuthService,
private _router:Router)

ngOnInit()
this._authService.getProfile().subscribe(data=>
console.log(data);
this._dataService=data;
this.user = this._dataService.user;
,err=>
console.log(err);
return false;
)





The AuthService(Injected to all)



_/**



authenticateUser(user) **called from loginComponent**
let headers = new HttpHeaders();
headers.append('content-type','application/json');

return this.http.post('http://localhost:8080/users/authenticate',user,headers:headers)



getProfile() **called from profileComponent**
let headers = new HttpHeaders();
this.loadToken();
headers.append('Authorization',this.token);
headers.append('content-type','application/json');

return this.http.get('http://localhost:8080/users/profile',headers:headers)


loadToken()
const token = localStorage.getItem('id_token');
this.token=token;



storeUserData(token,user)
localStorage.setItem('id_token',token);
localStorage.setItem('user',JSON.stringify(user));

this.token = token;
this.user=user;




GitHub Repository link



While i am accessing the protected Route the error is :



Http failure response for http://localhost:8080/users/profile: 401 Unauthorized










share|improve this question






















  • If you look at your headers for the request, you would see that the headers are not set. HttpHeaders is immutable and always returns a new instance.

    – AJT_82
    Mar 25 at 18:48











  • stackoverflow.com/questions/45286764/…

    – AJT_82
    Mar 25 at 18:48











  • Than how can I solve this in getprofile() function

    – Shiva Chandel
    Mar 25 at 18:59











  • Look at the accepted answer in the question I linked, it shows you how :)

    – AJT_82
    Mar 25 at 18:59

















0















User.js (backend)



//profile



router.get('/profile', passport.authenticate('jwt', session: false ), (req, res) => 
res.json(
user: req.user,
)
);


Angular



Login Component:



//onLoginSubmit() is a event Based function



onLoginSubmit()
const user =
username:this.username,
password:this.password


this._authService.authenticateUser(user).subscribe(data=>
console.log(data);
this._dataServiceData=data;

if(this._dataServiceData.success)
this._authService.storeUserData(this._dataServiceData.token,this._dataServiceData.user);
this._flahMessage.show('You are now Logged in !',cssClass:'alert-success',timeout:3000);
this._router.navigate(['dashboard']);
else
this._flahMessage.show(this._dataServiceData.msg,cssClass:'alert-danger',timeout:3000);
this._router.navigate(['login']);

);




On success The return of the data of subscribe is an object:



success:true



token:"bearer aGh..........Q2rEjhnZ6XjXVKmwNFoiWFjEJk"



Then if i am accessing the private Route e.g(profile) than it is unauthorizing it



Profile Component



export class ProfileComponent implements OnInit 
private _dataService:any=;
public user=;
constructor(private _authService:AuthService,
private _router:Router)

ngOnInit()
this._authService.getProfile().subscribe(data=>
console.log(data);
this._dataService=data;
this.user = this._dataService.user;
,err=>
console.log(err);
return false;
)





The AuthService(Injected to all)



_/**



authenticateUser(user) **called from loginComponent**
let headers = new HttpHeaders();
headers.append('content-type','application/json');

return this.http.post('http://localhost:8080/users/authenticate',user,headers:headers)



getProfile() **called from profileComponent**
let headers = new HttpHeaders();
this.loadToken();
headers.append('Authorization',this.token);
headers.append('content-type','application/json');

return this.http.get('http://localhost:8080/users/profile',headers:headers)


loadToken()
const token = localStorage.getItem('id_token');
this.token=token;



storeUserData(token,user)
localStorage.setItem('id_token',token);
localStorage.setItem('user',JSON.stringify(user));

this.token = token;
this.user=user;




GitHub Repository link



While i am accessing the protected Route the error is :



Http failure response for http://localhost:8080/users/profile: 401 Unauthorized










share|improve this question






















  • If you look at your headers for the request, you would see that the headers are not set. HttpHeaders is immutable and always returns a new instance.

    – AJT_82
    Mar 25 at 18:48











  • stackoverflow.com/questions/45286764/…

    – AJT_82
    Mar 25 at 18:48











  • Than how can I solve this in getprofile() function

    – Shiva Chandel
    Mar 25 at 18:59











  • Look at the accepted answer in the question I linked, it shows you how :)

    – AJT_82
    Mar 25 at 18:59













0












0








0








User.js (backend)



//profile



router.get('/profile', passport.authenticate('jwt', session: false ), (req, res) => 
res.json(
user: req.user,
)
);


Angular



Login Component:



//onLoginSubmit() is a event Based function



onLoginSubmit()
const user =
username:this.username,
password:this.password


this._authService.authenticateUser(user).subscribe(data=>
console.log(data);
this._dataServiceData=data;

if(this._dataServiceData.success)
this._authService.storeUserData(this._dataServiceData.token,this._dataServiceData.user);
this._flahMessage.show('You are now Logged in !',cssClass:'alert-success',timeout:3000);
this._router.navigate(['dashboard']);
else
this._flahMessage.show(this._dataServiceData.msg,cssClass:'alert-danger',timeout:3000);
this._router.navigate(['login']);

);




On success The return of the data of subscribe is an object:



success:true



token:"bearer aGh..........Q2rEjhnZ6XjXVKmwNFoiWFjEJk"



Then if i am accessing the private Route e.g(profile) than it is unauthorizing it



Profile Component



export class ProfileComponent implements OnInit 
private _dataService:any=;
public user=;
constructor(private _authService:AuthService,
private _router:Router)

ngOnInit()
this._authService.getProfile().subscribe(data=>
console.log(data);
this._dataService=data;
this.user = this._dataService.user;
,err=>
console.log(err);
return false;
)





The AuthService(Injected to all)



_/**



authenticateUser(user) **called from loginComponent**
let headers = new HttpHeaders();
headers.append('content-type','application/json');

return this.http.post('http://localhost:8080/users/authenticate',user,headers:headers)



getProfile() **called from profileComponent**
let headers = new HttpHeaders();
this.loadToken();
headers.append('Authorization',this.token);
headers.append('content-type','application/json');

return this.http.get('http://localhost:8080/users/profile',headers:headers)


loadToken()
const token = localStorage.getItem('id_token');
this.token=token;



storeUserData(token,user)
localStorage.setItem('id_token',token);
localStorage.setItem('user',JSON.stringify(user));

this.token = token;
this.user=user;




GitHub Repository link



While i am accessing the protected Route the error is :



Http failure response for http://localhost:8080/users/profile: 401 Unauthorized










share|improve this question














User.js (backend)



//profile



router.get('/profile', passport.authenticate('jwt', session: false ), (req, res) => 
res.json(
user: req.user,
)
);


Angular



Login Component:



//onLoginSubmit() is a event Based function



onLoginSubmit()
const user =
username:this.username,
password:this.password


this._authService.authenticateUser(user).subscribe(data=>
console.log(data);
this._dataServiceData=data;

if(this._dataServiceData.success)
this._authService.storeUserData(this._dataServiceData.token,this._dataServiceData.user);
this._flahMessage.show('You are now Logged in !',cssClass:'alert-success',timeout:3000);
this._router.navigate(['dashboard']);
else
this._flahMessage.show(this._dataServiceData.msg,cssClass:'alert-danger',timeout:3000);
this._router.navigate(['login']);

);




On success The return of the data of subscribe is an object:



success:true



token:"bearer aGh..........Q2rEjhnZ6XjXVKmwNFoiWFjEJk"



Then if i am accessing the private Route e.g(profile) than it is unauthorizing it



Profile Component



export class ProfileComponent implements OnInit 
private _dataService:any=;
public user=;
constructor(private _authService:AuthService,
private _router:Router)

ngOnInit()
this._authService.getProfile().subscribe(data=>
console.log(data);
this._dataService=data;
this.user = this._dataService.user;
,err=>
console.log(err);
return false;
)





The AuthService(Injected to all)



_/**



authenticateUser(user) **called from loginComponent**
let headers = new HttpHeaders();
headers.append('content-type','application/json');

return this.http.post('http://localhost:8080/users/authenticate',user,headers:headers)



getProfile() **called from profileComponent**
let headers = new HttpHeaders();
this.loadToken();
headers.append('Authorization',this.token);
headers.append('content-type','application/json');

return this.http.get('http://localhost:8080/users/profile',headers:headers)


loadToken()
const token = localStorage.getItem('id_token');
this.token=token;



storeUserData(token,user)
localStorage.setItem('id_token',token);
localStorage.setItem('user',JSON.stringify(user));

this.token = token;
this.user=user;




GitHub Repository link



While i am accessing the protected Route the error is :



Http failure response for http://localhost:8080/users/profile: 401 Unauthorized







node.js angular jwt authorization mean-stack






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 25 at 18:40









Shiva ChandelShiva Chandel

427 bronze badges




427 bronze badges












  • If you look at your headers for the request, you would see that the headers are not set. HttpHeaders is immutable and always returns a new instance.

    – AJT_82
    Mar 25 at 18:48











  • stackoverflow.com/questions/45286764/…

    – AJT_82
    Mar 25 at 18:48











  • Than how can I solve this in getprofile() function

    – Shiva Chandel
    Mar 25 at 18:59











  • Look at the accepted answer in the question I linked, it shows you how :)

    – AJT_82
    Mar 25 at 18:59

















  • If you look at your headers for the request, you would see that the headers are not set. HttpHeaders is immutable and always returns a new instance.

    – AJT_82
    Mar 25 at 18:48











  • stackoverflow.com/questions/45286764/…

    – AJT_82
    Mar 25 at 18:48











  • Than how can I solve this in getprofile() function

    – Shiva Chandel
    Mar 25 at 18:59











  • Look at the accepted answer in the question I linked, it shows you how :)

    – AJT_82
    Mar 25 at 18:59
















If you look at your headers for the request, you would see that the headers are not set. HttpHeaders is immutable and always returns a new instance.

– AJT_82
Mar 25 at 18:48





If you look at your headers for the request, you would see that the headers are not set. HttpHeaders is immutable and always returns a new instance.

– AJT_82
Mar 25 at 18:48













stackoverflow.com/questions/45286764/…

– AJT_82
Mar 25 at 18:48





stackoverflow.com/questions/45286764/…

– AJT_82
Mar 25 at 18:48













Than how can I solve this in getprofile() function

– Shiva Chandel
Mar 25 at 18:59





Than how can I solve this in getprofile() function

– Shiva Chandel
Mar 25 at 18:59













Look at the accepted answer in the question I linked, it shows you how :)

– AJT_82
Mar 25 at 18:59





Look at the accepted answer in the question I linked, it shows you how :)

– AJT_82
Mar 25 at 18:59












0






active

oldest

votes










Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55344481%2funauthorization-to-protected-route-when-request-is-made-from-angular-to-node%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























0






active

oldest

votes








0






active

oldest

votes









active

oldest

votes






active

oldest

votes




Is this question similar to what you get asked at work? Learn more about asking and sharing private information with your coworkers using Stack Overflow for Teams.







Is this question similar to what you get asked at work? Learn more about asking and sharing private information with your coworkers using Stack Overflow for Teams.



















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55344481%2funauthorization-to-protected-route-when-request-is-made-from-angular-to-node%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

용인 삼성생명 블루밍스 목차 통계 역대 감독 선수단 응원단 경기장 같이 보기 외부 링크 둘러보기 메뉴samsungblueminx.comeh선수 명단용인 삼성생명 블루밍스용인 삼성생명 블루밍스ehsamsungblueminx.comeheheheh

155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해