DRYな備忘録

Don't Repeat Yourself.

Go言語でBasic認証する

f:id:otiai10:20160529022213p:plain

参考

実装

main.go

package main

import (
    "fmt"
    "net/http"

    "github.com/otiai10/marmoset"
)

// BasicAuthFilter ...
type BasicAuthFilter struct {
    next http.Handler
}

// ServeHTTP ...
func (f BasicAuthFilter) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    // r.SetBasicAuth("foo", "bar")
    if user, pass, ok := r.BasicAuth(); ok && user == "oppai" && pass == "prunprun" {
        f.next.ServeHTTP(w, r)
    } else {
        w.Header().Set("WWW-Authenticate", "Basic")
        w.WriteHeader(http.StatusUnauthorized)
        fmt.Fprint(w, "ノーおっぱい!")
    }
}

func main() {

    router := marmoset.NewRouter()
    router.GET("/", func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprint(w, "おっぱいぷるんぷるん")
    })

    http.ListenAndServe(":9090", BasicAuthFilter{router})
}

メモ: BasicAuth失敗したときのレスポンスコード

http.StatusUnauthorized == 400

メモ: ブラウザがベーシック認証のダイアログ出してくれない

レスポンスにWWW-Authenticateヘッダーが必要

javascript - How to prevent browser to invoke basic auth popup and handle 401 error using Jquery? - Stack Overflow

If the WWW-Authenticate header is missing, then the browser won't prompt for credentials.

雑感

  • AppEngineもGoでつくってるので、これでアプリケーションのレイヤーでBasic認証つけれるはず

DRY