func Callback(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "text/html; charset=utf-8") //check state validity, see url := Config.AuthCodeURL(state) above state_check := r.FormValue("state") if State != state_check { http.Error(w, fmt.Sprintf("Wrong state string: Expected %s, got %s. Please, try again", State, state_check), http.StatusBadRequest) return } token, err := GetConfig().Exchange(oauth2.NoContext, r.FormValue("code")) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } client := GetConfig().Client(oauth2.NoContext, token) service, err := goauth2.New(client) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } uService := goauth2.NewUserinfoService(service) gouser, err := uService.Get().Do() if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } fmt.Fprintf(w, "Username: %s %s<br>ID: %s<br>Email: %s<br>Picture: %s<br>", gouser.GivenName, gouser.FamilyName, gouser.Id, gouser.Email, gouser.Picture) }
func mainhandler(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "text/plain") ctx := appengine.NewContext(r) //src := google.AppEngineTokenSource(ctx, oauthsvc.UserinfoEmailScope) src, err := google.DefaultTokenSource(ctx, oauthsvc.UserinfoEmailScope) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) } client := &http.Client{ Transport: &oauth2.Transport{ Source: src, Base: &urlfetch.Transport{Context: ctx}, }, } client = oauth2.NewClient(ctx, src) service, err := oauthsvc.New(client) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) } ui, err := service.Userinfo.Get().Do() if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) } log.Infof(ctx, "UserInfo: %v", ui.Email) fmt.Fprintln(w, "UserInfo: ", ui.Email) }
// googleHandler is a ContextHandler that gets the OAuth2 Token from the ctx // to get the corresponding Google Userinfoplus. If successful, the user info // is added to the ctx and the success handler is called. Otherwise, the // failure handler is called. func googleHandler(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) { token, err := oauth2Login.TokenFromContext(ctx) if err != nil { ctx = gologin.WithError(ctx, err) failure.ServeHTTP(ctx, w, req) return } httpClient := config.Client(ctx, token) googleService, err := google.New(httpClient) if err != nil { ctx = gologin.WithError(ctx, err) failure.ServeHTTP(ctx, w, req) return } userInfoPlus, err := googleService.Userinfo.Get().Do() err = validateResponse(userInfoPlus, err) if err != nil { ctx = gologin.WithError(ctx, err) failure.ServeHTTP(ctx, w, req) return } ctx = WithUser(ctx, userInfoPlus) success.ServeHTTP(ctx, w, req) } return ctxh.ContextHandlerFunc(fn) }
func main() { //serviceAccountJSONFile := "YOUR_SERVICE_ACCOUNT_JSON_FILE" //dat, err := ioutil.ReadFile(serviceAccountJSONFile) //if err != nil { // log.Fatalf("Unable to read service account file %v", err) //} //conf, err := google.JWTConfigFromJSON(dat, oauthsvc.UserinfoEmailScope) //if err != nil { // log.Fatalf("Unable to acquire generate config: %v", err) //} //src := conf.TokenSource(oauth2.NoContext) //client := conf.Client(oauth2.NoContext) os.Setenv("GOOGLE_APPLICATION_CREDENTIALS", serviceAccountJSONFile) src, err := google.DefaultTokenSource(oauth2.NoContext, oauthsvc.UserinfoEmailScope) if err != nil { log.Fatalf("Unable to acquire token source: %v", err) } client := oauth2.NewClient(context.Background(), src) service, err := oauthsvc.New(client) if err != nil { log.Fatalf("Unable to create api service: %v", err) } ui, err := service.Userinfo.Get().Do() if err != nil { log.Fatalf("Unable to get userinfo: ", err) } log.Printf("UserInfo: %v", ui.Email) }
func main() { conf := &oauth2.Config{ ClientID: "YOUR_CLIENT_ID", ClientSecret: "YOUR_CLIENT_SECRET", RedirectURL: "urn:ietf:wg:oauth:2.0:oob", Scopes: []string{ oauthsvc.UserinfoEmailScope, }, Endpoint: google.Endpoint, } url := conf.AuthCodeURL("state") log.Println("Visit the URL for the auth dialog: ", url) var code string log.Print("Enter auth token: ") if _, err := fmt.Scan(&code); err != nil { log.Fatalf(err.Error()) } tok, err := conf.Exchange(context.Background(), code) if err != nil { log.Fatalf(err.Error()) } //client := conf.Client(context.Background(),tok) src := conf.TokenSource(context.Background(), tok) client := oauth2.NewClient(context.Background(), src) service, err := oauthsvc.New(client) if err != nil { log.Fatalf("Unable to create oauth2 client: %v", err) } ui, err := service.Userinfo.Get().Do() if err != nil { log.Fatalf("ERROR: ", err) } log.Printf("UserInfo: %v", ui.Email) }
//GoogleCallback handles /google_callback route func GoogleCallback(w http.ResponseWriter, r *http.Request) { tmpl := context.Get(r, "template").(*template.Template) session := context.Get(r, "session").(*sessions.Session) state := r.FormValue("state") if oauthState != state { err := fmt.Errorf("Wrong state string: Expected %s, got %s. Please, try again", oauthState, state) log.Printf("ERROR: %s\n", err) w.WriteHeader(400) tmpl.Lookup("errors/400").Execute(w, shared.ErrorData(err)) return } token, err := goConfig().Exchange(oauth2.NoContext, r.FormValue("code")) if err != nil { log.Printf("ERROR: %s\n", err) w.WriteHeader(400) tmpl.Lookup("errors/400").Execute(w, shared.ErrorData(err)) return } client := goConfig().Client(oauth2.NoContext, token) service, err := goauth2.New(client) if err != nil { log.Printf("ERROR: %s\n", err) w.WriteHeader(400) tmpl.Lookup("errors/400").Execute(w, shared.ErrorData(err)) return } uService := goauth2.NewUserinfoService(service) gouser, err := uService.Get().Do() if err != nil { log.Printf("ERROR: %s\n", err) w.WriteHeader(400) tmpl.Lookup("errors/400").Execute(w, shared.ErrorData(err)) return } redirectURL := session.Values["oauth_redirect"] delete(session.Values, "oauth_redirect") session.Values["oauth_email"] = gouser.Email session.Values["oauth_name"] = gouser.GivenName + " " + gouser.FamilyName session.Save(r, w) if url, ok := redirectURL.(string); ok { http.Redirect(w, r, url, 303) } else { http.Redirect(w, r, "/", 303) } }
func setupClients(client *http.Client) { var err error loginClient = client oauthSvc, err = oauth.New(client) if err != nil { log.Fatalf("Unable to create OAuth service: %v", err) } drvSvc, err = drive.New(client) if err != nil { log.Fatalf("Unable to create Drive service: %v", err) } }
func main() { //src := google.ComputeTokenSource("") src, err := google.DefaultTokenSource(oauth2.NoContext, oauthsvc.UserinfoEmailScope) if err != nil { log.Fatalf("Unable to acquire token source: %v", err) } client := oauth2.NewClient(context.Background(), src) service, err := oauthsvc.New(client) if err != nil { log.Fatalf("Unable to create api service: %v", err) } ui, err := service.Userinfo.Get().Do() if err != nil { log.Fatalf("Unable to get userinfo: ", err) } log.Printf("UserInfo: %v", ui.Email) }
func (o oauthHandler) ServeHTTP(rw http.ResponseWriter, req *http.Request) { ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() code := req.FormValue("code") t, err := o.cfg.Exchange(ctx, code) if err != nil { glog.Warningf("Got error: %v", err) panic("foo") } httpClient := o.cfg.Client(ctx, t) oauth2Service, err := goauth2.New(httpClient) if err != nil { glog.Warningf("Got error getting http client: %v", err) panic("bar") } tokInfo, err := oauth2Service. Tokeninfo(). Context(ctx). AccessToken(t.AccessToken). Do() if err != nil { glog.Warningf("Got error getting token info: %v", err) panic("baz") } if uid, ok := o.emailToUserId[tokInfo.Email]; ok && tokInfo.VerifiedEmail { o.crypter.SetAuthCookie(rw, &pb.AuthCookie{User: uid}) var state pb.OAuthState redirectPath := "/" if DecryptProto(o.aead, req.FormValue("state"), nil, &state) { redirectPath = state.Path } http.Redirect(rw, req, redirectPath, http.StatusFound) return } http.Redirect(rw, req, "/unauthorized", http.StatusFound) }