Google App EngineにGoのWebAppをデプロイするために、いろいろ調査

Users API

Users Go API Overview  |  App Engine standard environment for Go  |  Google Cloud Platform

Users APIで何ができる?

  • ログイン中のuserを確認する
  • 認証用のページへユーザを誘導。(redirect)
  • Googleアカウントを持ってないユーザに新しいアカウントを作ってもらったり。

ユーザ認証

認証済の場合、ログアウト用のURLを取得し、ページに表示させる。 未認証の場合、ログイン用のURLを取得し、ページに表示させる。

import (
        "fmt"
        "net/http"

        "google.golang.org/appengine"
        "google.golang.org/appengine/user"
)

func welcome(w http.ResponseWriter, r *http.Request) {
        w.Header().Set("Content-type", "text/html; charset=utf-8")
        ctx := appengine.NewContext(r)
        u := user.Current(ctx)
        if u == nil {
                url, _ := user.LoginURL(ctx, "/")
                fmt.Fprintf(w, `<a href="%s">Sign in or register</a>`, url)
                return
        }
        url, _ := user.LogoutURL(ctx, "/")
        fmt.Fprintf(w, `Welcome, %s! (<a href="%s">sign out</a>)`, u, url)
}

管理者としての登録を強制させる

登録必須のページが存在する場合、app.yamlを利用して、ユーザに強制登録してもらうことが可能。
必要なロールなどを設定に任せば、認証メカニズムを独自に実装しなて済む。
詳細はyamlの設定を参照。

app.yaml Reference  |  App Engine standard environment for Go  |  Google Cloud Platform

OAuthの利用

標準ユーザ認証以外に、OAuthを利用することも可能。
※OAuthは認証プロトコルで、ユーザは第三者(アプリケーション)に許可を与えることで第三者がユーザの情報にアクセスできる。

import (
        "fmt"
        "net/http"

        "google.golang.org/appengine"
        "google.golang.org/appengine/user"
)

func welcomeOAuth(w http.ResponseWriter, r *http.Request) {
        ctx := appengine.NewContext(r)
        u, err := user.CurrentOAuth(ctx, "")
        if err != nil {
                http.Error(w, "OAuth Authorization header required", http.StatusUnauthorized)
                return
        }
        if !u.Admin {
                http.Error(w, "Admin login only", http.StatusUnauthorized)
                return
        }
        fmt.Fprintf(w, `Welcome, admin user %s!`, u)
}

認証のoptions

認証方法を選択することも可能。(設定変更することで)以下の方法がある。

Googleアカウントと開発サーバー

開発サーバーのシミュレーターはダミーの認証を提供する。これを利用すればユーザ認証、管理者認証のテストが容易にできる。