'Authorization: Bearer Undefined' - node.js

the Authorization header is always undefined when I am trying to login. Tried setting AOT = false in my angular.json file but to no avail. What is the issue here?
Auth-Interceptor
import { HttpHandler, HttpInterceptor, HttpRequest } from "#angular/common/http";
import { Injectable } from "#angular/core";
import { AuthService } from "./auth.service";
#Injectable()
export class AuthInterceptor implements HttpInterceptor{
constructor(private authService: AuthService){}
intercept(req: HttpRequest<any>, next: HttpHandler){
const authToken = this.authService.getToken();
const authRequest = req.clone({
headers: req.headers.set("Authorization", "Bearer " + authToken)
})
return next.handle(authRequest)
}
}
checkAuth middleware on backend
const jwt = require('jsonwebtoken');
module.exports = (req, res, next) => {
try{
const token = req.headers.authorization.split(" ")[1]
jwt.verify(token, "asderfghtyu")
next();
}
catch(error) {
res.status(401).json({
message: "Authorization failed macha"
})
}
}
auth-service.ts
export class AuthService {
private token: string;
constructor(private http: HttpClient) { }
getToken(){
return this.token;
}
createUser(FullName: string, email: string, role: string, password: string) {
const authData: AuthData = { FullName: FullName, email: email, role: role, password: password }
this.http.post("http://localhost:3300/api/user/signup", authData)
.subscribe(result => {
console.log(result);
})
}
login(email: string, password: string){
this.http.post<{token: string}>("http://localhost:3300/api/user/login", {email: email, password: password})
.subscribe(response=>{
const token = response.token;
this.token = token;
})
}
Here is the auth-service.ts file where getToken() function is present

In your Auth-Interceptor, replace -
const authRequest = req.clone({
headers: req.headers.set("Authorization", "Bearer " + authToken)
})
with -
const authRequest = !authToken ? req : req.clone({
setHeaders: { Authorization: `Bearer ${authToken}` }
});
This will add an Authorization header only if you have a token. If authService.getToken() returns undefined, no Authorization header will be added to the request.

Related

the login was successful but when the next step always appears the message '401' Unauthorized on Vue.js

when the account login endpoint localhost:5000/login a successful message appears, but when I call localhost:5000/status an error message '401' Unauthorized appears as if the login session was not saved
Here My Backend controllers/Auth.js
export const Status = async(req, res) =>{
if(!req.session.userId){
return res.status(401).json({msg: "Mohon login terlebih dahulu"});
}
const user = await User.findOne({
attributes: ['uuid', 'name', 'email', 'number','role'],
where: {
uuid: req.session.userId
}
});
if (!user) return res.status(400).json({msg: "User Tidak Ada"});
res.status(200).json(user);
}
Here My Frontend Auth.vue
import axios from 'axios';
export default{
namespace: true,
state: {
uuid: null,
user: null,
},
mutations: {
SET_UUID(state, uuid){
state.uuid = uuid
},
SET_USER(state, data){
state.user = data
}
},
actions: {
async signIn({ dispatch }, credentials){
let response = await axios.post('login', credentials)
dispatch('attempt', response.data.uuid)
},
async attempt({ commit }, uuid){
commit('SET_UUID', uuid)
try {
let response = await axios.get('status',{
headers: {
'Authorization': 'Bearer ' + uuid
}
})
commit('SET_USER', response.data)
} catch (error) {
commit('SET_UUID', null);
commit('SET_USER', null);
}
}
},
}
My Route route/AuthRoute.js
import express from "express";
import {
Login,
Status,
logOut
} from "../controllers/Atuh.js";
const router = express.Router();
router.get("/status", Status);
router.post("/login", Login);
router.delete("/logout", logOut);
export default router;

Discord api join guild, unauthorized 401 error

I'm trying to authenticate a user with Discord oauth2, then add this user to the guild. I'm also using Passportjs to authenticate the user, so the DiscordStrategy follows as
#Injectable()
export class DiscordStrategy extends PassportStrategy(Strategy) {
constructor(private authService: AuthService) {
super({
clientID: process.env.DISCORD_CLIENT_ID,
clientSecret: process.env.DISCORD_CLIENT_SECRET,
callbackURL: `http://${process.env.HOST}:${process.env.PORT}/auth/discord/callback`,
scope: ['identify', 'guilds', 'guilds.join'],
});
}
async validate(accessToken: string, refreshToken: string, profile: Profile) {
const { id } = profile;
console.log(profile);
const resp = await this.authService.joinGuild(accessToken, id);
console.log(resp);
}
}
and the authService.joinGuild
async joinGuild(accessToken: string, userId: string) {
return this.httpService
.put(
`https://discord.com/api/v8/guilds/${process.env.DISCORD_GUILD_ID}/members/${userId}`,
{
headers: {
Authorization: `Bot ${process.env.DISCORD_BOT_TOKEN}`,
},
body: {
access_token: `${accessToken}`,
},
},
)
.pipe(
catchError((e) => {
throw new HttpException(e.response.data, e.response.status);
}),
)
.pipe(
map((res) => {
console.log(res.data);
return res.data;
}),
)
.toPromise();
}
and my response data is data: { message: '401: Unauthorized', code: 0 }
What am I doing wrong here? I tried to give my bot every permission possible as well. Thanks.

having trouble getting user authorization variables working

In am having trouble passing the token information to my controller for authorization. In the below code, I have console logged the relevant information and I am able to get the token correctly, and the decoded information, but not the req.user information. When I console.log for that information I receive null, and when I console.log for decoded.id, I get undefined. I believe this is what is hanging up my authorization, however I'm not sure what to look at to fix it? Any thoughts very helpful!
Here's a github link:https://github.com/roxanneweber/projectmanager
const jwt = require('jsonwebtoken');
const asyncHandler = require('express-async-handler');
const User = require('../models/userModel');
const protect = asyncHandler(async (req, res, next) => {
let token;
if (
req.headers.authorization &&
req.headers.authorization.startsWith('Bearer')
) {
try {
// Get token from header
token = req.headers.authorization.split(' ')[1];
console.log(token);
// Verify token
const decoded = jwt.verify(token, process.env.JWT_SECRET);
console.log(decoded);
// Get user from token
req.user = await User.findById(decoded.id).select('-password');
console.log(req.user);
console.log(decoded.id);
next();
} catch (error) {
console.log(error);
res.status(401);
throw new Error('Not authorized');
}
}
if (!token) {
res.status(401);
throw new Error('Not authorized');
}
});
module.exports = { protect };
hi i am handling the token like this in my auth.middleware.ts
import jwt from 'jsonwebtoken';
export default function (req, res, next) {
try {
const token = req.headers.authorization.split(' ')[1];
const decodedToken = jwt.verify(token, process.env.JWT_SECRET);
// add userData object to request
req.userData = {
email: decodedToken.email,
userId: decodedToken.userId,
username: decodedToken.username,
role: decodedToken.role,
};
next();
} catch (error) {
return res.status(401).json({
message: 'not authenticated',
});
}
}
then my frontend handles setting the token like this:
import { HttpInterceptor, HttpRequest, HttpHandler, HttpHeaders } from '#angular/common/http';
import { Injectable } from '#angular/core';
import { AuthenticationService } from '../services/authentication.service';
export interface HttpConfig {
body?: any;
headers?: HttpHeaders;
observe?: any;
}
#Injectable()
export class AuthInterceptor implements HttpInterceptor {
constructor(private authService: AuthenticationService) {}
intercept(req: HttpRequest<any>, next: HttpHandler) {
const authToken = this.authService.getToken();
const authRequest = req.clone({
headers: req.headers.set('Authorization', 'Bearer ' + authToken),
});
return next.handle(authRequest);
}
}
then i am using the auth.middleware.ts in my backend route files like this:
import express from 'express';
import authMiddleware from '../middleware/auth.middleware';
import FooController from './foo.controller';
class FooRoutes {
router = express.Router();
fooController = FooController;
constructor() {
this.configureRoutes();
}
configureRoutes() {
this.router.post('/foo/start', authMiddleware, this.fooController.start);
this.router.put('/foo/stop/:id', authMiddleware, this.fooController.stop);
this.router.get('/foo/:userId', authMiddleware, this.fooController.getAll);
this.router.delete('/foo/delete/:id', authMiddleware, this.fooController.delete);
}
}
export default new FooRoutes().router;

jwt prevents me from seeing other users' profiles nodejs, angular

I followed a tutorial on how to create an authentication system. I tried to understand as much as possible while following the tutorial, but there are things that I still don't get, and now I've come to a problem that I've tried many things to fix but the answer is still negative. The problem is that the jwt middleware only allows me to see the profile of the user that I am logged in as, but I don't want that, I want a user to be able to see every other users' profiles, how can I do that? Thanks in advance!!
For the backend, here is my "user.route.js"
router.get("/profile/:id",auth, async (req, res) => {
try {
// request.user is getting fetched from Middleware after token authentication
const user = await User.findById(req.user.id);
res.json(user);
} catch (e) {
res.send({ message: "Error in Fetching user" });
}
});
for front end, here is my "authentication.service.ts"
export interface UserDetails{
username: string
email: string
password: string
firstName: string
lastName: string
exp: number
iat: number
}
interface TokenResponse{
token: string
}
export interface TokenPayload{
username: string
email: string
password: string
firstName: string
lastName: string
}
#Injectable({
providedIn: 'root'
})
export class AuthenticationService {
private token: string
constructor(private http: HttpClient, private router: Router) {}
private saveToken(token: string): void{
localStorage.setItem('usertoken', token)
this.token = token
}
private getToken(): string{
if(!this.token){
this.token = localStorage.getItem('usertoken')
}
return this.token
}
public getUserDetails(): UserDetails{
const token = this.getToken()
let payload
if(token){
payload = token.split('.')[1]
payload = window.atob(payload)
return JSON.parse(payload)
}else{
return null
}
}
public isLoggedIn(): boolean{
const user = this.getUserDetails()
if(user){
return user.exp > Date.now()/ 1000
}
else{
return false
}
}
public login(user: TokenPayload): Observable<any>{
const base = this.http.post('/user/login', user)
const request = base.pipe(
map((data: TokenResponse) => {
if(data.token){
this.saveToken(data.token)
}return data
})
)
return request
}
public register(user: TokenPayload) : Observable<any>{
const base = this.http.post('/user/register', user)
const request = base.pipe(
map((data: TokenResponse) => {
if(data.token){
this.saveToken(data.token)
}
return data
})
)
return request
}
public profile(id): Observable<any>{
const username = this.getUserDetails().username
return this.http.get(`/user/profile/${id}`,
{
headers: {Authorization: `${this.getToken()}`}
})
}
public logout(): void{
this.token = ''
window.localStorage.removeItem('usertoken')
this.router.navigateByUrl('/')
}
}
and this is the "profile.component.ts" code
ngOnInit() {
this.route.params.subscribe(params => {
const id = params.id;
this.auth.profile(id).subscribe(
user => {
this.details = user
},
err => {
console.error(err)
}
)
})
}
req.user up there is filled in by the authorization middleware, it does not use the id from url path like you want. For that you should use req.params.id

Authentication issues using token in angular 6 + node js

I trying to build an Authentication function in angular with node js as my server,
and i have issues with the identification of the token that sent from angular.
I using the angular HttpInterceptor service to handle with the headers, and i am created a middelware function inside my node js. the error that i receiving is:
{headers: HttpHeaders, status: 401, statusText: "Unauthorized"..
Any help will be appreciated
Middleware function
const jwt = require("jsonwebtoken");
module.exports = (req, res, next) => {
try {
const token = req.headers.authorization.split(" ")[1];
jwt.verify(token, "this_is_the_secret");
next();
} catch (error) {
res.status(401).json({ message: "Auth failed!" });
}
};
Middleware implantation
router.post('/orders', checkAuth, function(req,res,next){
Order.create(req.body.order, function(err, createdOrder){
if (err) return next(err)
.then()
Show.findByIdAndUpdate({"_id": req.body.showId}, {"$push":{"takenSeats": req.body.takenSeatsIds}})
.exec(function(err, updatadShow){
if (err) return next(err)
console.log(updatadShow)
})
res.json(createdOrder)
})
})
Auth service in angular
import { Injectable } from "../../../node_modules/#angular/core";
import { HttpClient } from "../../../node_modules/#angular/common/http";
import { AuthData } from "../models/auth-data.model";
#Injectable({ providedIn: "root"})
export class AuthService {
private token: string
signupUrl = "http://localhost:3000/signup";
loginUrl = "http://localhost:3000/login"
constructor(private http: HttpClient){}
getToken(){
return this.token
}
createUser(email: string, password:string){
const authData: AuthData = {email: email, password: password}
this.http.post(this.signupUrl, authData)
.subscribe(response => {
console.log(response)
});
}
login(email: string, password){
const authData: AuthData = {email: email, password: password}
this.http.post<{token: string}>(this.loginUrl,authData)
.subscribe(response => {
console.log(response)
const token = response.token
this.token = token;
console.log("token" + this.token)
});
}
}
AuthInterceptor service
import { HttpInterceptor, HttpRequest, HttpHandler } from "../../../node_modules/#angular/common/http";
import { Injectable } from "../../../node_modules/#angular/core";
import { AuthService } from "./auth.service";
#Injectable()
export class AuthInterceptor implements HttpInterceptor {
constructor(private authService:AuthService){}
intercept(req: HttpRequest<any>, next: HttpHandler) {
const authToken = this.authService.getToken();
const authRequest = req.clone({
headers: req.headers.set('Authorization', "Bearer" + authToken)
})
return next.handle(authRequest)
}
}
[Edit] Sates of the Authentication token
console.log of the login response
{token: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6I…Q3OH0.fCgCuHQkDHHgJHq8LFqeVxLayyr-9U-Y6_23_9FGHkU", expiresIn: 3600}
auth.service.ts:35 tokeneyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6Imlnb3JybzYyMUBnbWFpbC5jb20iLCJ1c2VySWQiOiI1YjU4YjYwYTUxMDkyNDI4Njg1MDM3MzIiLCJpYXQiOjE1MzI1NDc4NzgsImV4cCI6MTUzMjU1MTQ3OH0.fCgCuHQkDHHgJHq8LFqeVxLayyr-9U-Y6_23_9FGHkU
console.log of the req.headers.authorization after posting to a route without implementation of the middleware
BearereyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6Imlnb3JybzYyMUBnbWFpbC5jb20iLCJ1c2VySWQiOiI1YjU4YjYwYTUxMDkyNDI4Njg1MDM3MzIiLCJpYXQiOjE1MzI1NDc4NzgsImV4cCI6MTUzMjU1MTQ3OH0.fCgCuHQkDHHgJHq8LFqeVxLayyr-9U-Y6_23_9FGHkU
console.log of the states inside the middleware function
logging points
const jwt = require("jsonwebtoken");
module.exports = (req, res, next) => {
try {
console.log(" Before the split " + req.headers.authorization)
const token = req.headers.authorization.split(" ")[1];
console.log(" After The split " + req.headers.authorization)
jwt.verify(token, "this_is_the_secret");
next();
} catch (error) {
res.status(401).json({ message: "Auth failed!" });
}
};
Result
Before the split BearereyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6Imlnb3JybzYyMUBnbWFpbC5jb20iLCJ1c2VySWQiOiI1YjU4YjYwYTUxMDkyNDI4Njg1MDM3MzIiLCJpYXQiOjE1MzI1NDc4NzgsImV4cCI6MTUzMjU1MTQ3OH0.fCgCuHQkDHHgJHq8LFqeVxLayyr-9U-Y6_23_9FGHkU
After The split BearereyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6Imlnb3JybzYyMUBnbWFpbC5jb20iLCJ1c2VySWQiOiI1YjU4YjYwYTUxMDkyNDI4Njg1MDM3MzIiLCJpYXQiOjE1MzI1NDc4NzgsImV4cCI6MTUzMjU1MTQ3OH0.fCgCuHQkDHHgJHq8LFqeVxLayyr-9U-Y6_23_9FGHkU
Ok. I found up what was the problem, I didnt put space after the "Bearer "
In the HttpInterceptor

Resources