2016-11-20 9 views
1

私のウェブサイトにはこの要件があります。このウェブサイトはAngular 2で構築されたSPAになります。 私が望むのは、ユーザーがGoogle、Facebook、Twitter oauthを使用してログインできることです。oauthノードjを使用して角度2を認証する方法

ノードサーバーでoauthをセットアップできますが、問題はangear 2アプリを使用してログインを許可する方法です。

角度2アプリで、ユーザーがfacebook signinオプションをクリックした場合、私は自分のアプリケーションの状態を失うため、ユーザーをリダイレクトできません。

これは非常に初心者の問題かどうかわかりません。誰もが角度2 +ノードoauthで何が起こるのかを手伝ってもらえますか

答えて

2

アプリケーションのフロントエンドを処理するために角型アプリケーションでルートを設定したいと思っています。次に、アプリケーションのauth0認証を処理するサービスを作成します。

これは、安全なルートセットと公開されたルートセットをアプリケーションに設定する方法の概要です。誰かがoauthでログインすると、安全なルートに転送されます。

ここから出発するルートです。私たちは今、あなたがそれを持っていることを

ルート

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 } 
]; 

[OK]をファイルapp.routing.tsに安全で公共を指定します。テンプレートディレクトリを作成することができます。内側には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; 
    } 
} 

これで、Guardで保護されたルートが用意できました。 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 protected]", 
    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のTwitterとGoogle。誰かがウィジェットを起動すると、その3つが表示されます。

だから我々が今しなければならないすべては、誰かがログインをクリックしたときに、

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> 

明らかでないことがあれば教えてください。私は助けてうれしいです。

関連する問題