在前端安全存储令牌和敏感信息的方式(角度8)

时间:2019-09-12 08:14:39

标签: angular cookies jwt local-storage session-cookies

我正在使用Angular 8,我想使用cookie存储访问令牌和一些令牌。

因此,我尝试将令牌存储在cookie中,这是我第一次工作,但是当我看到要注销并清除cookie时,它们并不会一直删除,并且会出现401状态错误(未经授权) )出现。我正在使用ngx-cookie-service。您知道一种存储令牌的好方法和安全方法吗?这是我的AuthService:

public login(username: string, password: string) {
    this.username = username;
    this.password = password;
    const params = new URLSearchParams();
    params.append('username', username);
    params.append('password', password);
    params.append('grant_type', 'password');
    const headers = new HttpHeaders({
      'Content-type': 'application/x-www-form-urlencoded; charset=utf-8',
      Authorization: 'Basic ' + btoa('Andricebrain:Aqwzsx1995')
    });

    const options = {
      headers
    };
    this.httpClient
      .post(
        environment.baseUrlOauth + '/oauth/token',
        params.toString(),
        options
      )
      .subscribe(
        data => {
          this.getAuthorities(data);
          console.log(data);

          // this.router.navigate(['/home']);
        },
        error => {
          this.toastr.error('Erreur', 'Login ou mot de passe incorrect');
        }
      );
  }


  getAuthorities(token): boolean {
    const headers = new HttpHeaders({
      'Content-type': 'application/json; charset=utf-8',
      Authorization: 'Basic ' + btoa('Andricebrain:Aqwzsx1995')
    });
    const options = {
      headers
    };
    this.httpClient
      .get(
        environment.baseUrlOauth +
          '/oauth/check_token?token=' +
          token.access_token,
        options
      )
      .toPromise()
      .then(
        data => {
          console.log(token);

          this.saveToken(token, data);
          // return true;
        },
        error => {
          console.log(error);
          alert('Error : get authorities');
          // return false;
        }
      );
    return false;
  }

  saveToken(token, check) {
    const expireDate = new Date().getTime() + 1000 * token.expires_in;
    this.cookie.set('access_token', token.access_token, expireDate);
    this.cookie.set('refresh_token', token.refresh_token);
    this.cookie.set('authorities', check.authorities);
    this.cookie.set('user', JSON.stringify(check.user[0]));
    this.authorities = check.authorities;
    this.user = check.user[0];
    this.router.navigate(['/home']);
  }

// TokenInterceptorService

  intercept(
    req: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    return next.handle(req).pipe(
      tap((ev: HttpEvent<any>) => {
        if (ev instanceof HttpResponse) {
          // console.log('processing response', ev);
          // if (ev.status === 200) {
          //   this.toastr.success('L\'opération s\'est bien passée :-)', 'Succès');
          // }
          //
          // if (ev.status === 201) {
          //   this.toastr.success('Votre objet a bien été créé :-)', 'Succès');
          // }
        }
      }),
      catchError((error: HttpErrorResponse) => {
        if (error.status === 401) {
          if (error.error.error === 'invalid_token') {
            // TODO: Token refreshing
            // this.toastr.info('Nous tentons de vous reconnecter !', 'Reconnexion');
            this.authService.refreshToken();

            const token = this.cookie.get('access_token');
            if (token) {
              // this.toastr.info('Reconnexion', 'Nous avons presque réussi !');
              req = req.clone({
                setHeaders: {
                  'Content-Type': 'application/json',
                  Authorization: 'Bearer ' + token
                }
              });
            }
          } else {
            // Logout from account or do some other stuff
            this.appService.logout();
          }

          if (error.error.error === 'unauthorized') {
            // TODO: Token refreshing
            // this.toastr.info('Vous ne pouvez pas accéder à cette ressource !', 'Accès Refusé');
          }
        }

/*
        if (error.status === 409) {
           this.toastr.error('Une donnée pose problème', 'Conflit');
         }

        if (error.status === 400) {
           this.toastr.error('L\'objet qui a été envoyé est mal construit !', 'Mauvaise requête');
         }
*/

        return throwError(error);
      })
    );
  }

如果您可以找到安全的解决方案,那就太好了

1 个答案:

答案 0 :(得分:0)

关于在浏览器中存储令牌的一个公​​认的答案是使用JWT。 它们可以被加密,签名或两者都被加密。此外,与cookie相比,它们在移动浏览器中的工作效果更好。该库可以帮助您为角度应用程序获得正确的JWT设置。 https://github.com/auth0/angular2-jwt

您的Cookie错误可能是由于未在正确的路径中设置它们造成的。请记住,ngx-cookie会将cookie设置在URL的当前路径上,并且您可能更希望将其设置在根目录上。

import os 
os.environ["CUDA_VISIBLE_DEVICES"] = 0,1  #Will assign GPUs 0 and 1 to the model

勇气!