angular - 为什么离子/角度拒绝进行身份验证?
问题描述
我已经构建了一个从服务器接收用户信息和令牌 (jwt) 的身份验证应用程序。我将数据存储在本地,然后使用它在应用程序中进行更多计算。对于路由守卫,如果令牌可用,则应转到仪表板,否则返回登录。
这是我的身份验证服务,我正在调用 loggedIn 方法
import { HttpClient } from "@angular/common/http"
import { Router } from '@angular/router'
import { Storage } from '@ionic/storage';
@Injectable({
providedIn: 'root'
})
export class AuthService {
private _registerUrl = "http://localhost:3000/api/register"
private _loginUrl = "http://localhost:3000/api/login"
constructor(private http: HttpClient, private _router:Router,private storage: Storage) { }
registerUser(user){
return this.http.post<any>(this._registerUrl,user)
}
loginUser(user){
return this.http.post<any>(this._loginUrl,user)
}
loggedIn(){
return !!this.storage.get('token')
}
getToken(){
return this.storage.get('token')
}
logoutUser(){
this.storage.remove('token')
this.storage.remove('user')
this._router.navigate(['/login'])
}
}
路由文件
import { PreloadAllModules, RouterModule, Routes } from '@angular/router';
import { DashboardPage } from './dashboard/dashboard.page';
import {HomePage } from './dashboardComponents/home/home.page'
import {MessagesPage } from './dashboardComponents/messages/messages.page'
import {PaymentsPage } from './dashboardComponents/payments/payments.page'
import {PostedJPage } from './dashboardComponents/posted-j/posted-j.page'
import {ProfileEditPage } from './dashboardComponents/profile-edit/profile-edit.page'
import {PostPage } from './dashboardComponents/post/post.page'
import {SettingsPage} from './dashboardComponents/settings/settings.page'
import { PasswordResetPage } from './password-reset/password-reset.page'
import { JobCompletedPage } from './dashboardComponents/job-completed/job-completed.page'
import { AppliedJobsPage} from './dashboardComponents/applied-jobs/applied-jobs.page'
import { AuthGuard } from './auth.guard'
const routes: Routes = [
{ path: '', redirectTo: 'login', pathMatch: 'full' },
{ path: 'login', loadChildren: './login/login.module#LoginPageModule' },
{ path: 'register', loadChildren: './register/register.module#RegisterPageModule' },
{ path: 'password-reset', component:PasswordResetPage, pathMatch:'full' },
{ path:'dashboard', redirectTo:'dashboard/home/1000}'},
{ path:'dashboard', component: DashboardPage,canActivate: [AuthGuard],
children: [
{ path: 'messages', component:MessagesPage , pathMatch:'full'},
{ path: 'home/:distance', component: HomePage , pathMatch:'full'},
{ path: 'payments', component:PaymentsPage , pathMatch:'full'},
{ path: 'post', component:PostPage ,pathMatch:'full'},
{ path: 'settings', component: SettingsPage, pathMatch:'full' },
{ path: 'profile-edit', component: ProfileEditPage, pathMatch:'full' },
{path:'posted', component:PostedJPage,pathMatch:'full'},
{path:'job-completed', component:JobCompletedPage, pathMatch:'full' },
{path:'applied-jobs',component:AppliedJobsPage,pathMatch:"full"}
]
}
];
@NgModule({
imports: [
RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules })
],
exports: [RouterModule]
})
export class AppRoutingModule { }
export const components = [
HomePage,
MessagesPage,
PaymentsPage,
PostedJPage,
ProfileEditPage,
DashboardPage,
PostPage,
SettingsPage,
PasswordResetPage,
JobCompletedPage,
AppliedJobsPage
];
保护文件
import { ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree,CanActivate,Router } from '@angular/router';
import { Observable } from 'rxjs';
import { AuthService} from './auth.service'
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
constructor(private _authService: AuthService, private _router:Router){
}
canActivate(): boolean {
if(this._authService.loggedIn()){
return true
} else {
this._router.navigate(['/login'])
return false
}
}
}
我正在使用离子存储,因为我最终会在 Playstore 上启动它。无论令牌是否存在,即使我有一个守卫,它仍然会进入仪表板页面。
解决方案
试试这个:
修改您的 LoggedIn 方法以返回承诺(删除!!)
loggedIn() {
return this.storage.get('token').then((token)=>{
if (token) {
console.log("token true")
return true
} else {
console.log("token false")
return false
}
})
};
像这样修改 CanActivate :
async canActivate(): Promise<boolean> {
if(await this.auth.loggedIn()){
return true
} else {
this._router.navigate(['/login'])
return false
};
};
推荐阅读
- html - 图片没有获得移动响应
- android - setState 不会改变 TextField 的装饰
- excel - 使用 VBA 从已关闭的 Excel 工作簿中导入图像/图片
- python - 如何在点击时从模板传递值
- ios - 不同的类有相似的方法
- javascript - RTCDataChannel 的“bufferedamountlow”事件未在 Safari 中触发?
- python - 异常值去除隔离林
- azure - 将应用程序从 ASP.NET Core 2.2 升级到 ASP.NET Core 3.1 后,Azure DevOps 构建失败
- c# - 从对象c#中的列表中删除重复项
- python-3.x - Pandas Group-By 并计算两列的比率