CanActivate 返回 true 但组件中仍然出现 401 Unauthorized 错误
CanActivate returned true but still got 401 Unauthorize error in component
确实 CanActivate 返回了 true 但在我的组件中调用数据库时仍然出现 401 错误。
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private route: ActivateRouteSnapshot, private tokenService: TokenService) {}
public canActivate = (
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<boolean>|Promise<boolean>|boolean => {
const token = this.tokenService.token; // get jwt token
if (!token || this.isTokenExpired(token)) {
this.route.navigateByUrl('/login');
return false;
}
return true;
}
}
isTokenExpired 方法:
private isTokenExpired = (token: any): boolean => {
return Number(token.issued_at) + Number(token.expires_in) >= new Date().getTime();
}
我设置了一个断点,发现它返回了true。但是在我的组件中,我访问了数据库,但出现了 401 错误。
我的组件
async ngOnInit() {
await this.myService.getInformation('url').then(() => this.loading()).catch(this.showing = false;));}
另一个class中的getInformation
方法。
public getInformation = (url: string): Promise<void> => {
return new Promise(resolve, reject) => {
this.subscription.get().subscribe(response => {
this.data = response;
resolve();
},
error => {
console.log(error); // 401 error here
reject();
});
});
}
根据您发布的内容,您缺少将身份验证令牌注入 Http 请求的 HttpInterceptor。
一个good example:
@Injectable()
export class TokenInterceptor implements HttpInterceptor {
constructor(public auth: AuthService) {}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
request = request.clone({
setHeaders: {
Authorization: `Bearer ${this.auth.getToken()}`
}
});
return next.handle(request);
}
}
这将连接整个应用程序的 Http 注入,以将令牌插入请求 headers。至少一旦它也被添加到 Angular 的 DI 供应商中。
然后使用它会自动像这样工作:
// service method
return this.http.get('myApi/mymethod');
找到了。
我将 apigee 用于我的 OAuthV2 政策。通过 this:
issued_at The date the access token was issued expressed in Unix epoch time in milliseconds.
expires_in The expiration time for the access token. Expressed in seconds. Although the ExpiresIn element sets the expiration in milliseconds, in the token response and flow variables, the value is expresed in seconds.
所以我在求和的时候必须匹配数据格式
private isTokenExpired = (token: any): boolean => {
return Number(token.issued_at) + Number(token.expires_in*1000) < new Date().getTime();
}
这意味着
Number(token.issued_at) + Number(token.expires_in)
==>
Number(token.issued_at) + Number(token.expires_in*1000)
确实 CanActivate 返回了 true 但在我的组件中调用数据库时仍然出现 401 错误。
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private route: ActivateRouteSnapshot, private tokenService: TokenService) {}
public canActivate = (
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<boolean>|Promise<boolean>|boolean => {
const token = this.tokenService.token; // get jwt token
if (!token || this.isTokenExpired(token)) {
this.route.navigateByUrl('/login');
return false;
}
return true;
}
}
isTokenExpired 方法:
private isTokenExpired = (token: any): boolean => {
return Number(token.issued_at) + Number(token.expires_in) >= new Date().getTime();
}
我设置了一个断点,发现它返回了true。但是在我的组件中,我访问了数据库,但出现了 401 错误。
我的组件
async ngOnInit() {
await this.myService.getInformation('url').then(() => this.loading()).catch(this.showing = false;));}
另一个class中的getInformation
方法。
public getInformation = (url: string): Promise<void> => {
return new Promise(resolve, reject) => {
this.subscription.get().subscribe(response => {
this.data = response;
resolve();
},
error => {
console.log(error); // 401 error here
reject();
});
});
}
根据您发布的内容,您缺少将身份验证令牌注入 Http 请求的 HttpInterceptor。
一个good example:
@Injectable()
export class TokenInterceptor implements HttpInterceptor {
constructor(public auth: AuthService) {}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
request = request.clone({
setHeaders: {
Authorization: `Bearer ${this.auth.getToken()}`
}
});
return next.handle(request);
}
}
这将连接整个应用程序的 Http 注入,以将令牌插入请求 headers。至少一旦它也被添加到 Angular 的 DI 供应商中。
然后使用它会自动像这样工作:
// service method
return this.http.get('myApi/mymethod');
找到了。
我将 apigee 用于我的 OAuthV2 政策。通过 this:
issued_at The date the access token was issued expressed in Unix epoch time in milliseconds.
expires_in The expiration time for the access token. Expressed in seconds. Although the ExpiresIn element sets the expiration in milliseconds, in the token response and flow variables, the value is expresed in seconds.
所以我在求和的时候必须匹配数据格式
private isTokenExpired = (token: any): boolean => {
return Number(token.issued_at) + Number(token.expires_in*1000) < new Date().getTime();
}
这意味着
Number(token.issued_at) + Number(token.expires_in)
==>
Number(token.issued_at) + Number(token.expires_in*1000)