本文整理汇总了Golang中golang.org/x/oauth2/google.JWTConfigFromJSON函数的典型用法代码示例。如果您正苦于以下问题:Golang JWTConfigFromJSON函数的具体用法?Golang JWTConfigFromJSON怎么用?Golang JWTConfigFromJSON使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了JWTConfigFromJSON函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: main
func main() {
data, err := ioutil.ReadFile(key)
if err != nil {
log.Fatal(err)
}
conf, err := google.JWTConfigFromJSON(data, "https://www.googleapis.com/auth/plus.profile.emails.read")
if err != nil {
log.Fatal(err)
}
client := conf.Client(oauth2.NoContext)
plusService, err := plus.New(client)
if err != nil {
log.Fatal(err)
}
peopleService := plus.NewPeopleService(plusService)
call := peopleService.Get("105303214497629424637")
person, err := call.Do()
if err != nil {
log.Fatal(err)
}
fmt.Println(person)
}
示例2: getCloudContext
func getCloudContext(aeCtx context.Context) (context.Context, error) {
data, err := ioutil.ReadFile("gcs.xxjson")
if err != nil {
return nil, err
}
conf, err := google.JWTConfigFromJSON(
data,
storage.ScopeFullControl,
)
if err != nil {
return nil, err
}
tokenSource := conf.TokenSource(aeCtx)
hc := &http.Client{
Transport: &oauth2.Transport{
Source: tokenSource,
Base: &urlfetch.Transport{Context: aeCtx},
},
}
return cloud.NewContext(appengine.AppID(aeCtx), hc), nil
}
示例3: NewSalesforceOpportunityEventService
func NewSalesforceOpportunityEventService(ctx context.Context, jsonPath, projectID, namespace string) (SalesforceOpportunityEventService, error) {
logger.Infof("NewSalesforceOpportunityEventService: jsonPath - %s", jsonPath)
jsonKey, err := ioutil.ReadFile(jsonPath)
if err != nil {
return nil, err
}
conf, err := google.JWTConfigFromJSON(
jsonKey,
pubsub.ScopeCloudPlatform,
pubsub.ScopePubSub,
)
if err != nil {
return nil, err
}
pubSubEvents := &SalesforceOpportunityEvents{
conf: conf,
projectID: projectID,
Topic: "opportunity_chages",
Subscription: "opportunity_chages_sub" + namespace,
}
return pubSubEvents, nil
}
示例4: createOutputFile
func (s *shard) createOutputFile(c context.Context) (io.WriteCloser, error) {
c, _ = context.WithTimeout(c, time.Duration(10)*time.Minute)
// for development we can't use the appengine default credentials so
// instead need to create our own oauth token source to access storage
// TODO: maybe give job a chance to generate this - it could also
// create the writer (?). The only reason we're doing it is to prevent
// duplication and also handle the file rollup operations
var client *cstorage.Client
if appengine.IsDevAppServer() {
jsonKey, err := ioutil.ReadFile("service-account.json")
if err != nil {
return nil, err
}
conf, err := google.JWTConfigFromJSON(jsonKey, cstorage.ScopeReadWrite)
if err != nil {
return nil, err
}
client, err = cstorage.NewClient(c, option.WithTokenSource(conf.TokenSource(c)))
if err != nil {
return nil, err
}
} else {
var err error
client, err = cstorage.NewClient(c)
if err != nil {
return nil, err
}
}
o := client.Bucket(s.job.Bucket).Object(s.sliceFilename(s.Sequence)).NewWriter(c)
// TODO: wrap writer to count bytes and continue slice if we get close to 10Mb limit (?)
return o, nil
}
示例5: Init
func (d *driver) Init(r *core.RexRay) error {
d.r = r
var err error
d.zone = d.r.Config.GetString("gce.zone")
d.project = d.r.Config.GetString("gce.project")
serviceAccountJSON, err := ioutil.ReadFile(d.r.Config.GetString("gce.keyfile"))
if err != nil {
log.WithField("provider", providerName).Fatalf("Could not read service account credentials file, %s => {%s}", d.r.Config.GetString("gce.keyfile"), err)
return err
}
config, err := google.JWTConfigFromJSON(serviceAccountJSON,
compute.ComputeScope,
)
client, err := compute.New(config.Client(context.Background()))
if err != nil {
log.WithField("provider", providerName).Fatalf("Could not create compute client => {%s}", err)
return err
}
d.client = client
instanceId, err := getCurrentInstanceId()
if err != nil {
log.WithField("provider", providerName).Fatalf("Could not get current instance => {%s}", err)
return err
}
d.currentInstanceId = instanceId
log.WithField("provider", providerName).Info("storage driver initialized")
return nil
}
示例6: Example_serviceAccount
func Example_serviceAccount() {
// Warning: The better way to use service accounts is to set GOOGLE_APPLICATION_CREDENTIALS
// and use the Application Default Credentials.
ctx := context.Background()
// Use a JSON key file associated with a Google service account to
// authenticate and authorize.
// Go to https://console.developers.google.com/permissions/serviceaccounts to create
// and download a service account key for your project.
//
// Note: The example uses the datastore client, but the same steps apply to
// the other client libraries underneath this package.
key, err := ioutil.ReadFile("/path/to/service-account-key.json")
if err != nil {
// TODO: handle error.
}
cfg, err := google.JWTConfigFromJSON(key, datastore.ScopeDatastore)
if err != nil {
// TODO: handle error.
}
client, err := datastore.NewClient(
ctx, "project-id", option.WithTokenSource(cfg.TokenSource(ctx)))
if err != nil {
// TODO: handle error.
}
// Use the client.
_ = client
}
示例7: NewGCSImageStore
func (this *Factory) NewGCSImageStore(conf map[string]string) ImageStore {
jsonKey, err := ioutil.ReadFile(conf["KeyFile"])
if err != nil {
log.Fatal(err)
}
cloudConf, err := google.JWTConfigFromJSON(
jsonKey,
gcs.ScopeFullControl,
)
if err != nil {
log.Fatal(err)
}
bucket := conf["BucketName"]
ctx := gcloud.NewContext(conf["AppID"], cloudConf.Client(oauth2.NoContext))
mapper := NewNamePathMapper(conf["NamePathRegex"], conf["NamePathMap"])
return NewGCSImageStore(
ctx,
bucket,
conf["StoreRoot"],
mapper,
)
}
示例8: newContext
func newContext(projectID, jsonKey string) (context.Context, error) {
if projectID == "" {
return nil, errors.New("project id not provided")
}
if jsonKey == "" {
return nil, errors.New("JSON key not provided")
}
key, err := ioutil.ReadFile(jsonKey)
if err != nil {
return nil, err
}
conf, err := google.JWTConfigFromJSON(
key,
pubsub.ScopeCloudPlatform,
pubsub.ScopePubSub,
)
if err != nil {
return nil, err
}
ctx := cloud.NewContext(projectID, conf.Client(oauth2.NoContext))
return ctx, nil
}
示例9: New
// New creates a Client from the configuration.
func New(ctx context.Context, config *Config) (*Client, error) {
conf := *config
certs := &Certificates{URL: publicCertsURL}
var widgetURL *url.URL
if conf.WidgetURL != "" {
var err error
widgetURL, err = url.Parse(conf.WidgetURL)
if err != nil {
return nil, fmt.Errorf("invalid WidgetURL: %s", conf.WidgetURL)
}
}
var jc *jwt.Config
if config.GoogleAppCredentialsPath != "" {
b, err := ioutil.ReadFile(config.GoogleAppCredentialsPath)
if err != nil {
return nil, fmt.Errorf("invalid GoogleAppCredentialsPath: %v", err)
}
jc, err = google.JWTConfigFromJSON(b, identitytoolkitScope)
if err != nil {
return nil, err
}
}
api, err := newAPIClient(ctx, jc)
if err != nil {
return nil, err
}
conf.normalize()
return &Client{
config: &conf,
widgetURL: widgetURL,
certs: certs,
api: api,
jc: jc,
}, nil
}
示例10: connect
// connect - opens a new connection to bigquery, reusing the token if possible or regenerating a new auth token if required
func (c *Client) connect() (*bigquery.Service, error) {
if c.token != nil {
if !c.token.Valid() && c.service != nil {
return c.service, nil
}
}
// generate auth token and create service object
//authScope := bigquery.BigqueryScope
pemKeyBytes, err := ioutil.ReadFile(c.pemPath)
if err != nil {
panic(err)
}
t, err := google.JWTConfigFromJSON(
pemKeyBytes,
"https://www.googleapis.com/auth/bigquery")
//t := jwt.NewToken(c.accountEmailAddress, bigquery.BigqueryScope, pemKeyBytes)
client := t.Client(oauth2.NoContext)
service, err := bigquery.New(client)
if err != nil {
return nil, err
}
c.service = service
return service, nil
}
示例11: Example_auth
func Example_auth() {
// Initialize an authorized context with Google Developers Console
// JSON key. Read the google package examples to learn more about
// different authorization flows you can use.
// http://godoc.org/golang.org/x/oauth2/google
jsonKey, err := ioutil.ReadFile("/path/to/json/keyfile.json")
if err != nil {
log.Fatal(err)
}
conf, err := google.JWTConfigFromJSON(
jsonKey,
storage.ScopeFullControl,
)
if err != nil {
log.Fatal(err)
}
ctx := context.Background()
client, err := storage.NewClient(ctx, cloud.WithTokenSource(conf.TokenSource(ctx)))
if err != nil {
log.Fatal(err)
}
// Use the client (see other examples)
doSomething(client)
// After using the client, free any resources (e.g. network connections).
client.Close()
}
示例12: newClient
// newClient creates http.Client with a jwt service account when
// jsonFile flag is specified, otherwise by obtaining the GCE service
// account's access token.
func newClient(jsonFile string) (*http.Client, error) {
if jsonFile != "" {
jsonKey, err := ioutil.ReadFile(jsonFile)
if err != nil {
return nil, err
}
conf, err := google.JWTConfigFromJSON(jsonKey, pubsub.ScopePubSub)
if err != nil {
return nil, err
}
return conf.Client(oauth2.NoContext), nil
}
if metadata.OnGCE() {
c := &http.Client{
Transport: &oauth2.Transport{
Source: google.ComputeTokenSource(""),
},
}
if *projID == "" {
projectID, err := metadata.ProjectID()
if err != nil {
return nil, fmt.Errorf("ProjectID failed, %v", err)
}
*projID = projectID
}
return c, nil
}
return nil, errors.New("Could not create an authenticated client.")
}
示例13: 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)
}
示例14: Do
// Do handles command-line requests to the Google BrainMaps API
func (dtype *Type) Do(cmd datastore.Request, reply *datastore.Response) error {
switch cmd.Argument(1) {
case "volumes":
// Read in the JSON Web Token
jwtdata, err := ioutil.ReadFile(cmd.Argument(2))
if err != nil {
return fmt.Errorf("Cannot load JSON Web Token file (%s): %v", cmd.Argument(2), err)
}
conf, err := google.JWTConfigFromJSON(jwtdata, "https://www.googleapis.com/auth/brainmaps")
if err != nil {
return fmt.Errorf("Cannot establish JWT Config file from Google: %v", err)
}
client := conf.Client(oauth2.NoContext)
// Make the call.
url := fmt.Sprintf("%s/volumes", bmapsPrefix)
resp, err := client.Get(url)
if err != nil {
return fmt.Errorf("Error getting volumes metadata from Google: %v", err)
}
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("Unexpected status code %d returned when getting volumes for user", resp.StatusCode)
}
metadata, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
resp.Body.Close()
reply.Text = string(metadata)
return nil
default:
return fmt.Errorf("unknown command for type %s", dtype.GetTypeName())
}
}
示例15: main
func main() {
// Your credentials should be obtained from the Google
// Developer Console (https://console.developers.google.com).
// Navigate to your project, then see the "Credentials" page
// under "APIs & Auth".
// To create a service account client, click "Create new Client ID",
// select "Service Account", and click "Create Client ID". A JSON
// key file will then be downloaded to your computer.
data, err := ioutil.ReadFile("downloaded.json")
if err != nil {
log.Fatal(err)
}
conf, err := google.JWTConfigFromJSON(data, "https://www.google.com/m8/feeds")
if err != nil {
log.Fatal(err)
}
// Initiate an http.Client. The following GET request will be
// authorized and authenticated on the behalf of
// your service account.
client := conf.Client(oauth2.NoContext)
res, err := client.Get("https://www.google.com/m8/feeds/contacts/default/full")
if err != nil {
log.Println("err:", err)
}
body, err := ioutil.ReadAll(res.Body)
log.Println(string(body))
}