Created
August 16, 2016 11:51
-
-
Save utahta/6910a402c7a8b7faa6ba32b4c41157e4 to your computer and use it in GitHub Desktop.
Google OAuth2 Token
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/json" | |
"fmt" | |
"io/ioutil" | |
"log" | |
"strings" | |
"golang.org/x/oauth2" | |
) | |
type Auth struct { | |
ClientID string | |
Secret string | |
RedirectUrl string | |
Scopes []string | |
} | |
func GetAuthInfo() *Auth { | |
auth := &Auth{ | |
ClientID: "", | |
Secret: "", | |
RedirectUrl: "urn:ietf:wg:oauth:2.0:oob", | |
Scopes: []string{}, | |
} | |
inputNewData(auth) | |
return auth | |
} | |
func inputNewData(auth *Auth) { | |
fmt.Printf("Input ClientID: ") | |
fmt.Scanf("%s\n", &auth.ClientID) | |
fmt.Printf("Input Secret: ") | |
fmt.Scanf("%s\n", &auth.Secret) | |
var scopes string | |
fmt.Printf("Input Scopes: ") | |
fmt.Scanf("%s\n", &scopes) | |
auth.Scopes = strings.Split(scopes, ",") | |
} | |
func main() { | |
// 認証情報の取得(何もなければ、入力を促します) | |
// clientID, secret は Developers Console の Credentials からコピー&ペーストして下さい。 | |
auth := GetAuthInfo() | |
fmt.Println("Start Execute API") | |
config := &oauth2.Config{ | |
ClientID: auth.ClientID, | |
ClientSecret: auth.Secret, | |
RedirectURL: auth.RedirectUrl, | |
Scopes: auth.Scopes, | |
Endpoint: oauth2.Endpoint{ | |
AuthURL: "https://accounts.google.com/o/oauth2/auth", | |
TokenURL: "https://accounts.google.com/o/oauth2/token", | |
}, | |
} | |
// 認証コードなし=>ブラウザで認証させるためにURLを出力 | |
url := config.AuthCodeURL("") | |
fmt.Println("ブラウザで以下のURLにアクセスし、認証して下さい。") | |
fmt.Println(url) | |
fmt.Println("") | |
// 認証コードを入力 | |
fmt.Printf("Input auth code: ") | |
var code string | |
fmt.Scanf("%s\n", &code) | |
// 認証トークンを取得する | |
token, err := config.Exchange(oauth2.NoContext, code) | |
if err != nil { | |
log.Fatal(err) | |
} | |
text, err := json.Marshal(token) | |
if err != nil { | |
log.Fatal(err) | |
} | |
err = ioutil.WriteFile("token.json", text, 0777) | |
if err != nil { | |
log.Fatal(err) | |
} | |
fmt.Println("token is saved to token.json") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment