0
1

[Golang]Googleログインを実装してみる

Posted at

Golangのシンプルさと強力な機能を組み合わせて、Googleログインを実装する方法を学びます。このガイドでは、コード例と実践的なアドバイスを通じて、認証プロセスの設計と実装のコツを掴んでいきます。初心者でも理解しやすいように、基本的な原則から始めます。

Googleログインの仕組み

Googleに限らず、多くのシングルサインオンは以下のようになっています。

  1. GoogleアカウントにログインするページにコールバックするURLを踏めてリダイレクトする
  2. ログインする
  3. codeのクエリーパラメータとともにコールバック用のページに飛ぶ
  4. codeをClientIDとClientSecretを使ってアクセストークンを取得する
  5. Userテーブルを必要に応じて作成
  6. JWTを作成して必要な情報含めてフロントに返す

今回はGoogleログインができることさえ確認が出来れば良いの4までを実装する

必要なライブラリをインストール

go get golang.org/x/oauth2
go get golang.org/x/oauth2/google@v0.15.0

GCPからcredentialを取得してコードに含める

ログインの認証に必要なのは以下の3つです。
初期化関数の引数に含めてください。

  • ClientID
  • ClientSecret
  • RedirectURL
func NewGoogleOauthConfig(clientID string, clientSecret string, redirectUrl string) *oauth2.Config {
	conf := &oauth2.Config{
		RedirectURL:  redirectUrl,
		ClientID:     clientID,
		ClientSecret: clientSecret,
		Scopes:       []string{"https://www.googleapis.com/auth/userinfo.email"},
		Endpoint:     google.Endpoint,
	}

	return conf

}

GoogleアカウントにログインするページにコールバックするURLを作成する

下のコードでGoogleのログインページへのURLが生成されるので実際にログインをしてください

コールバックでエラーになっていると思いますがクエリーパラメーターにcodeがついてきているはずです。

func TestGoogleOauthConfig(t *testing.T) {
	googleOauthConfig := NewGoogleOauthConfig(clientID, clientSecret, redirectUrl)
	url := googleOauthConfig.AuthCodeURL("state", oauth2.AccessTypeOffline)
	fmt.Println(url)
}

アクセストークンを取得する

アクセストークンはconfigのライブラリの関数のレシーバー関数で簡単に取得することができます。

func GetUserInfo(conf *oauth2.Config, token *oauth2.Token) (string, error) {
	client := conf.Client(oauth2.NoContext, token)
	response, err := client.Get("https://www.googleapis.com/oauth2/v2/userinfo")
	if err != nil {
		return "", err
	}

	userInfo := make(map[string]interface{})
	err = json.NewDecoder(response.Body).Decode(&userInfo)
	if err != nil {
		return "", err
	}
	fmt.Println(userInfo)
	userName := userInfo["email"].(string)

	return userName, nil
}

func Show(w http.ResponseWriter, r *http.Request) {
	code := r.URL.Query().Get("code")

	clientID := ""
	clientSecret := ""
	redirectUrl := ""
	googleOauthConfig := NewGoogleOauthConfig(clientID, clientSecret, redirectUrl)
	token, err := GetAccessToken(googleOauthConfig, code)
	if err != nil {
		fmt.Println(err)
	}
	username, err := GetUserInfo(googleOauthConfig, token)
	if err != nil {
		fmt.Println(err)
	}
   w.Write([]byte(username))
}

func main() {
	http.HandleFunc("/callback", Show)
	http.ListenAndServe(":3000", nil)
}


このコードを実行してから先ほとのログインの手順を実行して見てください。

これでブラウザでgmailのアドレス表示されます。

質問等があるかた

質問はTwitterで募集しております

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1