在Angular 4中确定各种身份验证方法

时间:2017-11-15 23:39:42

标签: angular jwt

我已经阅读了两篇在Angular 4中实现身份验证的教程。

first一个会覆盖 RouterOutlet 类,并声明不需要登录的公共路由。

但是,second方法是使用Angular 4提供的 canActivate AuthGuard接口。
我正在努力找出哪种方法是正确或有效的方法。

此外,我如何在Angular 4中实现授权。我读到了 canActivateChild 界面,但它似乎太复杂了。

2 个答案:

答案 0 :(得分:1)

我建议您使用AuthGuard

以下是如何实施AuthGuard的简单示例。

<强> Module.ts

// Routes
const routes : Routes = [
{
    path: '',
    component: HomeComponent,
    canActivate : [AuthService] //<== Activate AuthGuard
},
{
    path: 'login',
    component: LoginComponent
},
{
    path: '**',
    redirectTo: ''
}
];
'

@NgModule({
    declarations: [
    AppComponent,
    LoginComponent,
    HomeComponent
    ],
    providers: [AuthService], //<== Add AuthService here
    bootstrap: [AppComponent]
})

<强> AuthService

import { Injectable }     from '@angular/core';
import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot }    from '@angular/router';

@Injectable() 
export class AuthService implements CanActivate {

    constructor(private router: Router) {}

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
        let url: string = state.url; //<== Get URL if needed

        if (localStorage.getItem('token')) { // <== Check for token
            return true;
        }else {
            this.router.navigate(['/login']);
            return false;
        }
    }
}

答案 1 :(得分:0)

我写了两个Guards,一个用于实现身份验证,另一个用于授权。

//Guard for Authentication
@Injectable()
export class AuthGuard implements CanActivate {
    constructor(private loginService: LoginService, private router: Router) { }
    canActivate() {
      if(this.loginService.isLoggedIn()){
        return true;
      }
      this.router.navigate(['/home']);
      return false;
    }
}

//Guard for Authorization
@Injectable()
export class AdminAuthGuard implements CanActivate {
    constructor(private loginService: LoginService, private router: Router) { }
    canActivate() {
      return this.loginService.checkSession().map(res=>{
            let resJSON = res.json();
            let isAllowed = (resJSON.length > 0 && resJSON[0].authority === "ROLE_ADMIN") ? true : (this.router.navigate(['/home']), false);
            return isAllowed;
          });
    }
}

此实施是否正确,还是应该关注其他实施? (虽然它工作正常,但我正在寻找更好的方法) 我的应用程序的路由文件如下:

const appRoutes: Routes = [
    {
        path: '',
        redirectTo: '/home',
        pathMatch: 'full'
    },
    {
        path: 'home',
        component: HomeComponent
    },
    {
        path: 'adminPage',
        component: MyAccountComponent,
        canActivate: [AuthGuard, AdminAuthGuard] 
    }
];  

因此,每当我以管理员身份登录时,我都可以访问 adminPage ,而如果我以普通用户身份登录,则无法访问网页。

loginService已实现如下:

//Login Service
@Injectable()
export class LoginService {
  private serverPath:string = AppConst.serverPath; //'http://127.0.0.1:8888'
  constructor(private http:Http, private router:Router) { }
  isLoggedIn() {
      return localStorage.getItem('xAuthToken') !== null;
    }
  //Server will send back the Token for the user.   
  sendCredential(username: string, password: string) {
    let url = this.serverPath+'/token';
    let encodedCredentials = btoa(username+":"+password);
    let basicHeader = "Basic "+encodedCredentials;
    let headers = new Headers({
        'Content-Type' : 'application/x-www-form-urlencoded',
        'Authorization' : basicHeader
    });
    return this.http.get(url, {headers: headers});
  }
  //Server returns a JSONARRAY respresenting the roles of the user.
  checkSession() {
    let url = this.serverPath+'/checkSession';
    let headers = new Headers({
        'x-auth-token' : localStorage.getItem('xAuthToken')
    });
    return this.http.get(url, {headers: headers});
  }
  logout() {
    let url = this.serverPath+'/user/logout';
    let headers = new Headers({
        'x-auth-token' : localStorage.getItem('xAuthToken')
    });
    return this.http.post(url, '', {headers: headers});
  }
}