LoginSignup
0
2

More than 1 year has passed since last update.

Twitter Oauth1.0認証方法メモ [golang]

Last updated at Posted at 2022-05-20

Twitter開発者登録

  1. プロジェクト作成
  2. アプリ作成
    1. API KeyとAPI Secretを控えておく(ドキュメントではConsumer KeyとConsumer Secretと記載されている)
    2. Setting画面からOAuth1.0aを有効化する
    3. App permissionsを変更する(投稿処理はRead and write)
    4. Callback URI/Redirect URLを設定する
      1. 認証画面でユーザーが認証実行した後に遷移するURL

Go言語での実装

ライブラリのインストール

bash
# https://github.com/dghubble/oauth1
go get github.com/dghubble/oauth1

認証画面URLの生成

main.go
import (
	"net/url"

	"github.com/dghubble/oauth1"
	"github.com/dghubble/oauth1/twitter"
)

// oauth1のconfig作成
conf := &oauth1.Config{
	ConsumerKey:    [ConsumerKey],
	ConsumerSecret: [ConsumerSecret],
	CallbackURL:    [CallbackURL],
	Endpoint:       twitter.AuthorizeEndpoint,
}

// Oauth認証用のリクエストトークン発行
// requestTokenとrequestSecretをDBに保存しておく
requestToken, requestSecret, err := conf.RequestToken()
if err != nil {
	// エラー処理
}

// Oauth認証画面のURL発行
authorizationURL, err := conf.AuthorizationURL(requestToken)
if err != nil {
	// エラー処理
}

// フロントサイドで遷移処理を実行する
return authorizationURL

アクセストークンの生成(認証画面からのコールバック処理)

main.go
// NOTE: echo.Contextからクエリパラメータを読み取る前提で処理を記載しています
oauthToken := ec.QueryParam("oauth_token") // == request_token
oauthVerifier := ec.QueryParam("oauth_verifier")

// 認証画面URLの生成 でDBに保存したrequestSecretを
// oauthToken(requestToken)から取得
requestSecret := getRequestSecret(oauthToken)

conf := &oauth1.Config{
	ConsumerKey:    [ConsumerKey],
	ConsumerSecret: [ConsumerSecret],
	CallbackURL:    [CallbackURL],
	Endpoint:       twitter.AuthorizeEndpoint,
}

// accessToken, accessSecretをDBに保存しておく
accessToken, accessSecret, err := conf.AccessToken(oauthToken, requestSecret, oauthVerifier)
if err != nil {
	// エラー処理
}

0
2
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
2