前言
今年是2020年了,应该没有还在用userId
来鉴权了吧,也应该很少人使用cookie
来保持会话了吧?而现在更常用的是Authorization
,
关于Authorization
简略的讲一讲Authorization,如果要深入了解的话请看底部的参考文章链接。Authorization的认证方式在我接触中有两种
- Basic
- Bearer
Basic
HTTP基本认证,在请求的时候加上以下请求头:
Authorization : basic base64encode(username+":"+password))
将用户名和密码用英文冒号(:)拼接起来,并进行一次Base64编码。服务端拿到basic码,然后自己查询相关信息再按照base64encode(username+":"+password))
的方式得出当前用户的basic进行对比。
Bearer
授权完成后会返回类似下面的数据结构:
{
"token_type": "Bearer",
"access_token": "xxxxx",
"refresh_token": "xxxxx"
}
而其中的refresh_token
的作用是在access_token
失效的时候进行重新刷新传入的参数,具体怎么传要看各自项目的实现方式。access_token
就是我们的认证令牌。token_type是令牌的类型,而我现在使用到的只有bearer
,其它类型未碰到,希望各位看官能补充一下。
在使用的时候需要加上以下请求头:
Authorization : token_type access_token
也就是这样:
Authorization: Bearer xxxxx
实现
方式1 :authenticator
authenticator
是在创建OkHttpClient
的时候能够设置的一个方法,接收的是一个okhttp3.Authenticator
的interface,默认不设置的话是一个NONE
的空实现,而回调的地方是在okhttp3.internal.http.RetryAndFollowUpInterceptor.followUpRequest()