我有以下登录方法:
login(username, password)
{
let headerOptions = new HttpHeaders();
// headerOptions.append('Access-Control-Allow-Origin', '*');
// headerOptions.append('Access-Control-Request-Headers', '*');
// headerOptions.append('Content-Type', 'application/json');
// headerOptions.append('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,PATCH,OPTIONS');
headerOptions.append('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
this.credentials = {user: username, pass: password};
const httpParams = new HttpParams()
.set('username', username)
.set('password', password);
//console.log("hi "+ this.credentials);
return this.http.post('http://dev.local/scripts/login.php', httpParams, {
headers: headerOptions,
})
}
当用户成功登录时,一个 JWT 数组会返回到本地存储中,因此我们可以检查角色,以及它是否仍然登录。
有一个组件只有管理员才有权访问它,所以当用户点击路由时:
{
path: 'forgot',
component: ForgotPasswordComponent,
canActivate: [AuthGuardService]
},
authGuard 将使用canActivate()
守卫运行。
canActivate(_route: ActivatedRouteSnapshot,
_state: RouterStateSnapshot) : Observable<boolean> | Promise<boolean> | boolean
{
if(this.authApi.checkIsLogin())
{
return true;
}
else
{
return false;
}
}
现在检查checkIsLogin()
,执行以下脚本以返回一个承诺:
checkLoggedInAdmin()
{
//Get the JWT token from local storage
let jwt = localStorage.getItem('jwt');
let httpParams = new HttpParams().set('jwt', jwt);
let headerOptions = new HttpHeaders();
headerOptions.append('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
const promise = new Promise(
(resolve, reject)=>{
if(jwt!="" || jwt!=null || jwt!=undefined)
{
this.http.post('http://dev.local/scripts/checkLoginAdmin.php', httpParams, {
headers: headerOptions
}).subscribe(
(data)=>{
if(data==true)
{
this.loggedIn=true;
}
else{
this.loggedIn = false;
}
}
)
}
else
{
this.loggedIn=false;
}
resolve(this.loggedIn),
reject(this.loggedIn)
}
)
}
whereloggedIn
在类的顶部被定义为布尔值。
这是功能checkIsLogin()
:
checkIsLogin(){
return this.loggedIn
}
当用户登录时,会返回一个 jwt,其中包含所有必要的详细信息。但是,如果是管理员,并且在单击所需的路线时,什么都没有发生,也没有执行任何代码,控制台也没有错误。