為你的 Angular 應用程式新增驗證 (Authentication)
- 以下示範基於 Angular 18.0.0 和 angular-auth-oidc-client。
- 範例專案可在 GitHub 儲存庫 中找到。
先決條件
- 一個 Logto Cloud 帳戶或 自行託管的 Logto。
- 已建立的 Logto 單頁應用程式。
安裝
安裝 Logto JS 核心 SDK 和 Angular OIDC 客戶端庫:
- npm
- pnpm
- yarn
npm i @logto/js angular-auth-oidc-client
pnpm add @logto/js angular-auth-oidc-client
yarn add @logto/js angular-auth-oidc-client
整合
配置應用程式
在你的 Angular 專案中,於 app.config.ts
中新增驗證提供者:
import { buildAngularAuthConfig } from '@logto/js';
import { provideAuth } from 'angular-auth-oidc-client';
export const appConfig: ApplicationConfig = {
providers: [
provideHttpClient(withFetch()),
provideAuth({
config: buildAngularAuthConfig({
endpoint: '<your-logto-endpoint>',
appId: '<your-app-id>',
redirectUri: 'http://localhost:3000/callback',
postLogoutRedirectUri: 'http://localhost:3000/',
}),
}),
// ...其他提供者
],
};
配置重定向 URI
在深入細節之前,以下是終端使用者體驗的快速概覽。登入流程可簡化如下:
- 你的應用程式呼叫登入方法。
- 使用者被重定向至 Logto 登入頁面。對於原生應用程式,系統瀏覽器會被開啟。
- 使用者登入後被重定向回你的應用程式(配置為重定向 URI)。
關於基於重導的登入
- 此驗證流程遵循 OpenID Connect (OIDC) 協議,Logto 強制執行嚴格的安全措施以保護使用者登入。
- 如果你有多個應用程式,可以使用相同的身分提供者 (IdP, Identity provider)(Logto)。一旦使用者登入其中一個應用程式,Logto 將在使用者訪問另一個應用程式時自動完成登入流程。
欲了解更多關於基於重導登入的原理和優勢,請參閱 Logto 登入體驗解析。
在以下的程式碼片段中,我們假設你的應用程式運行在 http://localhost:3000/
。
配置重定向 URI
切換到 Logto Console 的應用程式詳細資訊頁面。新增一個重定向 URI http://localhost:3000/callback
。
就像登入一樣,使用者應被重定向到 Logto 以登出共享會話。完成後,將使用者重定向回你的網站會很不錯。例如,將 http://localhost:3000/
新增為登出後重定向 URI 區段。
然後點擊「儲存」以保存更改。
處理重定向
由於我們使用 http://localhost:3000/callback
作為重定向 URI,現在需要妥善處理它。angular-auth-oidc-client
函式庫提供了內建的重定向處理支援。你只需正確配置驗證提供者的設定,函式庫會處理其餘部分。
export const appConfig: ApplicationConfig = {
providers: [
provideAuth({
config: buildAngularAuthConfig({
// ...其他設定
redirectUri: 'http://localhost:3000/callback',
postLogoutRedirectUri: 'http://localhost:3000/',
}),
}),
// ...其他提供者
],
};
實作登入與登出
在你想要實作登入與登出的元件中(例如 app.component.ts
),注入 OidcSecurityService
並使用它來進行登入與登出。
import { OidcSecurityService } from 'angular-auth-oidc-client';
export class AppComponent implements OnInit {
constructor(public oidcSecurityService: OidcSecurityService) {}
signIn() {
this.oidcSecurityService.authorize();
}
signOut() {
this.oidcSecurityService.logoff().subscribe((result) => {
console.log('app sign-out', result);
});
}
}
然後,在模板中新增登入與登出按鈕:
<button (click)="signIn()">登入</button>
<br />
<button (click)="signOut()">登出</button>
呼叫 .signOut()
將清除記憶體和 localStorage 中所有的 Logto 資料(如果存在)。
檢查點:測試你的應用程式
現在,你可以測試你的應用程式:
- 執行你的應用程式,你會看到登入按鈕。
- 點擊登入按鈕,SDK 會初始化登入流程並將你重定向到 Logto 登入頁面。
- 登入後,你將被重定向回應用程式並看到登出按鈕。
- 點擊登出按鈕以清除權杖存儲並登出。
獲取使用者資訊
當使用者成功登入後,Logto 會簽發一個包含使用者資訊宣告的 ID 權杖 (ID token)。ID 權杖是一個 JSON Web Token (JWT)。
需要注意的是,根據使用者在登入時使用的權限範圍 (Scopes),可檢索的使用者資訊宣告可能不同。考慮到效能和資料大小,ID 權杖可能不包含所有使用者宣告,部分使用者宣告僅在 userinfo endpoint 中可用(請參閱下方相關列表)。
如果配置中沒有提供 resource
,buildAngularAuthConfig()
工具將啟用 autoUserInfo
和 renewUserInfoAfterTokenRenew
。這意味著 Logto 會在使用者登入後自動獲取使用者資訊,並在權杖更新後更新使用者資訊。
欲了解更多關於配置 angular-auth-oidc-client
函式庫的資訊,請參閱 官方文件。
顯示使用者資訊
OidcSecurityService
提供了一種方便的方法來訂閱驗證狀態以及使用者資訊:
import { OidcSecurityService } from 'angular-auth-oidc-client';
import { decodeIdToken, type IdTokenClaims } from '@logto/js';
export class AppComponent implements OnInit {
isAuthenticated = false;
idTokenClaims?: IdTokenClaims;
accessToken?: string;
constructor(public oidcSecurityService: OidcSecurityService) {}
ngOnInit() {
this.oidcSecurityService.checkAuth().subscribe(({ isAuthenticated, idToken, accessToken }) => {
console.log('app authenticated', isAuthenticated, idToken);
this.isAuthenticated = isAuthenticated;
this.idTokenClaims = decodeIdToken(idToken);
this.accessToken = accessToken;
});
}
// ...其他方法
}
並在模板中使用:
<button *ngIf="!isAuthenticated" (click)="signIn()">Sign in</button>
<ng-container *ngIf="isAuthenticated">
<pre>{{ idTokenClaims | json }}</pre>
<p>Access token: {{ accessToken }}</p>
<!-- ... -->
<button (click)="signOut()">Sign out</button>
</ng-container>
請求額外的宣告
你可能會發現從 idToken
返回的物件中缺少一些使用者資訊。這是因為 OAuth 2.0 和 OpenID Connect (OIDC) 的設計遵循最小權限原則 (PoLP, Principle of Least Privilege),而 Logto 是基於這些標準構建的。
預設情況下,僅返回有限的宣告 (Claims)。如果你需要更多資訊,可以請求額外的權限範圍 (Scopes) 以存取更多宣告。
「宣告 (Claim)」是對主體所做的斷言;「權限範圍 (Scope)」是一組宣告。在目前的情況下,宣告是關於使用者的一部分資訊。
以下是權限範圍與宣告關係的非規範性範例:
「sub」宣告表示「主體 (Subject)」,即使用者的唯一識別符(例如使用者 ID)。
Logto SDK 將始終請求三個權限範圍:openid
、profile
和 offline_access
。
要請求額外的權限範圍 (Scopes),可以配置驗證提供者的配置:
import { UserScope, buildAngularAuthConfig } from '@logto/js';
export const appConfig: ApplicationConfig = {
providers: [
provideHttpClient(withFetch()),
provideAuth({
config: buildAngularAuthConfig({
// ...其他配置
scopes: [
UserScope.Email,
UserScope.Phone,
UserScope.CustomData,
UserScope.Identities,
UserScope.Organizations,
],
}),
}),
// ...其他提供者
],
};
然後你可以在 idToken
的返回值中訪問額外的宣告。
需要網路請求的宣告 (Claims)
為了防止 ID 權杖 (ID token) 膨脹,某些宣告 (Claims) 需要透過網路請求來獲取。例如,即使在權限範圍 (Scopes) 中請求了 custom_data
宣告,它也不會包含在使用者物件中。要存取這些宣告,你可以配置 userData
選項:
import { OidcSecurityService } from 'angular-auth-oidc-client';
import { type UserInfoResponse } from '@logto/js';
export class AppComponent implements OnInit {
isAuthenticated = false;
userData?: UserInfoResponse;
accessToken?: string;
constructor(public oidcSecurityService: OidcSecurityService) {}
ngOnInit() {
this.oidcSecurityService
.checkAuth()
.subscribe(({ isAuthenticated, userData, accessToken }) => {
console.log('app authenticated', isAuthenticated, idToken);
this.isAuthenticated = isAuthenticated;
this.userData = userData;
this.accessToken = accessToken;
});
}
// ...其他方法
}
// 現在你可以訪問宣告 `userData.custom_data`
userData
,SDK 將在使用者登入後透過請求 userinfo 端點 來獲取使用者資訊,並且一旦請求完成,userData
將可用。
權限範圍 (Scopes) 和宣告
Logto 使用 OIDC 權限範圍 (Scopes) 和宣告 (Claims) 慣例 來定義從 ID 權杖 (ID token) 和 OIDC 使用者資訊端點 (userinfo endpoint) 獲取使用者資訊的權限範圍和宣告。無論是「權限範圍 (Scope)」還是「宣告 (Claim)」,都是 OAuth 2.0 和 OpenID Connect (OIDC) 規範中的術語。
以下是支援的權限範圍 (Scopes) 及其對應的宣告 (Claims):
openid
宣告名稱 | 類型 | 描述 | 需要使用者資訊嗎? |
---|---|---|---|
sub | string | 使用者的唯一識別符 | 否 |
profile
宣告名稱 | 類型 | 描述 | 需要使用者資訊嗎? |
---|---|---|---|
name | string | 使用者的全名 | 否 |
username | string | 使用者的用戶名 | 否 |
picture | string | 使用者個人資料圖片的 URL。此 URL 必須指向圖像文件(例如 PNG、JPEG 或 GIF 圖像文件),而不是包含圖像的網頁。請注意,此 URL 應特別參考適合在描述使用者時顯示的個人資料照片,而不是使用者拍攝的任意照片。 | 否 |
created_at | number | 使用者創建的時間。時間以自 Unix epoch(1970-01-01T00:00:00Z)以來的毫秒數表示。 | 否 |
updated_at | number | 使用者資訊最後更新的時間。時間以自 Unix epoch(1970-01-01T00:00:00Z)以來的毫秒數表示。 | 否 |
其他 標準宣告 包括 family_name
、given_name
、middle_name
、nickname
、preferred_username
、profile
、website
、gender
、birthdate
、zoneinfo
和 locale
也將包含在 profile
權限範圍中,無需請求使用者資訊端點。與上述宣告的不同之處在於,這些宣告僅在其值不為空時返回,而上述宣告在值為空時將返回 null
。
與標準宣告不同,created_at
和 updated_at
宣告使用毫秒而非秒。
email
宣告名稱 | 類型 | 描述 | 需要使用者資訊嗎? |
---|---|---|---|
string | 使用者的電子郵件地址 | 否 | |
email_verified | boolean | 電子郵件地址是否已驗證 | 否 |
phone
宣告名稱 | 類型 | 描述 | 需要使用者資訊嗎? |
---|---|---|---|
phone_number | string | 使用者的電話號碼 | 否 |
phone_number_verified | boolean | 電話號碼是否已驗證 | 否 |
address
請參閱 OpenID Connect Core 1.0 以獲取地址宣告的詳細資訊。
custom_data
宣告名稱 | 類型 | 描述 | 需要使用者資訊嗎? |
---|---|---|---|
custom_data | object | 使用者的自訂資料 | 是 |
identities
宣告名稱 | 類型 | 描述 | 需要使用者資訊嗎? |
---|---|---|---|
identities | object | 使用者的連結身分 | 是 |
sso_identities | array | 使用者的連結 SSO 身分 | 是 |
roles
宣告名稱 | 類型 | 描述 | 需要使用者資訊嗎? |
---|---|---|---|
roles | string[] | 使用者的角色 | 否 |
urn:logto:scope:organizations
宣告名稱 | 類型 | 描述 | 需要使用者資訊嗎? |
---|---|---|---|
organizations | string[] | 使用者所屬的組織 ID | 否 |
organization_data | object[] | 使用者所屬的組織資料 | 是 |
urn:logto:scope:organization_roles
宣告名稱 | 類型 | 描述 | 需要使用者資訊嗎? |
---|---|---|---|
organization_roles | string[] | 使用者所屬的組織角色,格式為 <organization_id>:<role_name> | 否 |
考慮到效能和資料大小,如果「需要使用者資訊嗎?」為「是」,則表示該宣告不會顯示在 ID 權杖中,而會在 使用者資訊端點 回應中返回。
API 資源
為 API 資源 (API resource) 配置 angular-auth-oidc-client
我們建議先閱讀 🔐 角色型存取控制 (RBAC, Role-Based Access Control),以瞭解 Logto RBAC 的基本概念以及如何正確設定 API 資源。
一旦你設定了 API 資源,就可以在應用程式中配置 Logto 時新增它們:
export const appConfig: ApplicationConfig = {
providers: [
provideHttpClient(withFetch()),
provideAuth({
config: buildAngularAuthConfig({
// ...other config
resource: 'https://your-api-resource.com',
}),
}),
// ...other providers
],
};
每個 API 資源都有其自身的權限(權限範圍)。
例如,https://shopping.your-app.com/api
資源具有 shopping:read
和 shopping:write
權限,而 https://store.your-app.com/api
資源具有 store:read
和 store:write
權限。
要請求這些權限,你可以在應用程式中配置 Logto 時新增它們:
export const appConfig: ApplicationConfig = {
providers: [
provideHttpClient(withFetch()),
provideAuth({
config: buildAngularAuthConfig({
// ...other config
resource: 'https://your-api-resource.com',
scopes: ['openid', 'profile', 'offline_access', 'read', 'write'],
}),
}),
// ...other providers
],
};
你可能會注意到權限範圍是獨立於 API 資源定義的。這是因為 OAuth 2.0 的資源標示符 (Resource Indicators) 指定請求的最終權限範圍將是所有目標服務中所有權限範圍的笛卡兒積。
請求未在 API 資源中定義的權限範圍是可以的。例如,即使 API 資源中沒有可用的 email
權限範圍,你也可以請求 email
權限範圍。不可用的權限範圍將被安全地忽略。
成功登入後,Logto 將根據使用者的角色向 API 資源發出適當的權限範圍。
現在,存取權杖 (Access token) 將以 JSON Web Token (JWT) 格式呈現,而非隨機字串(不透明權杖 (Opaque token))。
當設定 resource
時,autoUserInfo
和 renewUserInfoAfterTokenRenew
皆會被停用。這是因為存取權杖 (Access token) 將針對特定 API 資源 (API resource) 請求,而非使用者資訊端點。
目前,僅 Logto 官方 SDK 支援同時請求使用者資訊與 API 資源存取權杖 (Access tokens) 的功能。如需同時請求,請隨時與我們聯繫。