Angular + Node-如何使用Auth Guard检查经过身份验证的用户 [英] Angular + Node - How to check for authenticated user using Auth Guard

查看:61
本文介绍了Angular + Node-如何使用Auth Guard检查经过身份验证的用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过向存在jwt标头的后端api发出请求来检查使用情况是否已通过身份验证.如果他们是用户,则返回该用户;否则,将返回未授权的用户.

I am trying to check if the using is Authenticated by making a request to the back-end api with the jwt headers present. If they are the user is returned if not it will return unauthorized.

我的问题是auth.guard被触发并在console.log中返回undefined,因为auth.service尚未完成查询.

The problem i have is the auth.guard is fired and returns undefined in the console.log because the auth.service has not finished querying.

auth.guard.ts

auth.guard.ts

import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { Router } from '@angular/router';
import { AuthService } from '../services/auth.service';

@Injectable()
export class AuthGuard implements CanActivate {


  constructor(private authService: AuthService, private router: Router) { }


  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {

    console.log(this.authService.isAuthenticated());

    if (this.authService.isAuthenticated()) {
      return true;
    }

    this.router.navigate(['/login'], { queryParams: { returnUrl: state.url } });
    return false

  }
}

auth.service.ts

auth.service.ts

import { JwtService } from './jwt.service';
import { Injectable } from '@angular/core';
import { ApiService } from './api.service';
import { UserService } from './user.service';

@Injectable()
export class AuthService {

  user: any;

  constructor(
    private apiService: ApiService,
    private jwtService: JwtService,
    private userService: UserService) {


      this.getAuthenticatedUser().subscribe(res => {
        console.log(res);
        this.user = res;
      }, (error) => {
        this.user = null;
      });


  }

  login(credentials) {

    let endpoint = 'auth/'

    return this.apiService.post(endpoint, credentials)
      .map(res => {
        this.jwtService.saveToken(res.data.jwtToken);
        window.localStorage.setItem('user_id', res.data.user._id);
      });
  }

  logout() {

  }


  isAuthenticated() {
    return this.user;
  }

  getAuthenticatedUser() {

    let endpoint = 'auth/'

    return this.apiService.get(endpoint);
  }

}

什么是实现这一目标的最佳方法?

Whats is the best implementation here to achieve this?

推荐答案

您可以通过添加本地存储会话来简化此操作.用户通过身份验证后,您可以将令牌存储在本地存储中,并在authguard服务中可以检查状态.

You could simplify this by adding a localstorage session. Once the user is authenticated you can store the token in localstorage and in authguard service you can check the status.

例如:

您可以使用以下登录用户信息创建一个类,

You could create a class with login user info as follows,

export class LoginInfo {
    username: string;
    role: string;
    token: string;
    isLoggedIn: boolean;
}

以及您的 authservice.ts

and in your authservice.ts

 login(username: string, password: string): Observable<LoginInfo> {
        const url = `${environment.apiUrl}/token`;
        const params = 'username=' + username + '&password=' + password + '&grant_type=password';
        const headers = new Headers({
            'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'
        });
        return this.http.post(url, params, { headers: headers, withCredentials: true })
            .map((response: Response) => {
                console.log(response);
                const token = response.json() && response.json().access_token;
                if (token) {
                    this.tokenInfo = this.decodeToken(token);
                    this.loggedInfo = new LoginInfo();
                    this.loggedInfo.role = this.tokenInfo.Role;
                    this.loggedInfo.token = token;
                    this.loggedInfo.username = username;
                    this.loggedInfo.isLoggedIn = true;
                    localStorage.setItem('token', token);
                    localStorage.setItem('loggedInfo', JSON.stringify(this.loggedInfo));
                    return this.loggedInfo;
                } else {
                    return this.loggedInfo;
                }
            },
            err => console.log(err));
    }

和您的 auth-guard.service.ts

and in your auth-guard.service.ts

您可以简单地检查令牌并在令牌不存在的情况下重定向到登录

you can simply check the token and redirect to login if the token is not present

canActivate() {
    if (localStorage.getItem('loggedInfo')) {
        return true;
    }
    this.router.navigate(['/login']);
    return false;
}

这篇关于Angular + Node-如何使用Auth Guard检查经过身份验证的用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆