Angular 4 Cookie vs Token 认证
基于Cookie的认证 - Cookie -示例1 import { Component,OnInit } from '@angular/core';
import { CookieService } from 'ngx-cookie-service';
@Component({
selector: 'app-root',templateUrl: './app.component.html'
})
export class AppComponent implements OnInit {
cookieValue = 'default';
constructor( private cookieService: CookieService ) { }
ngOnInit(): void {
//set Cookie
//Syntax- set( name: string,value: string,expires?: number | Date,path?: string,domain?: string,secure?: boolean ): void;
this.cookieService.set( 'appCookie','This is hello apps.' );
}
//set Cookie
//Syntax - get( name: string ): string;
getCookie(key: string){
return this.cookieService.get(key);
}
//check Cookie
//Syntax - check( name: string ): boolean;
checkCookie(key: string){
return this.cookieService.check(key);
}
//get All Cookie
//Syntax - getAll(): {};
getAllCookie(){
return this.cookieService.getAll();
}
//delete cookie
//Syntax - delete( name: string,domain?: string ): void;
deleteCookie(key: string){
return this.cookieService.delete(key);
}
//delete All cookie
//Syntax - deleteAll( path?: string,domain?: string ): void;
deleteAllCookie(){
return this.cookieService.deleteAll();
}
}
Cookie - 示例2 import { Component,OnInit } from '@angular/core';
import { Cookie } from 'ng2-cookies/ng2-cookies';
export class AppComponent implements OnInit {
constructor( private cookieService: CookieService ) { }
ngOnInit(): void {
//set Cookie
//Syntax- set( name: string,'This is hello apps.' );
}
//set Cookie
//Syntax - get( name: string ): string;
getCookie(key: string){
return this.cookieService.get(key);
}
//delete cookie
//Syntax - delete( name: string,domain?: string ): void;
deleteCookie(key: string){
return this.cookieService.delete(key);
}
}
Cookies 局限性 – 基于Token的认证 – 无状态 – 每一笔交易(transaction)都被执行,就好像它是第一次完成的一样,而且不像Cookie要存储用于当前交易的信息。 基于Token 的认证步骤 - private _setSession(authResult,profile) {
//Save session data and update login status subject
localStorage.setItem('access_token',authResult.accessToken);
localStorage.setItem('id_token',authResult.idToken);
localStorage.setItem('userProfile',JSON.stringify(profile));
this.setLoggedIn(true);
}
Tokens保存在什么地方? 示例 - 认证 Service [auth.service.ts] import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { AUTH_CONFIG } from './auth0-variables';
import { tokenNotExpired } from 'angular2-jwt';
import { UserProfile } from './profile.model';
// Avoid name not found warnings
declare var auth0: any;
@Injectable()
export class AuthService {
// Create Auth0 web auth instance
// @TODO: Update AUTH_CONFIG and remove .example extension in src/app/auth/auth0-variables.ts.example
auth0 = new auth0.WebAuth({
clientID: AUTH_CONFIG.CLIENT_ID,domain: AUTH_CONFIG.CLIENT_DOMAIN
});
userProfile: UserProfile;
// Create a stream of logged in status to communicate throughout app
loggedIn: boolean;
loggedIn$ = new BehaviorSubject<boolean>(this.loggedIn);
constructor(private router: Router) {
// If authenticated,set local profile property and update login status subject
if (this.authenticated) {
this.userProfile = JSON.parse(localStorage.getItem('profile'));
this.setLoggedIn(true);
}
}
setLoggedIn(value: boolean) {
// Update login status subject
this.loggedIn$.next(value);
this.loggedIn = value;
}
login() {
// Auth0 authorize request
// Note: nonce is automatically generated: https://auth0.com/docs/libraries/auth0js/v8#using-nonce
this.auth0.authorize({
responseType: 'token id_token',redirectUri: AUTH_CONFIG.REDIRECT,audience: AUTH_CONFIG.AUDIENCE,scope: AUTH_CONFIG.SCOPE
});
}
handleAuth() {
// When Auth0 hash parsed,get profile
this.auth0.parseHash((err,authResult) => { if (authResult && authResult.accessToken && authResult.idToken) { window.location.hash = ''; this._getProfile(authResult); this.router.navigate(['/']); } else if (err) { this.router.navigate(['/']); console.error(`Error: ${err.error}`); } }); } private _getProfile(authResult) { // Use access token to retrieve user's profile and set session this.auth0.client.userInfo(authResult.accessToken,(err,profile) => { this._setSession(authResult,profile); }); } private _setSession(authResult,profile) { // Save session data and update login status subject localStorage.setItem('access_token',authResult.accessToken); localStorage.setItem('id_token',authResult.idToken); localStorage.setItem('profile',JSON.stringify(profile)); this.userProfile = profile; this.setLoggedIn(true); } logout() { // Remove tokens and profile and update login status subject localStorage.removeItem('access_token'); localStorage.removeItem('id_token'); localStorage.removeItem('profile'); this.userProfile = undefined; this.setLoggedIn(false); } get authenticated() { // Check if there's an unexpired access token return tokenNotExpired('access_token'); } }
在组件中使用 AuthService – //Use of AuthService in the Component Page.
import { Component } from '@angular/core';
import { AuthService } from './auth/auth.service';
export class Login {
constructor(private authService: AuthService) {
// Check for authentication and handle,if hash present.
authService.handleAuth();
}
} (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |