前言
随着 Web 应用程序的普及,用户验证和安全变得越来越重要。 JSON Web Tokens (JWT) 已经成为了一种流行的 Web 应用程序认证方案之一,可以将用户信息加密在 token 中,并使用此 token 进行请求。npm 包 @scomith/ng-jwt-auth 可以方便地实现 JWT 认证,本文就来详细介绍一下如何使用此包。
安装
首先,在 Angular 项目中使用 npm 安装 @scomith/ng-jwt-auth 包:
npm install @scomith/ng-jwt-auth
配置
在项目中,首先需要配置 @scomith/ng-jwt-auth 包。
导入模块
要使用 @scomith/ng-jwt-auth,需要在 app.module.ts 文件中导入以下模块:
import { NgJwtAuthModule } from '@scomith/ng-jwt-auth'; @NgModule({ declarations: [AppComponent], imports: [BrowserModule, NgJwtAuthModule.forRoot()], bootstrap: [AppComponent], }) export class AppModule {}
设置配置选项
接下来,需要为 @scomith/ng-jwt-auth 设置选项。为了避免硬编码选项,通常会将这些选项定义在一个单独的配置文件中,例如 config.ts。
import { NgJwtAuthOptions } from '@scomith/ng-jwt-auth'; export const AUTH_CONFIG: NgJwtAuthOptions = { tokenGetter: () => localStorage.getItem('access_token'), headerName: 'Authorization', authScheme: 'Bearer', allowedDomains: ['localhost:4200'], };
我们可以自行定制这些选项,以满足我们自己的需求。这里我们简单介绍一下这些选项:
tokenGetter
:用于获取 token 的函数。headerName
:Authorization 头部的名称。authScheme
:Authorization 头部的方案。allowedDomains
:允许的域名列表。
最后,在 app.module.ts 文件的 providers 数组中引入 AUTH_CONFIG:
-- -------------------- ---- ------- ------ - ----------- - ---- ----------- ----------- ------------- --------------- -------- --------------- --------------------------- ---------- --------------- ---------- -- -------- --------------------- --------- ----------- --- -- ------ ----- --------- --展开代码
这里我们将 AUTH_CONFIG 注入为 tokenGetter 选项的值。
使用
配置完成后,我们就可以在 Angular 应用程序中使用 @scomith/ng-jwt-auth 来简化 JWT 认证了!
获取 token
首先,在登录过程中,我们需要获取 token 并将其存储在本地存储中。在此处,我们使用了 Angular 的 HttpClient 发送 POST 请求来获取 token。
-- -------------------- ---- ------- ------ - ---------- - ---- ----------------------- ------ ----- ----------- - ------------------- ----- ----------- -- ------- - ----- ---- - - --------- ------- --------- ----------- -- -------------------------------------------------- ---------------- ------ -- ------------------------------------ ------------------- ------- -- ------------------ -- - -展开代码
发送请求
接下来,我们可以使用 @scomith/ng-jwt-auth 的 HttpService 服务来发送包含 JWT 认证 token 的请求。这个服务会自动在每个请求的 header 中包含 token。例如:
-- -------------------- ---- ------- ------ - ----------- - ---- ----------------------- ------ ----- ----------- - ------------------- ------------ ------------ -- ---------- - ------ ----------------------------------------------------------- - -展开代码
这里我们通过 HttpService 的 get 方法获取了 /users 的数据。
总结
通过使用 @scomith/ng-jwt-auth,我们可以快速简单地实现基于 JWT 的身份验证。本文介绍了如何使用此软件包的详细步骤和示例代码,相信能对你对 JWT 认证的理解和使用有所帮助。
来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/6005677981e8991b448e3df7