此Auth防护不适用于API响应。当我运行代码时,它总是返回true。但我想基于api响应运行防护。是他们实现这一目标的方法?
import {Injectable} from '@angular/core';
import {CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router, Route} from '@angular/router';
import {
HttpClient,
HttpHeaders
} from '@angular/common/http';
import {Observable} from 'rxjs';
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private router: Router, private http: HttpClient) {
}
canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
const sendData = {};
sendData['id'] = sessionStorage.getItem('id');
console.log(JSON.stringify(sendData));
const headers = new HttpHeaders()
.set('Content-Type', 'application/json')
.set('token', sessionStorage.getItem('auth') ? sessionStorage.getItem('auth') : 'test');
this.http.post('http://127.0.0.1:5000/auth',
JSON.stringify(sendData), {
headers
})
.subscribe(
(val: any) => {
},
response => {
this.router.navigate(['/login']);
},
() => {
console.log('The POST observable is now completed.');
});
return true;
}
}
答案 0 :(得分:0)
检查此。您已在 canActivate authguard的末尾返回true。这样,它将始终返回true。相反,您应该根据自己的情况将其放在http post请求的subscription方法中。像这样的东西。
this.http.post('http://127.0.0.1:5000/auth',
JSON.stringify(sendData), {
headers
}).pipe(map(response => {
//suppose we get isAuthenticated bit in response. Your response obj may vary but logic shall be same
if (response.isAuthenticated) {
return true;
}
else {
return false;
}
}));
谢谢。