1
0
mirror of https://github.com/astaxie/beego.git synced 2024-11-01 09:20:55 +00:00
Beego/plugins/apiauth/apiauth.go

181 lines
4.7 KiB
Go
Raw Normal View History

2014-08-27 16:25:50 +00:00
// Copyright 2014 beego Author. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package apiauth provides handlers to enable apiauth support.
2014-08-28 02:21:32 +00:00
//
2014-08-27 16:25:50 +00:00
// Simple Usage:
// import(
// "github.com/astaxie/beego"
// "github.com/astaxie/beego/plugins/apiauth"
// )
//
// func main(){
// // apiauth every request
2014-08-28 02:05:02 +00:00
// beego.InsertFilter("*", beego.BeforeRouter,apiauth.APIBaiscAuth("appid","appkey"))
2014-08-27 16:25:50 +00:00
// beego.Run()
// }
//
2014-08-28 02:05:02 +00:00
// Advanced Usage:
//
// func getAppSecret(appid string) string {
// // get appsecret by appid
2014-08-28 02:21:32 +00:00
// // maybe store in configure, maybe in database
2014-08-28 02:05:02 +00:00
// }
//
2015-09-12 14:03:45 +00:00
// beego.InsertFilter("*", beego.BeforeRouter,apiauth.APISecretAuth(getAppSecret, 360))
2014-08-28 02:05:02 +00:00
//
2016-03-11 04:14:18 +00:00
// Information:
2014-08-28 02:21:32 +00:00
//
// In the request user should include these params in the query
2014-08-28 02:05:02 +00:00
//
2014-08-28 02:21:32 +00:00
// 1. appid
2014-08-28 02:05:02 +00:00
//
2016-01-17 15:48:17 +00:00
// appid is assigned to the application
2014-08-28 02:05:02 +00:00
//
2014-08-28 02:21:32 +00:00
// 2. signature
2014-08-28 02:05:02 +00:00
//
2014-08-28 02:21:32 +00:00
// get the signature use apiauth.Signature()
2014-08-28 02:05:02 +00:00
//
2014-08-28 02:21:32 +00:00
// when you send to server remember use url.QueryEscape()
2014-08-28 02:05:02 +00:00
//
2014-08-28 02:21:32 +00:00
// 3. timestamp:
2014-08-28 02:05:02 +00:00
//
// send the request time, the format is yyyy-mm-dd HH:ii:ss
//
2014-08-27 16:25:50 +00:00
package apiauth
import (
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"fmt"
"net/url"
"sort"
"time"
"github.com/astaxie/beego"
"github.com/astaxie/beego/context"
)
2015-09-12 14:03:45 +00:00
// AppIDToAppSecret is used to get appsecret throw appid
type AppIDToAppSecret func(string) string
2014-08-27 16:25:50 +00:00
2015-09-12 14:03:45 +00:00
// APIBaiscAuth use the basic appid/appkey as the AppIdToAppSecret
2014-08-27 16:25:50 +00:00
func APIBaiscAuth(appid, appkey string) beego.FilterFunc {
ft := func(aid string) string {
if aid == appid {
return appkey
}
return ""
}
2015-09-12 14:03:45 +00:00
return APISecretAuth(ft, 300)
2014-08-27 16:25:50 +00:00
}
2015-09-12 14:03:45 +00:00
// APISecretAuth use AppIdToAppSecret verify and
func APISecretAuth(f AppIDToAppSecret, timeout int) beego.FilterFunc {
2014-08-27 16:25:50 +00:00
return func(ctx *context.Context) {
if ctx.Input.Query("appid") == "" {
ctx.ResponseWriter.WriteHeader(403)
2014-08-27 16:25:50 +00:00
ctx.WriteString("miss query param: appid")
return
}
appsecret := f(ctx.Input.Query("appid"))
if appsecret == "" {
ctx.ResponseWriter.WriteHeader(403)
2014-08-27 16:25:50 +00:00
ctx.WriteString("not exist this appid")
return
}
if ctx.Input.Query("signature") == "" {
ctx.ResponseWriter.WriteHeader(403)
2014-08-27 16:25:50 +00:00
ctx.WriteString("miss query param: signature")
return
}
if ctx.Input.Query("timestamp") == "" {
ctx.ResponseWriter.WriteHeader(403)
2014-08-27 16:25:50 +00:00
ctx.WriteString("miss query param: timestamp")
return
}
u, err := time.Parse("2006-01-02 15:04:05", ctx.Input.Query("timestamp"))
if err != nil {
ctx.ResponseWriter.WriteHeader(403)
2014-08-27 16:25:50 +00:00
ctx.WriteString("timestamp format is error, should 2006-01-02 15:04:05")
return
}
t := time.Now()
2014-08-28 02:05:02 +00:00
if t.Sub(u).Seconds() > float64(timeout) {
ctx.ResponseWriter.WriteHeader(403)
2014-08-27 16:25:50 +00:00
ctx.WriteString("timeout! the request time is long ago, please try again")
return
}
if ctx.Input.Query("signature") !=
2015-09-12 14:03:45 +00:00
Signature(appsecret, ctx.Input.Method(), ctx.Request.Form, ctx.Input.URI()) {
ctx.ResponseWriter.WriteHeader(403)
2014-08-27 16:25:50 +00:00
ctx.WriteString("auth failed")
}
}
}
2015-09-12 14:03:45 +00:00
// Signature used to generate signature with the appsecret/method/params/RequestURI
2014-08-27 16:25:50 +00:00
func Signature(appsecret, method string, params url.Values, RequestURI string) (result string) {
var query string
pa := make(map[string]string)
for k, v := range params {
pa[k] = v[0]
}
vs := mapSorter(pa)
vs.Sort()
for i := 0; i < vs.Len(); i++ {
if vs.Keys[i] == "signature" {
continue
}
if vs.Keys[i] != "" && vs.Vals[i] != "" {
query = fmt.Sprintf("%v%v%v", query, vs.Keys[i], vs.Vals[i])
}
}
2015-09-12 14:03:45 +00:00
stringToSign := fmt.Sprintf("%v\n%v\n%v\n", method, query, RequestURI)
2014-08-27 16:25:50 +00:00
sha256 := sha256.New
hash := hmac.New(sha256, []byte(appsecret))
2015-09-12 14:03:45 +00:00
hash.Write([]byte(stringToSign))
2014-08-28 02:05:02 +00:00
return base64.StdEncoding.EncodeToString(hash.Sum(nil))
2014-08-27 16:25:50 +00:00
}
type valSorter struct {
Keys []string
Vals []string
}
func mapSorter(m map[string]string) *valSorter {
vs := &valSorter{
Keys: make([]string, 0, len(m)),
Vals: make([]string, 0, len(m)),
}
for k, v := range m {
vs.Keys = append(vs.Keys, k)
vs.Vals = append(vs.Vals, v)
}
return vs
}
func (vs *valSorter) Sort() {
sort.Sort(vs)
}
func (vs *valSorter) Len() int { return len(vs.Keys) }
func (vs *valSorter) Less(i, j int) bool { return vs.Keys[i] < vs.Keys[j] }
func (vs *valSorter) Swap(i, j int) {
vs.Vals[i], vs.Vals[j] = vs.Vals[j], vs.Vals[i]
vs.Keys[i], vs.Keys[j] = vs.Keys[j], vs.Keys[i]
}