6
5

More than 3 years have passed since last update.

golangでGoogleとOAuth2.0で彼女を作る

Last updated at Posted at 2019-05-07

趣旨

素人おじさんですが、
golangでGoogleのOAuth2.0を使ってユーザー情報を取得する方法を学びました。

背景

  • Google提供のLibraryをちゃんと使いたい
    • Libraryちゃんと使ったサンプルがあまり見当たらず
  • 説明を省略しないで動くソースを示してほしい
    • 公式サイトも途中で「以下省略」

素人の私は迷子・・・試行錯誤をした後なんとか完成したので、その過程を紹介。

事前に必要なこと

ライブラリ

GoogleのAPI用ライブラリをGet :heart:
go get -u google.golang.org/api/oauth2/v2

Google Developer Console

Google Developer ConsoleからAPIのCredentialsをGet :heart:
https://console.developers.google.com/apis/

CredentialsのAuthorised redirect URIsに、本件で使うリダイレクト用URLを登録
http://localhost:5001/loginr

ソース

こんな子たちをimport :love_hotel:

import (
    "net/http"
    "log"
  "fmt"
  "context"
  "golang.org/x/oauth2"
  "golang.org/x/oauth2/google"
  oauthapi "google.golang.org/api/oauth2/v2"
)

まずはログインページ

あなたのページからGoogleログインページへ遷移URLするためのURLを作るよ

var conf = &oauth2.Config{
  ClientID:     "Your Client ID", //あなたのやつ
  ClientSecret: "Your Client Secret", //あなたのやつ
  Scopes:       []string{oauthapi.UserinfoEmailScope},
  Endpoint: google.Endpoint,
  RedirectURL : "http://localhost:5001/loginr",
}

//URLを作れるよ。 yourStateUUIDは本来はCSRF対策用UUIDを入れる。
conf.AuthCodeURL("yourStateUUID", oauth2.AccessTypeOffline)

このURLをてきとーなところのaタグに入れれば、Googleのログインページに遷移できるよ。

だいたいこんなURLができるはず

https://accounts.google.com/o/oauth2/auth?access_type=offline&client_id=Your+Client+ID&redirect_uri=http%3A%2F%2Flocalhost%3A5001%2Floginr&response_type=code&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email&state=yourStateUUIDroot@233cc47a021e

リダイレクトページ

Googleが認証した後、Googleはあなたのサイト(指定したリダイレクトURL)にアクセスコード付きでリダイレクトしてくれるよ。
サーバー側では、そのアクセスコードを読み取ってGoogleにつないで、ユーザー情報をGet。


func LoginRHandler(w http.ResponseWriter, r *http.Request) {
  //パラメータからアクセスコードを読み取り
  code := r.URL.Query()["code"]
  if code == nil ||  len(code) == 0 {
    fmt.Fprint(w,"Invalid Parameter")
  }
  //いろいろライブラリが頑張って
  ctx := context.Background()
  tok, err := conf.Exchange(ctx, code[0])
  if err != nil {
  fmt.Fprintf(w,"OAuth Error:%v", err)
  }
  //APIクライアントができて
  client := conf.Client(ctx, tok)
  //Userinfo APIをGetしてDoして
  svr, err := oauthapi.New(client)
  ui, err := svr.Userinfo.Get().Do()
  if err != nil {
    fmt.Fprintf(w,"OAuth Error:%v", err)
  } else {
    //メールアドレス取得!
    fmt.Fprintf(w, "Your are logined as : %s",  ui.Email)
  }
}

同じような形で、いろいろなGoogle APIを呼べると思う。
GetしてDo

最後に

全ソースはこちら
https://play.golang.org/p/ghQ0_5bdBQ4

おことわり

現代文明には疎いおじさんが書いています。
私の若い頃はパンチカードが主流だったので、キータもギットも素人です。粗相がありましても多めに見て頂きやさしくご指摘頂けますと幸いです。

6
5
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
6
5