bixi
Version:
企业级中后台前端解决方案
119 lines (98 loc) • 3.06 kB
Markdown
---
order: 1
title: 开始使用
type: Guide
---
### 1. 安装依赖
```bash
yarn add @bixi/auth
```
### 2. 注册模块
```typescript
import { BixiAuthModule} from '@bixi/auth';
@NgModule({
imports: [
BixiAuthModule
]
})
export class AppModule { }
```
### 3. 添加 HTTP 拦截器
##### 使用 JWTInterceptor
```typescript
import { BixiAuthModule, JWTInterceptor } from '@bixi/auth';
@NgModule({
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: JWTInterceptor,
multi: true
}
]
})
export class AppModule { }
```
##### 使用 SimpleInterceptor
```ts
import { BixiAuthModule, SimpleInterceptor } from '@bixi/auth';
@NgModule({
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: SimpleInterceptor,
multi: true
}
]
})
export class AppModule { }
```
可以通过 `BixiAuthConfig` 指定参数名以及其发送位置,例如:
```js
token_send_key = 'token';
token_send_template = 'Bearer ${token}';
token_send_place = 'header';
```
表示在每一个请求的 header 加上 { token: 'Bearer token_string' } 数据。
### 4. 添加路由守卫
```typescript
import { Routes } from '@angular/router';
import { JWTGuard } from '@bixi/auth';
const routes: Routes = [
{
path: 'secret',
component: SecretComponent,
canActivate: [JWTGuard],
}
];
```
### 5. 添加配置
```ts
import { BixiAuthModule, JWTInterceptor, BixiAuthConfig, BIXI_AUTH_CONFIG } from '@bixi/auth';
const bixiAuthConfig: BixiAuthConfig = {
store_key: 'bixi-store-key',
// 注意如果发现项目无法进入,通常是因为拦截器拦截了不该拦截的请求,请检查 ignores 是否已经列出所有需要被忽略的请求(包括 json 文件的获取)
ignores: [/\/login/, /assets\//, /passport\//]
};
@NgModule({
providers: [
{
provide: BIXI_AUTH_CONFIG,
useValue: bixiAuthConfig
},
]
})
export class AppModule { }
```
### BixiAuthConfig
| 成员 | 说明 | 类型 | 默认值 |
|----|----|----|-----|------|
| `[store_key]` | `string` | `_token` | `localStorage` 的存储KEY值 |
| `[token_invalid_redirect]` | `boolean` | `true` | 无效时跳转至登录页,包括:无效token值、token已过期(限JWT) |
| `[token_exp_offset]` | `number` | `10` | JWT token过期时间偏移值(单位:秒) |
| `[token_send_key]` | `string` | Token | 发送token参数名 |
| `[token_send_template]` | `string` | `${token}` | 发送token模板,以 `${属性名}` 表示占位符,属性名要确保存在否则以空字符代替 |
| `[token_send_place]` | `header,body,url` | `header` | 发送token参数位置 |
| `[login_url]` | `string` | `/login` | 登录页路由地址 |
| `[ignores]` | `RegExp[]` | `[ /\/login/, /assets\// ]` | 忽略 URL 地址清单 |
| `[allow_anonymous_key]` | `string` | `_allow_anonymous` | 允许匿名登录标识号,若请求参数中带有该KEY表示忽略TOKEN |
| `[executeOtherInterceptors]` | `boolean` | `true` | 是否校验失效时命中后继续调用后续拦截器的 `intercept` 方法 |