Angular 4 Cookie vs Token 认证

相关链接:
Angular 4 Authentication With Auth0
Serverless 架构应用开发:基于 Auth0 授权的 Serverless 应用登录
原文链接:
Angular 4 Cookie vs Token Authentication

基于Cookie的认证 -
基于cookie的认证是默认的,且是有状态的(stateful)。
有状态的(Stateful) - 保存与跟踪用于当前交易的、之前存储的 信息。
基于HTTP cookie的有状态(Stateful)服务,使用HTTP传输协议 与 其传递cookies的能力,常用作会话上下文。

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, path?: 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, 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);
  }

  //delete cookie
  //Syntax - delete( name: string, path?: string, domain?: string ): void;
  deleteCookie(key: string){
    return this.cookieService.delete(key);
  }
}

Cookies 局限性 –
一个Web服务器只存储20个左右的Cookie,并且一个Cookie最大信息量不能超过4KB,如果您指定max-age属性,它将是持续到无限期。

基于Token的认证 –
由于REST风格的Web API,SPA等的应用,基于Token的认证在过去几年得到了发展。 基于Token的认证是无状态的(Stateless)。

无状态 – 每一笔交易(transaction)都被执行,就好像它是第一次完成的一样,而且不像Cookie要存储用于当前交易的信息。

基于Token 的认证步骤 -
用户输入登录凭证==》Server Side验证登录凭证==》验证成功返回Token到Client Side==》Client Side存储Token到local storage/session/cookie中
示例

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);
}
基于令牌的身份验证的优势 -
1, 无状态,
2,可扩展
3,解耦(Decoupled)
4,JWT被放置在浏览器本地存储中
5,保护跨域和CORS
6,数据存储在JWT中
7,保护XSS和XSRF保护

Tokens保存在什么地方?
这取决于你,你想在哪里存储JWT(Json web token)。 JWT放置在您的浏览器本地存储中。

示例 - 认证 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();
  }
}

这里写图片描述

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值