本文整理汇总了Golang中golang.org/x/oauth2/google.DefaultTokenSource函数的典型用法代码示例。如果您正苦于以下问题:Golang DefaultTokenSource函数的具体用法?Golang DefaultTokenSource怎么用?Golang DefaultTokenSource使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了DefaultTokenSource函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。
示例1: main
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)
}
开发者ID:salrashid123,项目名称:gcpsamples,代码行数:32,代码来源:main.go
示例2: getBucket
func getBucket(ctx context.Context) (b gcs.Bucket, err error) {
if *fBucket == "" {
err = errors.New("You must set --bucket.")
return
}
// Set up the token source.
const scope = gcs.Scope_ReadOnly
tokenSrc, err := google.DefaultTokenSource(context.Background(), scope)
if err != nil {
err = fmt.Errorf("DefaultTokenSource: %v", err)
return
}
// Use that to create a GCS connection.
cfg := &gcs.ConnConfig{
TokenSource: tokenSrc,
}
conn, err := gcs.NewConn(cfg)
if err != nil {
err = fmt.Errorf("NewConn: %v", err)
return
}
// Open the bucket.
b, err = conn.OpenBucket(ctx, *fBucket)
if err != nil {
err = fmt.Errorf("OpenBucket: %v", err)
return
}
return
}
开发者ID:okdave,项目名称:gcloud,代码行数:34,代码来源:main.go
示例3: NewHTTPClient
// NewHTTPClient returns an HTTP client for use communicating with a Google cloud
// service, configured with the given ClientOptions. It also returns the endpoint
// for the service as specified in the options.
func NewHTTPClient(ctx context.Context, opts ...option.ClientOption) (*http.Client, string, error) {
var o internal.DialSettings
for _, opt := range opts {
opt.Apply(&o)
}
if o.GRPCConn != nil {
return nil, "", errors.New("unsupported gRPC connection specified")
}
// TODO(djd): Set UserAgent on all outgoing requests.
if o.HTTPClient != nil {
return o.HTTPClient, o.Endpoint, nil
}
if o.ServiceAccountJSONFilename != "" {
ts, err := serviceAcctTokenSource(ctx, o.ServiceAccountJSONFilename, o.Scopes...)
if err != nil {
return nil, "", err
}
o.TokenSource = ts
}
if o.TokenSource == nil {
var err error
o.TokenSource, err = google.DefaultTokenSource(ctx, o.Scopes...)
if err != nil {
return nil, "", fmt.Errorf("google.DefaultTokenSource: %v", err)
}
}
return oauth2.NewClient(ctx, o.TokenSource), o.Endpoint, nil
}
开发者ID:spxtr,项目名称:contrib,代码行数:31,代码来源:dial.go
示例4: NewApplicationDefault
// NewApplicationDefault returns "Application Default Credentials". For more
// detail, see https://developers.google.com/accounts/docs/application-default-credentials.
func NewApplicationDefault(ctx context.Context, scope ...string) (credentials.PerRPCCredentials, error) {
t, err := google.DefaultTokenSource(ctx, scope...)
if err != nil {
return nil, err
}
return TokenSource{t}, nil
}
开发者ID:chinahbcq,项目名称:grpc-go,代码行数:9,代码来源:oauth.go
示例5: newGCPAuthProvider
func newGCPAuthProvider() (restclient.AuthProvider, error) {
ts, err := google.DefaultTokenSource(context.TODO(), "https://www.googleapis.com/auth/cloud-platform")
if err != nil {
return nil, err
}
return &gcpAuthProvider{ts}, nil
}
开发者ID:Clarifai,项目名称:kubernetes,代码行数:7,代码来源:gcp.go
示例6: DialGRPC
// DialGRPC returns a GRPC connection for use communicating with a Google cloud
// service, configured with the given ClientOptions.
func DialGRPC(ctx context.Context, opts ...option.ClientOption) (*grpc.ClientConn, error) {
var o internal.DialSettings
for _, opt := range opts {
opt.Apply(&o)
}
if o.HTTPClient != nil {
return nil, errors.New("unsupported HTTP client specified")
}
if o.GRPCConn != nil {
return o.GRPCConn, nil
}
if o.TokenSource == nil {
var err error
o.TokenSource, err = google.DefaultTokenSource(ctx, o.Scopes...)
if err != nil {
return nil, fmt.Errorf("google.DefaultTokenSource: %v", err)
}
}
grpcOpts := []grpc.DialOption{
grpc.WithPerRPCCredentials(oauth.TokenSource{o.TokenSource}),
grpc.WithTransportCredentials(credentials.NewClientTLSFromCert(nil, "")),
}
if appengineDialerHook != nil {
// Use the Socket API on App Engine.
grpcOpts = append(grpcOpts, appengineDialerHook(ctx))
}
grpcOpts = append(grpcOpts, o.GRPCDialOpts...)
if o.UserAgent != "" {
grpcOpts = append(grpcOpts, grpc.WithUserAgent(o.UserAgent))
}
return grpc.Dial(o.Endpoint, grpcOpts...)
}
开发者ID:Ropes,项目名称:pubbing,代码行数:34,代码来源:dial.go
示例7: mainhandler
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)
}
开发者ID:salrashid123,项目名称:gcpsamples,代码行数:26,代码来源:main.go
示例8: init
func init() {
bucket := os.Getenv("REGISTRY_STORAGE_GCS_BUCKET")
credentials := os.Getenv("GOOGLE_APPLICATION_CREDENTIALS")
// Skip GCS storage driver tests if environment variable parameters are not provided
skipGCS = func() string {
if bucket == "" || credentials == "" {
return "The following environment variables must be set to enable these tests: REGISTRY_STORAGE_GCS_BUCKET, GOOGLE_APPLICATION_CREDENTIALS"
}
return ""
}
if skipGCS() != "" {
return
}
root, err := ioutil.TempDir("", "driver-")
if err != nil {
panic(err)
}
defer os.Remove(root)
var ts oauth2.TokenSource
var email string
var privateKey []byte
ts, err = google.DefaultTokenSource(ctx.Background(), storage.ScopeFullControl)
if err != nil {
// Assume that the file contents are within the environment variable since it exists
// but does not contain a valid file path
jwtConfig, err := google.JWTConfigFromJSON([]byte(credentials), storage.ScopeFullControl)
if err != nil {
panic(fmt.Sprintf("Error reading JWT config : %s", err))
}
email = jwtConfig.Email
privateKey = []byte(jwtConfig.PrivateKey)
if len(privateKey) == 0 {
panic("Error reading JWT config : missing private_key property")
}
if email == "" {
panic("Error reading JWT config : missing client_email property")
}
ts = jwtConfig.TokenSource(ctx.Background())
}
gcsDriverConstructor = func(rootDirectory string) (storagedriver.StorageDriver, error) {
parameters := driverParameters{
bucket: bucket,
rootDirectory: root,
email: email,
privateKey: privateKey,
client: oauth2.NewClient(ctx.Background(), ts),
}
return New(parameters)
}
testsuites.RegisterSuite(func() (storagedriver.StorageDriver, error) {
return gcsDriverConstructor(root)
}, skipGCS)
}
开发者ID:dalsh,项目名称:distribution,代码行数:60,代码来源:gcs_test.go
示例9: DialGRPC
// DialGRPC returns a GRPC connection for use communicating with a Google cloud
// service, configured with the given ClientOptions.
func DialGRPC(ctx context.Context, opt ...cloud.ClientOption) (*grpc.ClientConn, error) {
var o opts.DialOpt
for _, opt := range opt {
opt.Resolve(&o)
}
if o.HTTPClient != nil {
return nil, errors.New("unsupported HTTP base transport specified")
}
if o.GRPCClient != nil {
return o.GRPCClient, nil
}
if o.TokenSource == nil {
var err error
o.TokenSource, err = google.DefaultTokenSource(ctx, o.Scopes...)
if err != nil {
return nil, fmt.Errorf("google.DefaultTokenSource: %v", err)
}
}
grpcOpts := []grpc.DialOption{
grpc.WithPerRPCCredentials(oauth.TokenSource{o.TokenSource}),
grpc.WithTransportCredentials(credentials.NewClientTLSFromCert(nil, "")),
}
grpcOpts = append(grpcOpts, o.GRPCDialOpts...)
if o.UserAgent != "" {
grpcOpts = append(grpcOpts, grpc.WithUserAgent(o.UserAgent))
}
return grpc.Dial(o.Endpoint, grpcOpts...)
}
开发者ID:otsimo,项目名称:watch,代码行数:30,代码来源:dial.go
示例10: getAppDefaultClientArgs
func getAppDefaultClientArgs() (*context.Context, *cloud.ClientOption, error) {
ctx := oauth2.NoContext
tokenSrc, err := google.DefaultTokenSource(ctx, ScopeCloudPlatform)
if err != nil {
return nil, nil, err
}
clientOption := cloud.WithTokenSource(tokenSrc)
return &ctx, &clientOption, nil
}
开发者ID:dhermes,项目名称:gcloud-golang-bigtable-examples,代码行数:10,代码来源:helpers.go
示例11: init
func init() {
ctx = context.Background()
var err error
defaultTokenSource, err = google.DefaultTokenSource(ctx,
storage.ScopeFullControl,
)
if err != nil || defaultTokenSource == nil {
public.LogE.Fatalf("Error getting storage token source: %s\n", err.Error())
}
}
开发者ID:mshockwave,项目名称:nthuaplus-backend,代码行数:12,代码来源:storage.go
示例12: initGCE
func initGCE() error {
initGCECalled = true
// Use the staging project if not on GCE. This assumes the DefaultTokenSource
// credential used below has access to that project.
if !metadata.OnGCE() {
projectID = stagingProjectID
}
var err error
projectID, err = metadata.ProjectID()
if err != nil {
return fmt.Errorf("failed to get current GCE ProjectID: %v", err)
}
inStaging = projectID == stagingProjectID
if inStaging {
log.Printf("Running in staging cluster (%q)", projectID)
}
tokenSource, _ = google.DefaultTokenSource(oauth2.NoContext)
httpClient := oauth2.NewClient(oauth2.NoContext, tokenSource)
serviceCtx = cloud.NewContext(projectID, httpClient)
projectZone, err = metadata.Get("instance/zone")
if err != nil || projectZone == "" {
return fmt.Errorf("failed to get current GCE zone: %v", err)
}
// Convert the zone from "projects/1234/zones/us-central1-a" to "us-central1-a".
projectZone = path.Base(projectZone)
if !hasComputeScope() {
return errors.New("The coordinator is not running with access to read and write Compute resources. VM support disabled.")
}
projectRegion = projectZone[:strings.LastIndex(projectZone, "-")] // "us-central1"
externalIP, err = metadata.ExternalIP()
if err != nil {
return fmt.Errorf("ExternalIP: %v", err)
}
computeService, _ = compute.New(httpClient)
errTryDeps = checkTryBuildDeps()
if errTryDeps != nil {
log.Printf("TryBot builders disabled due to error: %v", errTryDeps)
} else {
log.Printf("TryBot builders enabled.")
}
go gcePool.pollQuotaLoop()
return nil
}
开发者ID:way-2-go,项目名称:build,代码行数:50,代码来源:gce.go
示例13: getToken
func getToken() string {
os.Setenv("GOOGLE_APPLICATION_CREDENTIALS", "grpc-go16-dev-608d72c9bce0.json")
const scope = "https://www.googleapis.com/auth/bigtable.data"
ts, err := google.DefaultTokenSource(context.Background(), scope)
if err != nil {
log.Fatal("DefaultTokenSource:", err)
}
tk, err := ts.Token()
if err != nil {
log.Fatal("Token:", err)
}
return tk.AccessToken
}
开发者ID:bradfitz,项目名称:grpc-go16-demo,代码行数:14,代码来源:demo.go
示例14: NewContext
func NewContext() (*Context, error) {
ctx := &Context{
apiRateGate: time.NewTicker(time.Second / 10).C,
}
background := context.Background()
tokenSource, err := google.DefaultTokenSource(background, compute.CloudPlatformScope)
if err != nil {
return nil, fmt.Errorf("failed to get a token source: %v", err)
}
httpClient := oauth2.NewClient(background, tokenSource)
ctx.computeService, _ = compute.New(httpClient)
// Obtain project name, zone and current instance IP address.
ctx.ProjectID, err = ctx.getMeta("project/project-id")
if err != nil {
return nil, fmt.Errorf("failed to query gce project-id: %v", err)
}
ctx.ZoneID, err = ctx.getMeta("instance/zone")
if err != nil {
return nil, fmt.Errorf("failed to query gce zone: %v", err)
}
if i := strings.LastIndexByte(ctx.ZoneID, '/'); i != -1 {
ctx.ZoneID = ctx.ZoneID[i+1:] // the query returns some nonsense prefix
}
instID, err := ctx.getMeta("instance/id")
if err != nil {
return nil, fmt.Errorf("failed to query gce instance id: %v", err)
}
instances, err := ctx.computeService.Instances.List(ctx.ProjectID, ctx.ZoneID).Do()
if err != nil {
return nil, fmt.Errorf("error getting instance list: %v", err)
}
// Finds this instance internal IP.
for _, inst := range instances.Items {
if fmt.Sprint(inst.Id) != instID {
continue
}
ctx.Instance = inst.Name
for _, iface := range inst.NetworkInterfaces {
if strings.HasPrefix(iface.NetworkIP, "10.") {
ctx.InternalIP = iface.NetworkIP
break
}
}
break
}
if ctx.Instance == "" || ctx.InternalIP == "" {
return nil, fmt.Errorf("failed to get current instance name and internal IP")
}
return ctx, nil
}
开发者ID:sploving,项目名称:syzkaller,代码行数:50,代码来源:gce.go
示例15: init
func init() {
makeDeps := func(ctx context.Context) (deps gcstesting.BucketTestDeps) {
var err error
// Set up the token source.
const scope = gcs.Scope_FullControl
tokenSrc, err := google.DefaultTokenSource(context.Background(), scope)
AssertEq(nil, err)
// Use that to create a GCS connection, enabling retry if requested.
cfg := &gcs.ConnConfig{
TokenSource: tokenSrc,
}
if *fUseRetry {
cfg.MaxBackoffSleep = 5 * time.Minute
deps.BuffersEntireContentsForCreate = true
}
if *fDebugGCS {
cfg.GCSDebugLogger = log.New(os.Stderr, "gcs: ", 0)
}
if *fDebugHTTP {
cfg.HTTPDebugLogger = log.New(os.Stderr, "http: ", 0)
}
conn, err := gcs.NewConn(cfg)
AssertEq(nil, err)
// Open the bucket.
deps.Bucket, err = conn.OpenBucket(ctx, *fBucket)
AssertEq(nil, err)
// Clear the bucket.
err = gcsutil.DeleteAllObjects(ctx, deps.Bucket)
if err != nil {
panic("DeleteAllObjects: " + err.Error())
}
// Set up other information.
deps.Clock = timeutil.RealClock()
deps.SupportsCancellation = true
return
}
gcstesting.RegisterBucketTests(makeDeps)
}
开发者ID:okdave,项目名称:gcloud,代码行数:49,代码来源:integration_test.go
示例16: newCachedTokenSource
func newCachedTokenSource(accessToken, expiry string, persister restclient.AuthProviderConfigPersister) (*cachedTokenSource, error) {
var expiryTime time.Time
if parsedTime, err := time.Parse(time.RFC3339Nano, expiry); err == nil {
expiryTime = parsedTime
}
ts, err := google.DefaultTokenSource(context.Background(), "https://www.googleapis.com/auth/cloud-platform")
if err != nil {
return nil, err
}
return &cachedTokenSource{
source: ts,
accessToken: accessToken,
expiry: expiryTime,
persister: persister,
}, nil
}
开发者ID:ncdc,项目名称:kubernetes,代码行数:16,代码来源:gcp.go
示例17: GCEClientInit
// GCEClientInit uses Google's host FS searching functionality to find auth
// tokens if they exist. eg: GCE VMs, Authenticated Developers
func GCEClientInit(ctx *context.Context, project string) *pubsub.Client {
var client *pubsub.Client
clientOnce := new(sync.Once)
clientOnce.Do(func() {
source, err := google.DefaultTokenSource(*ctx, pubsub.ScopePubSub)
if err != nil {
log.Errorf("error creating token source: %v", err)
os.Exit(1)
}
client, err = pubsub.NewClient(*ctx, project, cloud.WithTokenSource(source))
if err != nil {
log.Errorf("error creating pubsub.Client: %v", err)
os.Exit(1)
}
})
return client
}
开发者ID:Ropes,项目名称:pubbing,代码行数:19,代码来源:sub.go
示例18: getConn
func getConn() (c gcs.Conn, err error) {
// Create the oauth2 token source.
const scope = gcs.Scope_FullControl
tokenSrc, err := google.DefaultTokenSource(context.Background(), scope)
if err != nil {
return nil, err
}
// Create the connection.
const userAgent = "gcsfuse/0.0"
cfg := &gcs.ConnConfig{
TokenSource: tokenSrc,
UserAgent: userAgent,
}
return gcs.NewConn(cfg)
}
开发者ID:mbookman,项目名称:gcsfuse,代码行数:17,代码来源:main.go
示例19: main
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)
}
开发者ID:salrashid123,项目名称:gcpsamples,代码行数:17,代码来源:main.go
示例20: newGCPAuthProvider
func newGCPAuthProvider(_ string, gcpConfig map[string]string, persister restclient.AuthProviderConfigPersister) (restclient.AuthProvider, error) {
cmd, useCmd := gcpConfig["cmd-path"]
var ts oauth2.TokenSource
var err error
if useCmd {
ts, err = newCmdTokenSource(cmd, gcpConfig["token-key"], gcpConfig["expiry-key"], gcpConfig["time-fmt"])
} else {
ts, err = google.DefaultTokenSource(context.Background(), "https://www.googleapis.com/auth/cloud-platform")
}
if err != nil {
return nil, err
}
cts, err := newCachedTokenSource(gcpConfig["access-token"], gcpConfig["expiry"], persister, ts, gcpConfig)
if err != nil {
return nil, err
}
return &gcpAuthProvider{cts, persister}, nil
}
开发者ID:eljefedelrodeodeljefe,项目名称:kubernetes,代码行数:18,代码来源:gcp.go
注:本文中的golang.org/x/oauth2/google.DefaultTokenSource函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论