2016-11-20 43 views
1

我對我的網站有這個要求。該網站將是一個與Angular 2建成的SPA。 我想要的是,用戶可以使用Google,Facebook,Twitter oauth登錄。如何使用oauth節點js對角2進行身份驗證

我可以在節點服務器上設置oauth,但問題是如何允許通過角度2應用程序登錄。

在角2應用程序中,如果當用戶點擊Facebook登錄選項時,我不能重定向用戶,因爲我失去了我的應用程序的狀態。

我不知道這是一個非常初學者的問題。任何人都可以幫助我在角2 +節點發生什麼流oauth

回答

2

您將要在角應用中設置路由來處理您的應用程序的前端。然後創建一個服務來處理應用程序的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; 
    } 
} 

現在我們已經得到了用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和谷歌。然後當有人激活小部件時,這三個將出現。

所以現在我們所要做的就是顯示widget時有人點擊登錄,

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> 

讓我知道是否有什麼不清楚。我會很樂意提供幫助。

相關問題