basic auth for plugin
Showing
1 changed file
with
75 additions
and
0 deletions
plugins/auth/basic.go
0 → 100644
| 1 | // basic auth for plugin | ||
| 2 | package auth | ||
| 3 | |||
| 4 | // Example: | ||
| 5 | // func SecretAuth(username, password string) bool { | ||
| 6 | // if username == "astaxie" && password == "helloBeego" { | ||
| 7 | // return true | ||
| 8 | // } | ||
| 9 | // return false | ||
| 10 | // } | ||
| 11 | // authPlugin := auth.NewBasicAuthenticator(SecretAuth) | ||
| 12 | // beego.AddFilter("*","AfterStatic",authPlugin) | ||
| 13 | |||
| 14 | import ( | ||
| 15 | "encoding/base64" | ||
| 16 | "net/http" | ||
| 17 | "strings" | ||
| 18 | |||
| 19 | "github.com/astaxie/beego" | ||
| 20 | "github.com/astaxie/beego/context" | ||
| 21 | ) | ||
| 22 | |||
| 23 | func NewBasicAuthenticator(secrets SecretProvider, Realm string) beego.FilterFunc { | ||
| 24 | return func(ctx *context.Context) { | ||
| 25 | a := &BasicAuth{Secrets: secrets, Realm: Realm} | ||
| 26 | if username := a.CheckAuth(ctx.Request); username == "" { | ||
| 27 | a.RequireAuth(ctx.ResponseWriter, ctx.Request) | ||
| 28 | } | ||
| 29 | } | ||
| 30 | } | ||
| 31 | |||
| 32 | type SecretProvider func(user, pass string) bool | ||
| 33 | |||
| 34 | type BasicAuth struct { | ||
| 35 | Secrets SecretProvider | ||
| 36 | Realm string | ||
| 37 | } | ||
| 38 | |||
| 39 | /* | ||
| 40 | Checks the username/password combination from the request. Returns | ||
| 41 | either an empty string (authentication failed) or the name of the | ||
| 42 | authenticated user. | ||
| 43 | |||
| 44 | Supports MD5 and SHA1 password entries | ||
| 45 | */ | ||
| 46 | func (a *BasicAuth) CheckAuth(r *http.Request) string { | ||
| 47 | s := strings.SplitN(r.Header.Get("Authorization"), " ", 2) | ||
| 48 | if len(s) != 2 || s[0] != "Basic" { | ||
| 49 | return "" | ||
| 50 | } | ||
| 51 | |||
| 52 | b, err := base64.StdEncoding.DecodeString(s[1]) | ||
| 53 | if err != nil { | ||
| 54 | return "" | ||
| 55 | } | ||
| 56 | pair := strings.SplitN(string(b), ":", 2) | ||
| 57 | if len(pair) != 2 { | ||
| 58 | return "" | ||
| 59 | } | ||
| 60 | |||
| 61 | if a.Secrets(pair[0], pair[1]) { | ||
| 62 | return pair[0] | ||
| 63 | } | ||
| 64 | return "" | ||
| 65 | } | ||
| 66 | |||
| 67 | /* | ||
| 68 | http.Handler for BasicAuth which initiates the authentication process | ||
| 69 | (or requires reauthentication). | ||
| 70 | */ | ||
| 71 | func (a *BasicAuth) RequireAuth(w http.ResponseWriter, r *http.Request) { | ||
| 72 | w.Header().Set("WWW-Authenticate", `Basic realm="`+a.Realm+`"`) | ||
| 73 | w.WriteHeader(401) | ||
| 74 | w.Write([]byte("401 Unauthorized\n")) | ||
| 75 | } |
-
Please register or sign in to post a comment