我写了两个Guard,一个用于实现身份验证,另一个用于授权。
//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});
}
}