admin管理员组文章数量:1353331
I am trying to authenticate a user from Angular 2 app by calling an express api that provides a JWT token upon success. I have got a doubt to clear.
Do we ask express to set the cookie or is it Angular job to set a cookie with the token
loginUser(email: string, password: string) {
let headers = new Headers({ 'Content-Type': 'application/json'});
let options = new RequestOptions({headers: headers});
let loginInfo = { email: email, password: password };
return this.http.post('/auth/login', JSON.stringify(loginInfo), options)
.do(resp => {
// Do I need to set the cookie from here or it from the backend?
}).catch(error => {
return Observable.of(false);
})
}
I am trying to authenticate a user from Angular 2 app by calling an express api that provides a JWT token upon success. I have got a doubt to clear.
Do we ask express to set the cookie or is it Angular job to set a cookie with the token
loginUser(email: string, password: string) {
let headers = new Headers({ 'Content-Type': 'application/json'});
let options = new RequestOptions({headers: headers});
let loginInfo = { email: email, password: password };
return this.http.post('/auth/login', JSON.stringify(loginInfo), options)
.do(resp => {
// Do I need to set the cookie from here or it from the backend?
}).catch(error => {
return Observable.of(false);
})
}
Share
Improve this question
edited Apr 18, 2017 at 8:14
Jasnan
asked Apr 18, 2017 at 7:28
JasnanJasnan
4,5542 gold badges20 silver badges23 bronze badges
3
- 1 I think Angular will do the job. You can use even a local storage. – Yonas Hailu Commented Apr 18, 2017 at 7:31
- Please keep in mind though, should anyone follow Yonas suggestion. Using local storage would open up what ever you store there to XSS. Never store anyhing in local storage that would be considered a secret. – Reality-Torrent Commented Jan 9, 2020 at 15:08
- @Reality-Torrent how about when done in a cookie? is the app still vulnerable for XSS? – Gel Commented Apr 24, 2020 at 14:12
2 Answers
Reset to default 7You need to do it using Angular. Yes you can use localStorage suggested but better to be use Cookie.
here is a sample of code which i had used in my angular2 application.
login.ts
import { Component, OnInit, Input } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { AjaxLoader } from '../shared/services/ajax-loader';
import { UserService } from '../shared/services/user.service';
import { AuthCookie } from '../shared/services/auth-cookies-handler';
export class LoginComponent implements OnInit {
constructor(
private router: Router,
private route: ActivatedRoute,
private userService: UserService,
private ajaxLoader: AjaxLoader,
private _authCookie: AuthCookie) {
this.ajaxLoader.startLoading();
this.loginInfo = new User();
this.registrationInfo = new User();
}
validateUserAccount(event: Event) {
event.stopPropagation();
event.preventDefault();
this.userService.validateUserAccount(this.loginInfo)
.subscribe(
(data: any) => {
if (data.user === "Invalid") {
this.isInvalidLogin = true;
} else {
this._authCookie.setAuth(JSON.stringify(data));
this.router.navigate(['/home']);
}
},
error => {
if (error.status === 404) {
this.isInvalidLogin = true;
}
this.ajaxLoader.pleteLoading();
},
() => {
this.ajaxLoader.pleteLoading();
}
);
}
}
auth-cookies-handler.ts
import { Injectable } from '@angular/core';
import { Cookie } from 'ng2-cookies/ng2-cookies';
@Injectable()
export class AuthCookie {
constructor() { }
getAuth(): string {
return Cookie.get('id_token');
}
setAuth(value: string): void {
//0.0138889//this accept day not minuts
Cookie.set('id_token', value, 0.0138889);
}
deleteAuth(): void {
Cookie.delete('id_token');
}
}
And in your Component you can use below lines to validate AuthCookie.
if (!_this._authCookie.getAuth()) {
_this.router.navigate(["/login"]);
return false;
}
You have to do it with Angular. I personally use localStorage for that.
Example from my auth service:
login(email: string, password: string) {
const body = { email, password };
return this._http.post('http://localhost:8000/api/auth/authenticate', body)
.map(response => {
const jsonRes = response.json();
if(jsonRes.status == 'success') {
// Auth token
localStorage.setItem('auth_token', jsonRes.data.token);
}
return jsonRes;
})
.catch(error => Observable.throw(error.json()));
}
本文标签: javascriptHow to set a cookie for jwt token in Angular 2Stack Overflow
版权声明:本文标题:javascript - How to set a cookie for jwt token in Angular 2 - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743923963a2562613.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论