8-3、ts-axios http授权

2019-12-17  本文已影响0人  Eileen_1d88

HTTP协议中的Authorization请求header会包含服务器用于验证用户代理身份的凭证,通常会在服务器返回401 Unauthorized状态码以及WWW-Authoricate消息头之后在后续请求中发送此消息头。

axios库也允许你在请求配置中配置auth属性,auth属性是一个对象结构,包含username和password属性。一旦用户在请求的时候配置了这2个属性,我们就会自动往HTTP的请求header中添加Authorization属性,它的值为Basic加密串。这里的加密串是username:password base64加密后的结果。

axios.post('/more/post', {
  a: 1
}, {
  auth: {
    username: 'Eileen',
    password: '123456'
  }
}).then(res => {
  console.log(res)
})
代码实现

首先修改类型定义:

interface AxiosRequestConfig {
  // ...
  auth?: AxiosBasicCredentials
}

interface AxiosBasicCredentials {
  username: string,
  password: string
}

接着修改合并规则,因为auth是一个对象格式,所以它的合并规则是deepMergeStrat。

core/mergeConfig.ts

  const stratKeysDeepMerge = ['headers', 'auth']

export function flattenHeaders(headers: any, method: Method): any {
// ...
  const keysToDelete = ['delete', 'get', 'head', 'options', 'post', 'put', 'patch', 'common', 'auth']
 // ...
}

修改xhr.ts

const {
      // ...
      auth
    } = config
if (auth) {
    headers['Authorization'] = `Basic ${btoa(auth.username + ':' + auth.password)}`
}
demo
axios.post('/api/extend/post',{}, {
  auth: {
    username: 'Eileen',
    password: 'Eileen123456'
  }
})

运行demo,我们可以看到,request headers中多了Authorization字段

上一篇 下一篇

猜你喜欢

热点阅读