Javascript 如何使用oauth节点js对angular 2进行身份验证

Javascript 如何使用oauth节点js对angular 2进行身份验证,javascript,node.js,facebook,angular,oauth,Javascript,Node.js,Facebook,Angular,Oauth,我对我的网站有这个要求。该网站将是一个水疗与角2。 我想要的是,用户可以使用Google、Facebook、Twitter oauth登录 我可以在节点服务器上设置oauth,但问题是如何允许通过angular 2应用程序登录 在angular 2应用程序中,如果用户单击facebook登录选项,我无法重定向用户,因为我将丢失应用程序的状态 我不知道这是否是一个非常初级的问题。有谁能帮助我了解angular 2+节点oauth中发生的情况吗?您需要在angular应用程序中设置路由,以处理应用程

我对我的网站有这个要求。该网站将是一个水疗与角2。 我想要的是,用户可以使用Google、Facebook、Twitter oauth登录

我可以在节点服务器上设置oauth,但问题是如何允许通过angular 2应用程序登录

在angular 2应用程序中,如果用户单击facebook登录选项,我无法重定向用户,因为我将丢失应用程序的状态


我不知道这是否是一个非常初级的问题。有谁能帮助我了解angular 2+节点oauth中发生的情况吗?您需要在angular应用程序中设置路由,以处理应用程序的前端。然后创建一个服务来处理应用程序的auth0身份验证

这是在应用程序中设置安全路由集和公共路由集的概述。一旦有人使用oauth登录,他们将被转发到安全路由

所以从这里开始就是路线。我们将在app.routing.ts文件中指定一个安全和公共的

路线

const APP_ROUTES: Routes = [
    { path: '', redirectTo: '/home', pathMatch: 'full', },
    { path: '', component: PublicComponent, data: { title: 'Public Views' }, children: PUBLIC_ROUTES },
    { path: '', component: SecureComponent, canActivate: [Guard], data: { title: 'Secure Views' }, children: SECURE_ROUTES }
];
好的,现在你有了。您可以创建一个模板目录。在内部创建secure.component和public.component。然后,我创建了一个名为secure的目录和一个名为public的目录,我将所有依赖于身份验证级别的组件放在其中,以访问它们。我还将它们的路由添加到这些目录中的一个文件中,以使所有内容保持独立

请注意,在我上面的路线中,我在安全面板上设置了[Guard]。这将阻止任何人在没有身份验证的情况下进入安全路由

这是一个关于那个警卫的例子

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

@Injectable()
export class Guard implements CanActivate {

    constructor(protected router: Router, protected auth: Auth ) {}

     canActivate() {
        if (localStorage.getItem('access_token')) {
            // logged in so return true
            return true;
        }
        // not logged in so redirect to login page
        this.router.navigate(['/home']);
        return false;
    }
}
现在我们有了警卫,我们的路线已经安全了。我们可以设置
auth0
客户端

使用从auth0获得的凭据创建配置文件

interface AuthConfiguration {
    clientID: string,
    domain: string,
    callbackURL: string
}

export const myConfig: AuthConfiguration = {
    clientID: 'clietnifherefromauth0',
    domain: 'username.auth0.com',
    // You may need to change this!
    callbackURL: 'http://localhost:3000/endpoint/'
};
然后去验证某人的身份。接收他们的数据并将令牌及其数据保存到本地存储器。还提供注销功能和检查以确保他们已登录

import { Injectable }                      from '@angular/core';
import { tokenNotExpired, JwtHelper }      from 'angular2-jwt';
import { Router }                          from '@angular/router';
import { myConfig }                        from './auth.config';

declare var Auth0Lock: any;

var options = {
    theme: {
    logo: '/img/logo.png',
    primaryColor: '#779476'
    },
    languageDictionary: {
    emailInputPlaceholder: "email@example.com",
    title: "Login or SignUp"
  }, 
 };

@Injectable()
export class Auth {
  lock = new Auth0Lock(myConfig.clientID, myConfig.domain, options, {});
  userProfile: Object;
  constructor(private router: Router) {
    this.userProfile = JSON.parse(localStorage.getItem('profile'));
    this.lock.on('authenticated', (authResult: any) => {
      localStorage.setItem('access_token', authResult.idToken);
      this.lock.getProfile(authResult.idToken, (error: any, profile: any) => {
        if (error) {
          console.log(error);
          return;
        }
        localStorage.setItem('profile', JSON.stringify(profile));
        this.userProfile = profile;
        this.router.navigateByUrl('/CHANGETHISTOYOURROUTE');
      });
      this.lock.hide();
    });
  }

  public login() {
    this.lock.show();
  }

  private get accessToken(): string {
        return localStorage.getItem('access_token');
    }

  public authenticated(): boolean {
    try {
        var jwtHelper: JwtHelper = new JwtHelper();
        var token = this.accessToken;
        if (jwtHelper.isTokenExpired(token))
            return false;
        return true;
    }
    catch (err) {
        return false;
    }
  }

  public logout() {
    localStorage.removeItem('profile');
    localStorage.removeItem('access_token');
    this.userProfile = undefined;
    this.router.navigateByUrl('/home');
  };
}
确保进入auth0仪表板并选择所需的社交链接。就你而言,facebook、twitter和谷歌。然后,当有人激活小部件时,这三个小部件将出现

所以我们现在要做的就是当有人点击登录时显示小部件

html将显示一个登录链接。但如果他们登录,它会显示一些关于他们的信息

<ul class="nav navbar-nav pull-right">
                <li class="nav-item">
                    <a class="nav-link" (click)="auth.login()" *ngIf="!auth.authenticated()">Login / SignUp</a>
                    <a class="aside-toggle" href="#" role="button" aria-haspopup="true" aria-expanded="false" *ngIf="auth.authenticated()">
                    <span *ngIf="auth.authenticated() && auth.userProfile" class="profile-name">{{auth.userProfile.nickname}}</span>
                    <span *ngIf="!auth.authenticated() && !auth.userProfile" class="profile-name">Account</span>
                    <i class="icon-bell"></i><span class="tag tag-pill tag-danger profile-alerts">5</span>
                    <img *ngIf="auth.authenticated() && auth.userProfile" [src]="auth.userProfile.picture" class="img-avatar profile-picture" alt="User profile picture">
                    <img *ngIf="!auth.authenticated() && !auth.userProfile" src="/img/avatars/gravatar-default.png" alt="Default profile-picture">
                    </a>
                </li>
        </ul>
如果有什么不清楚的地方,请告诉我。我很乐意帮忙