Linux后台开发-App Sign(签名)认证-token签名认证

Linux后台开发-App Sign(签名)认证-token签名认证

最近在搞音视频聊天的项目,为了保证服务器的安全以及在以后授权给第三方使用时避免被其他人盗用AppID进行项目开发。

主要流程:

(1)业务服务器根据appid,app sign以及其他字段生成token,例如,go 语言 login_token 生成示例代码如下

func makeTokenSample(appid uint32, app_sign string, idname string, expired_add int64) (ret string, err error){
nonce := UniqueId()
expired := time.Now().Unix() + expired_add //单位:秒
app_sign = strings.Replace(app_sign, "0x","",-1)
app_sign = strings.Replace(app_sign, ",", "", -1)
if len(app_sign) < 32 {
return "", fmt.Errorf("app_key wrong")
}
app_sign_32 := app_sign[0:32]
source := fmt.Sprintf("%d%s%s%s%d",appid,app_sign_32,idname,nonce,expired)
sum := GetMd5String(source)
token := tokenInfo{}
token.Ver = 1
token.Hash = sum
token.Nonce = nonce
token.Expired = expired
buf, err := json.Marshal(token)
if err != nil {
return "", err
}
encodeString := base64.StdEncoding.EncodeToString(buf)
return encodeString, nil
}

(2)客户端去服务器端请求到token

(3)然后使用该token去主服务器进行登录认证,在登录的时候记得附带token和appid;

(4)主服务器根据appid查询到相应的App sign,并且解码base64.URLEncoding.DecodeString(token),得到nonce和expired的元素,比如

{"ver":1,"hash":"f925e8b0e70d7d7b3006e5226d471e02","nonce":"3576fa6e5000003","expired":1553247969}

hash部分就是我们要匹对的字符串,在主服务器端根据appid,app sign,nonce和expired重新生成Hash2

app_sign_32 := app_sign[0:32]
source := fmt.Sprintf("%d%s%s%s%d",appid,app_sign_32,idname,nonce,expired)
hash2:= GetMd5String(source)

匹对hash2和hash则成功则签名认证成功,特别要注意的是app sign一定不要泄露给别人,只要第三方拿到你的签名,那也是一样可以生成鉴权通过的token

鉴权成功后,expired用确定token的过期时间,如果过期则需要使用新的token进行验证。


分享到:


相關文章: