接續 Day 11 Login & JWT ,之前我們弄好了登入畫面,還有登入的事件,還有把 Token 存在 Storage。
Route Guard 可以讓我們去設置是否有權限可以進入某個頁面。
HTTP Interceptor 則是可以協助我們在 call API 的時候,幫我們在 header 塞 token ,以便可通過後端的認證。
ionic generate guard guards/auth --implements CanLoad
我在 AuthGuard 的判斷很簡單,就判斷是否有 Token 的存在,沒有的話就回到登入頁面。
之後我調整了我的 route ,除了 /login 之外,其他都加上了 Route Guard
const routes: Routes = [
{
path: 'login',
loadChildren: () =>
import('./login/login.module').then((m) => m.LoginPageModule),
},
{
path: 'tabs',
loadChildren: () =>
import('./tabs/tabs.module').then((m) => m.TabsPageModule),
canLoad: [AuthGuard],
},
{
path: 'music',
loadChildren: () =>
import('./music/music.module').then((m) => m.MusicPageModule),
canLoad: [AuthGuard],
},
// .... 中間還有其他類似 music 的頁面 省略....
{
path: '',
redirectTo: '/tabs/main-menu',
pathMatch: 'full',
},
];
接著在 setting.page 增加一個登出
最後結果 (這個版本的結果,後端的 [JwtAuthentication] 是被註解掉的,純粹是 demo 方便)
剛剛說到後端 [JwtAuthentication] 被註解,如果沒有註解的話,基本上會吐給你 401 的訊息,表示沒有權限。
基本上,所以需要在打 API 的時候在 Header 加上 Token 就可以了。
可以把 Header 加上 Token 這段統一交給 HTTP Interceptor
HTTP Interceptor 他可以讓我們在統一在打 API 出去之前做一層額外的加工或是包裝。
手動 HTTP Interceptor (Ionic 5 之後好像不能用 ionic generate 去建立 provider ? )
最後在 app.module 中 import
最後結果