【发布时间】:2017-04-26 11:53:18
【问题描述】:
我正在关注https://github.com/auth0-samples/auth0-angularjs2-systemjs-sample/tree/master/01-Login 此处给出的 Auth0 登录示例。
这是我的身份验证服务代码。
import { Injectable } from '@angular/core';
import { tokenNotExpired } from 'angular2-jwt';
import { myConfig } from '../auth0.config';
import { Router } from '@angular/router'
// Avoid name not found warnings
declare var Auth0Lock: any;
@Injectable()
export class Auth {
// Configure Auth0
lock = new Auth0Lock(myConfig.ClientID,myConfig.DomainName, {
auth: {
redirectUrl: 'http://localhost:4200/server-auth',
responseType: 'token',
params: {
state: 'mologin'
}
}
});
constructor(private router: Router) {
// Add callback for lock `authenticated` event
this.lock.on('authenticated', (authResult) => {
localStorage.setItem('id_token', authResult.idToken);
this.router.navigate(['/emails'])
});
}
public login() {
// Call the show method to display the widget.
this.lock.show();
};
public authenticated() {
// Check if there's an unexpired JWT
// It searches for an item in localStorage with key == 'id_token'
return tokenNotExpired();
};
public logout() {
// Remove token from localStorage
localStorage.removeItem('id_token');
};
}
成功路由后,我将导航到我的电子邮件页面。电子邮件组件被加载。它的构造函数和 onInit 方法被成功调用。但是没有显示 html。
这是我的身份验证保护代码。用户不会被路由到登录页面,所以这很好。
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot} from '@angular/router';
import { Auth } from '../../services';
import { Router } from '@angular/router';
import { Injectable} from '@angular/core';
@Injectable()
export class AuthenticationGuard implements CanActivate {
constructor(private authService: Auth, private router: Router) {
}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
let url = route.url[0];
if (!this.authService.authenticated()) {
this.router.navigate(['login']);
}
return true;
}
}
这是成功导航后正在加载的电子邮件组件。
@Component({
selector: 'email-templates',
templateUrl: './email-templates.component.html'
})
export class EmailTemplatesComponent implements OnInit {
public isLoaded: Boolean = false;
public barData:any;//barChart data
private emailsArray: Array<any> = [];//table's data
constructor(private router: Router, private toasterService: ToasterService,
private elementRef: ElementRef, private emailService: EmailTemplateService,
public modal: Modal, public overlay: Overlay, public vcRef: ViewContainerRef) {
overlay.defaultViewContainer = vcRef;
}
ngOnInit() {
this.getAllEmails();
}
getAllEmails() {
this.emailService.getAllEmails().subscribe(res => {
if(res.success=="true"){
this.emailsArray = res.data;
}
})
}
}
【问题讨论】:
标签: angular jwt angular2-routing auth0