golang oauth2.0
时间: 2024-01-03 08:04:46 浏览: 98
以下是使用Golang进行OAuth 2.0的简要介绍:
1. 引入相关包:
```go
import (
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
)
```
2. 配置OAuth2.0客户端:
```go
func main() {
conf := &oauth2.Config{
ClientID: "your-client-id",
ClientSecret: "your-client-secret",
RedirectURL: "http://localhost:8080/callback",
Scopes: []string{"scope1", "scope2"},
Endpoint: google.Endpoint,
}
// ...
}
```
3. 获取授权链接:
```go
func main() {
url := conf.AuthCodeURL("state", oauth2.AccessTypeOffline)
// Redirect user to url
}
```
4. 交换授权码获取访问令牌:
```go
func handleCallback(w http.ResponseWriter, r *http.Request) {
code := r.FormValue("code")
token, err := conf.Exchange(oauth2.NoContext, code)
if err != nil {
http.Error(w, "Failed to exchange token", http.StatusInternalServerError)
return
}
// Use token
}
```
阅读全文