Я пытаюсь реализовать токен jwt для защиты моих API. Я использую Angular во внешнем интерфейсе при использовании узла и express во внутреннем интерфейсе с mongodb в качестве базы данных. Я проверил мой API, и он, кажется, генерирует токен, но он не удаляется после выхода из системы или даже перед входом в систему. Я по-прежнему могу получить доступ к некоторым маршрутам, которые я не должен делать без входа в систему. Если вы хотите лучше взглянуть на проект, вы можете проверить мой git репозиторий https://github.com/tridibc2/blog-admin-mean. Когда я вхожу в систему, я получаю обратно этот объект:
{
"error": false,
"message": "Login Successful",
"status": 200,
"data": {
"authToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqd3RpZCI6IkJNQllta011IiwiaWF0IjoxNTc4NDk3ODkwODA2LCJleHAiOjE1Nzg1ODQyOTAsInN1YiI6ImF1dGhUb2tlbiIsImlzcyI6ImVkQ2hhdCIsImRhdGEiOnsidXNlcklkIjoiN3FiYVhacVoiLCJmaXJzdE5hbWUiOiJYdHJlbWF0b3IiLCJsYXN0TmFtZSI6ImRlIFNpbHZhIiwiZW1haWwiOiJ4dHJlbWF0b3JAcHViZy5jb20iLCJtb2JpbGVOdW1iZXIiOjk5MDkwOTkwOTl9fQ.KFyJAqaAygxL9IZNitAt5nt2naz8P7I6-JFCHwO4vdc",
"userDetails": {
"userId": "7qbaXZqZ",
"firstName": "Xtremator",
"lastName": "de Silva",
"email": "xtremator@pubg.com",
"mobileNumber": 9909099099
}
}
}
Ниже приведены мои Angular сервисные функции
public getUserInfoFromLocalStorage: any = () =>{
return JSON.parse(localStorage.getItem('userInfo'));
}
public setUserInfoInLocalStorage: any = (data) =>{
localStorage.setItem('userInfo', JSON.stringify(data))
}
public signinFunction(data): Observable<any>{
const params = new HttpParams()
.set('email', data.email)
.set('password', data.password)
return this._http.post(`${this.baseUrl}/login`, params);
}
Ниже приведены мои функции входа и выхода из системы, которые
public logout() {
this.blogpostService.logout().subscribe(
data =>{
console.log(data);
localStorage.removeItem('userInfo');
this.isLoggedIn = false;
this.router.navigate(['/home']);
},
error =>{
console.log("some error occured");
console.log(error.errorMessage);
}
)
}
public signinFunction: any = () => {
if(!this.email){
this.toastr.warning('Enter your email', 'Oops!');
} else if(!this.password){
this.toastr.warning('Enter your password', 'Oops!');
} else {
let data = {
email: this.email,
password: this.password
}
this.blogpostService.signinFunction(data).subscribe((apiResponse) =>{
console.log(apiResponse);
if(apiResponse.status === 200){
Cookie.set('authToken', apiResponse.data.authToken);
Cookie.set('receiverId', apiResponse.data.userDetails.userId);
Cookie.set('receiverName', apiResponse.data.userDetails.firstName + ' ' + apiResponse.data.userDetails.lastName);
this.blogpostService.setUserInfoInLocalStorage(apiResponse.data.userDetails);
this.router.navigate(['/admin/blog']);
} else {
this.toastr.error('Some Error Occured', 'Oops!');
}
}, (err) =>{
this.toastr.error('Some Error Occured', 'Oops!');
}
)} //end of condition
} //end of signinFunction
Ниже приведены функции контроллера моего узла
let loginFunction = (req, res) => {
let findUser = () => {
console.log("findUser");
return new Promise((resolve, reject) => {
if (req.body.email) {
console.log("req body email is there");
console.log(req.body);
UserModel.findOne({ email: req.body.email}, (err, userDetails) => {
if (err) {
console.log(err)
logger.error('Failed To Retrieve User Data', 'userController: findUser()', 10)
let apiResponse = response.generate(true, 'Failed To Find User Details', 500, null)
reject(apiResponse)
} else if (check.isEmpty(userDetails)) {
logger.error('No User Found', 'userController: findUser()', 7)
let apiResponse = response.generate(true, 'No User Details Found', 404, null)
reject(apiResponse)
} else {
logger.info('User Found', 'userController: findUser()', 10)
resolve(userDetails)
}
});
} else {
let apiResponse = response.generate(true, '"email" parameter is missing', 400, null)
reject(apiResponse)
}
})
}
let validatePassword = (retrievedUserDetails) => {
console.log("validatePassword");
return new Promise((resolve, reject) => {
passwordLib.comparePassword(req.body.password, retrievedUserDetails.password, (err, isMatch) => {
if (err) {
console.log(err)
logger.error(err.message, 'userController: validatePassword()', 10)
let apiResponse = response.generate(true, 'Login Failed', 500, null)
reject(apiResponse)
} else if (isMatch) {
let retrievedUserDetailsObj = retrievedUserDetails.toObject()
delete retrievedUserDetailsObj.password
delete retrievedUserDetailsObj._id
delete retrievedUserDetailsObj.__v
delete retrievedUserDetailsObj.createdOn
delete retrievedUserDetailsObj.modifiedOn
resolve(retrievedUserDetailsObj)
} else {
logger.info('Login Failed Due To Invalid Password', 'userController: validatePassword()', 10)
let apiResponse = response.generate(true, 'Wrong Password.Login Failed', 400, null)
reject(apiResponse)
}
})
})
}
let generateToken = (userDetails) => {
console.log("generate token");
return new Promise((resolve, reject) => {
token.generateToken(userDetails, (err, tokenDetails) => {
if (err) {
console.log(err)
let apiResponse = response.generate(true, 'Failed To Generate Token', 500, null)
reject(apiResponse)
} else {
tokenDetails.userId = userDetails.userId
tokenDetails.userDetails = userDetails
resolve(tokenDetails)
}
})
})
}
let saveToken = (tokenDetails) => {
console.log("save token");
return new Promise((resolve, reject) => {
AuthModel.findOne({ userId: tokenDetails.userId }, (err, retrievedTokenDetails) => {
if (err) {
console.log(err.message, 'userController: saveToken', 10)
let apiResponse = response.generate(true, 'Failed To Generate Token', 500, null)
reject(apiResponse)
} else if (check.isEmpty(retrievedTokenDetails)) {
let newAuthToken = new AuthModel({
userId: tokenDetails.userId,
authToken: tokenDetails.token,
tokenSecret: tokenDetails.tokenSecret,
tokenGenerationTime: time.now()
})
newAuthToken.save((err, newTokenDetails) => {
if (err) {
console.log(err)
logger.error(err.message, 'userController: saveToken', 10)
let apiResponse = response.generate(true, 'Failed To Generate Token', 500, null)
reject(apiResponse)
} else {
let responseBody = {
authToken: newTokenDetails.authToken,
userDetails: tokenDetails.userDetails
}
resolve(responseBody)
}
})
} else {
retrievedTokenDetails.authToken = tokenDetails.token
retrievedTokenDetails.tokenSecret = tokenDetails.tokenSecret
retrievedTokenDetails.tokenGenerationTime = time.now()
retrievedTokenDetails.save((err, newTokenDetails) => {
if (err) {
console.log(err)
logger.error(err.message, 'userController: saveToken', 10)
let apiResponse = response.generate(true, 'Failed To Generate Token', 500, null)
reject(apiResponse)
} else {
let responseBody = {
authToken: newTokenDetails.authToken,
userDetails: tokenDetails.userDetails
}
resolve(responseBody)
}
})
}
})
})
}
findUser(req,res)
.then(validatePassword)
.then(generateToken)
.then(saveToken)
.then((resolve) => {
let apiResponse = response.generate(false, 'Login Successful', 200, resolve)
res.status(200)
res.send(apiResponse)
})
.catch((err) => {
console.log("errorhandler");
console.log(err);
res.status(err.status)
res.send(err)
})
}
/**
* function to logout user.
* auth params: userId.
*/
let logout = (req, res) => {
AuthModel.findOneAndRemove({userId: req.user.userId}, (err, result) => {
if (err) {
console.log(err)
logger.error(err.message, 'user Controller: logout', 10)
let apiResponse = response.generate(true, `error occurred: ${err.message}`, 500, null)
res.send(apiResponse)
} else if (check.isEmpty(result)) {
let apiResponse = response.generate(true, 'Already Logged Out or Invalid UserId', 404, null)
res.send(apiResponse)
} else {
let apiResponse = response.generate(false, 'Logged Out Successfully', 200, null)
res.send(apiResponse)
}
})
} // end of the logout function.
маршруты
const routes: Routes = [
{ path: 'login', component: LoginComponent },
{ path: 'admin', component: AdminComponent },
{ path: 'admin/blog', component: ManageBlogsComponent },
{ path: 'admin/blog/create', component: CreateBlogComponent },
{ path: 'admin/blog/edit/:blogId', component: EditBlogComponent }
];