Go : OAuth2.0

引用

http://blog.csdn.net/wangshubo1989/article/details/77980316

引文以google为例子,这里使用github为例子(访问google有问题T_T)。

获取 oauth2

$ go get golang.org/x/oauth2

如果出现错误(被墙?),请参直接使用github下载即可。

$ mkdir -p $GOPATH/src/golang.org/x
$ cd $GOPATH/src/golang.org/x
$ git clone https://github.com/golang/oauth2.git

创建client id

访问这里: https://github.com/settings/developers, 点击“New OAuth App”,示例配置如下:

Homepage URLhttp://localhost:8000/
Authorization callback URLhttp://localhost:8000/GithubCallback

创建成功后,会生产Client IDClient Secret

源程序

package main

import (
    "fmt"
    "io/ioutil"
    "net/http"

    "golang.org/x/oauth2"
)

const htmlIndex = `<html><body>
<a href="/GithubLogin">Log in with Github</a>
</body></html>
`

// Endpoint is Github's OAuth 2.0 endpoint.
var endpoint = oauth2.Endpoint{
    AuthURL:  "https://github.com/login/oauth/authorize",
    TokenURL: "https://github.com/login/oauth/access_token",
}

var githubOauthConfig = &oauth2.Config{
    ClientID:     "YourClientID",
    ClientSecret: "YourClientSecret",
    RedirectURL:  "http://localhost:8000/GithubCallback",
    Scopes:       []string{"user", "repo"},
    Endpoint:     endpoint,
}

const oauthStateString = "random"

func main() {
    http.HandleFunc("/", handleMain)
    http.HandleFunc("/GithubLogin", handleGithubLogin)
    http.HandleFunc("/GithubCallback", handleGithubCallback)
    fmt.Println(http.ListenAndServe(":8000", nil))
}

func handleMain(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, htmlIndex)
}

func handleGithubLogin(w http.ResponseWriter, r *http.Request) {
    url := githubOauthConfig.AuthCodeURL(oauthStateString)
    fmt.Println(url)
    http.Redirect(w, r, url, http.StatusTemporaryRedirect)
}

func handleGithubCallback(w http.ResponseWriter, r *http.Request) {
    state := r.FormValue("state")
    if state != oauthStateString {
        fmt.Printf("invalid oauth state, expected '%s', got '%s'\n", oauthStateString, state)
        http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
        return
    }
    fmt.Println(state)

    code := r.FormValue("code")
    fmt.Println(code)
    token, err := githubOauthConfig.Exchange(oauth2.NoContext, code)
    fmt.Println(token)
    if err != nil {
        fmt.Printf("Code exchange failed with '%s'\n", err)
        http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
        return
    }

    response, err := http.Get("https://api.github.com/user?access_token=" + token.AccessToken)

    defer response.Body.Close()
    contents, err := ioutil.ReadAll(response.Body)
    fmt.Fprintf(w, "%s\n", contents)
}

修改上面的 ClientIDClientSecret即可。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值