本文整理汇总了Golang中golang.org/x/oauth2.Config.Exchange方法的典型用法代码示例。如果您正苦于以下问题:Golang Config.Exchange方法的具体用法?Golang Config.Exchange怎么用?Golang Config.Exchange使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类golang.org/x/oauth2.Config
的用法示例。
在下文中一共展示了Config.Exchange方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: exchangeToken
func exchangeToken(ctx context.Context, config *oauth2.Config, code string) *oauth2.Token {
token, err := config.Exchange(ctx, code)
if err != nil {
glog.Fatalf("Token exchange error: %v", err)
}
return token
}
示例2: handleOAuth2Callback
func handleOAuth2Callback(config *oauth2.Config, s sessions.Session, w http.ResponseWriter, r *http.Request) {
providedState := extractPath(r.URL.Query().Get("state"))
//verify that the provided state is the state we generated
//if it is not, then redirect to the error page
originalState := s.Get(keyState)
if providedState != originalState {
http.Redirect(w, r, PathError, http.StatusFound)
return
}
next := s.Get(keyNextPage).(string)
code := r.URL.Query().Get("code")
t, err := config.Exchange(oauth2.NoContext, code)
if err != nil {
// Pass the error message, or allow dev to provide its own
// error handler.
http.Redirect(w, r, PathError, http.StatusFound)
return
}
// Store the credentials in the session.
val, _ := json.Marshal(t)
s.Set(keyToken, val)
http.Redirect(w, r, next, http.StatusFound)
}
示例3: Config
// Config does the initial creation of the token
func Config(name string, config *oauth2.Config) error {
// See if already have a token
tokenString := fs.ConfigFile.MustValue(name, "token")
if tokenString != "" {
fmt.Printf("Already have a token - refresh?\n")
if !fs.Confirm() {
return nil
}
}
// Generate a URL for the user to visit for authorization.
authUrl := config.AuthCodeURL("state")
fmt.Printf("Go to the following link in your browser\n")
fmt.Printf("%s\n", authUrl)
fmt.Printf("Log in, then type paste the token that is returned in the browser here\n")
// Read the code, and exchange it for a token.
fmt.Printf("Enter verification code> ")
authCode := fs.ReadLine()
token, err := config.Exchange(oauth2.NoContext, authCode)
if err != nil {
return fmt.Errorf("Failed to get token: %v", err)
}
return putToken(name, token)
}
示例4: _google
func (p *Engine) _google(code string) (*User, error) {
var cfg oauth2.Config
if err := p.Dao.Get("google.oauth", &cfg); err != nil {
return nil, err
}
tok, err := cfg.Exchange(oauth2.NoContext, code)
if err != nil {
return nil, err
}
cli := cfg.Client(oauth2.NoContext, tok)
res, err := cli.Get("https://www.googleapis.com/oauth2/v1/userinfo?alt=json")
if err != nil {
return nil, err
}
defer res.Body.Close()
var gu GoogleUser
dec := json.NewDecoder(res.Body)
if err := dec.Decode(&gu); err != nil {
return nil, err
}
return p.Dao.AddUser(gu.ID, "google", gu.Email, gu.Name, gu.Link, gu.Picture)
}
示例5: tokenFromWeb
func tokenFromWeb(ctx context.Context, config *oauth2.Config) *oauth2.Token {
randState := fmt.Sprintf("st%d", time.Now().UnixNano())
tokenOnce.Do(func() {
http.HandleFunc("/oauth/", func(rw http.ResponseWriter, req *http.Request) {
if req.FormValue("state") != randState {
log.Printf("State doesn't match: req = %#v", req)
http.Error(rw, "", 500)
return
}
if code := req.FormValue("code"); code != "" {
fmt.Fprintf(rw, "<h1>Success</h1>Authorized.")
rw.(http.Flusher).Flush()
ch <- code
return
}
log.Printf("no code")
http.Error(rw, "", 500)
})
})
config.RedirectURL = "http://localhost:8383/oauth/"
authURL := config.AuthCodeURL(randState)
go openURL(authURL)
log.Printf("Authorize this app at: %s", authURL)
code := <-ch
log.Printf("Got code: %s", code)
token, err := config.Exchange(ctx, code)
if err != nil {
log.Fatalf("Token exchange error: %v", err)
}
return token
}
示例6: tokenFromWeb
// Ref: https://github.com/google/google-api-go-client/blob/master/examples/calendar.go
// Copyright 2014 The Go Authors. All rights reserved.
func tokenFromWeb(ctx context.Context, config *oauth2.Config) (*oauth2.Token, error) {
ch := make(chan string)
randState := fmt.Sprintf("st%d", time.Now().UnixNano())
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/favicon.ico" {
w.WriteHeader(http.StatusNotFound)
return
}
if r.FormValue("state") != randState {
w.WriteHeader(http.StatusInternalServerError)
return
}
if code := r.FormValue("code"); code != "" {
w.Write([]byte("<h1>Success</h1>Authorized."))
w.(http.Flusher).Flush()
ch <- code
return
}
// no code
w.WriteHeader(http.StatusInternalServerError)
}))
defer ts.Close()
config.RedirectURL = ts.URL
authURL := config.AuthCodeURL(randState)
fmt.Println("Access to %s", authURL)
code := <-ch
return config.Exchange(ctx, code)
}
示例7: GetTokenFromCode
func GetTokenFromCode(config *oauth2.Config, code string) (*oauth2.Token, error) {
token, err := config.Exchange(oauth2.NoContext, code)
if err != nil {
return nil, err
}
return token, nil
}
示例8: CallbackHandler
// CallbackHandler handles OAuth2 redirection URI requests by parsing the auth
// code and state, comparing with the state value from the ctx, and obtaining
// an OAuth2 Token.
func CallbackHandler(config *oauth2.Config, success, failure ctxh.ContextHandler) ctxh.ContextHandler {
if failure == nil {
failure = gologin.DefaultFailureHandler
}
fn := func(ctx context.Context, w http.ResponseWriter, req *http.Request) {
authCode, state, err := parseCallback(req)
if err != nil {
ctx = gologin.WithError(ctx, err)
failure.ServeHTTP(ctx, w, req)
return
}
ownerState, err := StateFromContext(ctx)
if err != nil {
ctx = gologin.WithError(ctx, err)
failure.ServeHTTP(ctx, w, req)
return
}
if state != ownerState || state == "" {
ctx = gologin.WithError(ctx, ErrInvalidState)
failure.ServeHTTP(ctx, w, req)
return
}
// use the authorization code to get a Token
token, err := config.Exchange(ctx, authCode)
if err != nil {
ctx = gologin.WithError(ctx, err)
failure.ServeHTTP(ctx, w, req)
return
}
ctx = WithToken(ctx, token)
success.ServeHTTP(ctx, w, req)
}
return ctxh.ContextHandlerFunc(fn)
}
示例9: getTokenFromWeb
// getTokenFromWeb uses Config to request a Token.
// It returns the retrieved Token.
func getTokenFromWeb(config *oauth2.Config) *oauth2.Token {
ch := make(chan string)
http.HandleFunc("/auth", func(rw http.ResponseWriter, req *http.Request) {
if code := req.FormValue("code"); code != "" {
fmt.Fprintf(rw, "<h1>Success</h1>Authorized.")
rw.(http.Flusher).Flush()
ch <- code
return
}
log.Printf("no code")
http.Error(rw, "", 500)
})
authURL := config.AuthCodeURL("state-token", oauth2.AccessTypeOffline)
go openUrl(authURL)
log.Printf("Authorize this app at: %s", authURL)
code := <-ch
log.Printf("received code")
tok, err := config.Exchange(oauth2.NoContext, code)
if err != nil {
log.Fatalf("Unable to retrieve token from web %v", err)
}
return tok
}
示例10: ExecuteFlow
func ExecuteFlow(ctx context.Context, config *oauth2.Config, options ...Option) (*oauth2.Token, error) {
o := processOpts(options)
configCopy := *config
config = &configCopy
code := make(chan string)
l, err := net.Listen("tcp", o.addr)
if err != nil {
return nil, err
}
defer l.Close()
config.RedirectURL = fmt.Sprintf("http://%s/", l.Addr().String())
go http.Serve(l, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, closeMessage)
code <- r.FormValue("code") // send code to OAuth flow
}))
url := config.AuthCodeURL("", oauth2.AccessTypeOffline)
if o.noBrowser {
fmt.Fprintln(os.Stderr, visitMessage)
} else if err := openURL(url); err != nil {
fmt.Fprintln(os.Stderr, visitMessage)
} else {
fmt.Fprintln(os.Stderr, openedMessage)
}
fmt.Fprintf(os.Stderr, "\n%s\n\n", url)
fmt.Fprintln(os.Stderr, resumeMessage)
return config.Exchange(ctx, <-code)
}
示例11: handleCallback
func handleCallback(w http.ResponseWriter, r *http.Request, config *oauth2.Config, profilesURL, code string) {
token, err := config.Exchange(oauth2.NoContext, code)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
client := config.Client(oauth2.NoContext, token)
response, err := client.Get(profilesURL)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer response.Body.Close()
rawBody, err := ioutil.ReadAll(response.Body)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
s, _ := session.Manager.SessionStart(w, r)
defer s.SessionRelease(w)
s.Set("id_token", token.Extra("id_token"))
s.Set("access_token", token.AccessToken)
s.Set("profile", string(rawBody))
http.Redirect(w, r, "/user", http.StatusMovedPermanently)
}
示例12: handleOAuth2Callback
func handleOAuth2Callback(config *oauth2.Config, s sessions.Session, w http.ResponseWriter, r *http.Request) {
providedState := extractPath(r.URL.Query().Get("state"))
//fmt.Printf("Got state from request %s\n", providedState)
//verify that the provided state is the state we generated
//if it is not, then redirect to the error page
originalState := s.Get(keyState)
//fmt.Printf("Got state from session %s\n", originalState)
if providedState != originalState {
//http.Redirect(w, r, PathError, http.StatusFound)
//return
}
//next := s.Get(keyNextPage).(string)
//fmt.Printf("Got a next page from the session: %s\n", next)
next := ""
code := r.URL.Query().Get("code")
t, err := config.Exchange(oauth2.NoContext, code)
if err != nil {
// Pass the error message, or allow dev to provide its own
// error handler.
fmt.Println("There is some error in the code exchange")
http.Redirect(w, r, PathError, http.StatusFound)
return
}
// Store the credentials in the session.
val, _ := json.Marshal(t)
s.Set(KeyToken, maskval(val))
http.Redirect(w, r, next, http.StatusFound)
}
示例13: authorize
// authorize performs user authorization flow, asking for permissions grant.
func authorize(conf *oauth2.Config) (*oauth2.Token, error) {
aurl := conf.AuthCodeURL("unused", oauth2.AccessTypeOffline)
fmt.Printf("Authorize me at following URL, please:\n\n%s\n\nCode: ", aurl)
var code string
if _, err := fmt.Scan(&code); err != nil {
return nil, err
}
return conf.Exchange(context.Background(), code)
}
示例14: main
func main() {
ctx := context.Background()
provider, err := oidc.NewProvider(ctx, "https://accounts.google.com")
if err != nil {
log.Fatal(err)
}
config := oauth2.Config{
ClientID: clientID,
ClientSecret: clientSecret,
Endpoint: provider.Endpoint(),
RedirectURL: "http://127.0.0.1:5556/auth/google/callback",
Scopes: []string{oidc.ScopeOpenID, "profile", "email"},
}
state := "foobar" // Don't do this in production.
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, config.AuthCodeURL(state), http.StatusFound)
})
http.HandleFunc("/auth/google/callback", func(w http.ResponseWriter, r *http.Request) {
if r.URL.Query().Get("state") != state {
http.Error(w, "state did not match", http.StatusBadRequest)
return
}
oauth2Token, err := config.Exchange(ctx, r.URL.Query().Get("code"))
if err != nil {
http.Error(w, "Failed to exchange token: "+err.Error(), http.StatusInternalServerError)
return
}
userInfo, err := provider.UserInfo(ctx, oauth2.StaticTokenSource(oauth2Token))
if err != nil {
http.Error(w, "Failed to get userinfo: "+err.Error(), http.StatusInternalServerError)
return
}
resp := struct {
OAuth2Token *oauth2.Token
UserInfo *oidc.UserInfo
}{oauth2Token, userInfo}
data, err := json.MarshalIndent(resp, "", " ")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Write(data)
})
log.Printf("listening on http://%s/", "127.0.0.1:5556")
log.Fatal(http.ListenAndServe("127.0.0.1:5556", nil))
}
示例15: auth
func auth(conf *oauth2.Config) (*oauth2.Token, error) {
url := conf.AuthCodeURL("", oauth2.AccessTypeOffline)
fmt.Printf("Visit the URL for the auth dialog: %v\n", url)
reader := bufio.NewReader(os.Stdin)
fmt.Printf("Enter the authorization code: ")
code, _ := reader.ReadString('\n')
token, err := conf.Exchange(oauth2.NoContext, code)
if err != nil {
return nil, err
}
return token, nil
}