apiauth.go 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  1. // Copyright 2014 beego Author. All Rights Reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. // Package apiauth provides handlers to enable apiauth support.
  15. //
  16. // Simple Usage:
  17. // import(
  18. // "github.com/astaxie/beego"
  19. // "github.com/astaxie/beego/plugins/apiauth"
  20. // )
  21. //
  22. // func main(){
  23. // // apiauth every request
  24. // beego.InsertFilter("*", beego.BeforeRouter,apiauth.APIBaiscAuth("appid","appkey"))
  25. // beego.Run()
  26. // }
  27. //
  28. // Advanced Usage:
  29. //
  30. // func getAppSecret(appid string) string {
  31. // // get appsecret by appid
  32. // // maybe store in configure, maybe in database
  33. // }
  34. //
  35. // beego.InsertFilter("*", beego.BeforeRouter,apiauth.APISecretAuth(getAppSecret, 360))
  36. //
  37. // Information:
  38. //
  39. // In the request user should include these params in the query
  40. //
  41. // 1. appid
  42. //
  43. // appid is assigned to the application
  44. //
  45. // 2. signature
  46. //
  47. // get the signature use apiauth.Signature()
  48. //
  49. // when you send to server remember use url.QueryEscape()
  50. //
  51. // 3. timestamp:
  52. //
  53. // send the request time, the format is yyyy-mm-dd HH:ii:ss
  54. //
  55. package apiauth
  56. import (
  57. "bytes"
  58. "crypto/hmac"
  59. "crypto/sha256"
  60. "encoding/base64"
  61. "fmt"
  62. "net/url"
  63. "sort"
  64. "time"
  65. "github.com/astaxie/beego"
  66. "github.com/astaxie/beego/context"
  67. )
  68. // AppIDToAppSecret is used to get appsecret throw appid
  69. type AppIDToAppSecret func(string) string
  70. // APIBaiscAuth use the basic appid/appkey as the AppIdToAppSecret
  71. func APIBaiscAuth(appid, appkey string) beego.FilterFunc {
  72. ft := func(aid string) string {
  73. if aid == appid {
  74. return appkey
  75. }
  76. return ""
  77. }
  78. return APISecretAuth(ft, 300)
  79. }
  80. // APISecretAuth use AppIdToAppSecret verify and
  81. func APISecretAuth(f AppIDToAppSecret, timeout int) beego.FilterFunc {
  82. return func(ctx *context.Context) {
  83. if ctx.Input.Query("appid") == "" {
  84. ctx.ResponseWriter.WriteHeader(403)
  85. ctx.WriteString("miss query param: appid")
  86. return
  87. }
  88. appsecret := f(ctx.Input.Query("appid"))
  89. if appsecret == "" {
  90. ctx.ResponseWriter.WriteHeader(403)
  91. ctx.WriteString("not exist this appid")
  92. return
  93. }
  94. if ctx.Input.Query("signature") == "" {
  95. ctx.ResponseWriter.WriteHeader(403)
  96. ctx.WriteString("miss query param: signature")
  97. return
  98. }
  99. if ctx.Input.Query("timestamp") == "" {
  100. ctx.ResponseWriter.WriteHeader(403)
  101. ctx.WriteString("miss query param: timestamp")
  102. return
  103. }
  104. u, err := time.Parse("2006-01-02 15:04:05", ctx.Input.Query("timestamp"))
  105. if err != nil {
  106. ctx.ResponseWriter.WriteHeader(403)
  107. ctx.WriteString("timestamp format is error, should 2006-01-02 15:04:05")
  108. return
  109. }
  110. t := time.Now()
  111. if t.Sub(u).Seconds() > float64(timeout) {
  112. ctx.ResponseWriter.WriteHeader(403)
  113. ctx.WriteString("timeout! the request time is long ago, please try again")
  114. return
  115. }
  116. if ctx.Input.Query("signature") !=
  117. Signature(appsecret, ctx.Input.Method(), ctx.Request.Form, ctx.Input.URL()) {
  118. ctx.ResponseWriter.WriteHeader(403)
  119. ctx.WriteString("auth failed")
  120. }
  121. }
  122. }
  123. // Signature used to generate signature with the appsecret/method/params/RequestURI
  124. func Signature(appsecret, method string, params url.Values, RequestURL string) (result string) {
  125. var b bytes.Buffer
  126. keys := make([]string, len(params))
  127. pa := make(map[string]string)
  128. for k, v := range params {
  129. pa[k] = v[0]
  130. keys = append(keys, k)
  131. }
  132. sort.Strings(keys)
  133. for _, key := range keys {
  134. if key == "signature" {
  135. continue
  136. }
  137. val := pa[key]
  138. if key != "" && val != "" {
  139. b.WriteString(key)
  140. b.WriteString(val)
  141. }
  142. }
  143. stringToSign := fmt.Sprintf("%v\n%v\n%v\n", method, b.String(), RequestURL)
  144. sha256 := sha256.New
  145. hash := hmac.New(sha256, []byte(appsecret))
  146. hash.Write([]byte(stringToSign))
  147. return base64.StdEncoding.EncodeToString(hash.Sum(nil))
  148. }