如何存储访问令牌以供重复使用?

use*_*226 7 oauth go

我正在使用 go 的 oauth2 包代表用户向 Instagram 发出请求。我唯一需要弄清楚的部分是如何存储访问/刷新令牌,然后如何在 oauth2 中再次使用它?这是我到目前为止的代码,它所做的只是获取访问令牌并向 API 发出一个请求。之后我不知道该怎么办。

package main

import "net/http"
import "io/ioutil"
import "fmt"
import "html/template"
import "golang.org/x/oauth2"

var ClientID = YOUR_CLIENT_ID

var ClientSecret = YOUR_CLIENT_SECRET
var RedirectURI = "http://localhost:8080/redirect"

var authURL = "https://api.instagram.com/oauth/authorize"

var tokenURL = "https://api.instagram.com/oauth/access_token"

var templ = template.Must(template.New("index.html").ParseFiles("index.html"))

var igConf *oauth2.Config

func redirect(res http.ResponseWriter, req *http.Request) {

    code := req.FormValue("code")

    if len(code) != 0 {
        tok, err := igConf.Exchange(oauth2.NoContext, code)
        if err != nil {
            fmt.Println(err)
            http.NotFound(res, req)
            return
        }

        if tok.Valid() {
            client := igConf.Client(oauth2.NoContext, tok)

            request, err := http.NewRequest("GET", "https://api.instagram.com/v1/users/self/?access_token="+tok.AccessToken, nil)
            if err != nil {
                fmt.Println(err)
                http.NotFound(res, req)
                return
            }

            resp, err := client.Do(request)
            if err != nil {
                fmt.Println(err)
                http.NotFound(res, req)
                return
            }
            defer resp.Body.Close()

            body, err := ioutil.ReadAll(resp.Body)
            if err != nil {
                fmt.Println(err)
                http.NotFound(res, req)
                return
            }

            res.Write(body)
        }

        http.NotFound(res, req)
    }

}

func homePage(res http.ResponseWriter, req *http.Request) {
    url := igConf.AuthCodeURL("", oauth2.AccessTypeOffline)
    fmt.Println(url)
    err := templ.Execute(res, url)
    if err != nil {
        fmt.Println(err)
    }
}

func main() {
    igConf = &oauth2.Config{
        ClientID:     ClientID,
        ClientSecret: ClientSecret,
        Endpoint: oauth2.Endpoint{
            AuthURL:  authURL,
            TokenURL: tokenURL,
        },
        RedirectURL: RedirectURI,
        Scopes:      []string{"public_content", "comments"},
    }

    http.HandleFunc("/redirect", redirect)
    http.HandleFunc("/", homePage)
    http.ListenAndServe(":8080", nil)
}
Run Code Online (Sandbox Code Playgroud)

Tom*_*and 3

res.Write(body)您可以通过在函数中的行之前插入以下代码,将访问令牌存储在 cookie 中redirect()

res.SetCookie(&Cookie{
   Name: "access_token",
   Value: tok.AccessToken,
   Expires: time.Now().Add(time.Hour * 24), // expires in 24 hours
}
Run Code Online (Sandbox Code Playgroud)

在其他一些处理程序中,您将再次读回此令牌,如下所示:

accessCookie, err := req.Cookie("access_token")
if err != nil {
   res.WriteHeader(http.StatusUnauthorized)
   fmt.Fprintln(res, "no access token provided")
   return
}
accessToken := accessCookie.Value
// make your requests to Instagram here
Run Code Online (Sandbox Code Playgroud)