本文整理汇总了Golang中golang.org/x/oauth2/jwt.Config类的典型用法代码示例。如果您正苦于以下问题:Golang Config类的具体用法?Golang Config怎么用?Golang Config使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Config类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: buildGoogleComputeService
func buildGoogleComputeService(accountJSON string) (*compute.Service, error) {
if accountJSON == "" {
return nil, fmt.Errorf("missing account-json")
}
a, err := loadGoogleAccountJSON(accountJSON)
if err != nil {
return nil, err
}
config := jwt.Config{
Email: a.ClientEmail,
PrivateKey: []byte(a.PrivateKey),
Scopes: []string{
compute.DevstorageFullControlScope,
compute.ComputeScope,
},
TokenURL: "https://accounts.google.com/o/oauth2/token",
}
client := config.Client(oauth2.NoContext)
if gceCustomHTTPTransport != nil {
client.Transport = gceCustomHTTPTransport
}
return compute.New(client)
}
示例2: buildGoogleComputeService
func buildGoogleComputeService(accountJSON string) (*compute.Service, error) {
a, err := loadGoogleAccountJSON(accountJSON)
if err != nil {
return nil, err
}
config := jwt.Config{
Email: a.ClientEmail,
PrivateKey: []byte(a.PrivateKey),
Scopes: []string{
compute.DevstorageFullControlScope,
compute.ComputeScope,
},
TokenURL: "https://accounts.google.com/o/oauth2/token",
}
client := config.Client(oauth2.NoContext)
cs, err := compute.New(client)
if err != nil {
return nil, err
}
cs.UserAgent = "gcloud-cleanup"
return cs, nil
}
示例3: GetUserGroups
// GetUserGroups returns the names of the groups that the specified user is a
// member of.
func GetUserGroups(emailAddress string) ([]string, error) {
conf := jwt.Config{
Email: *googleServiceEmail,
PrivateKey: []byte(*googleServicePrivateKey),
Scopes: []string{"https://www.googleapis.com/auth/admin.directory.group.readonly"},
TokenURL: google.JWTTokenURL,
Subject: *googleServiceUser,
}
client := conf.Client(oauth2.NoContext)
response, err := client.Get(fmt.Sprintf("https://www.googleapis.com/admin/directory/v1/groups?userKey=%s", emailAddress))
if err != nil {
return nil, fmt.Errorf("fetching groups: %s", err)
}
if response.StatusCode != 200 {
responseBody, err := ioutil.ReadAll(response.Body)
if err != nil {
return nil, fmt.Errorf("fetching groups: returned %s", response.Status)
}
return nil, fmt.Errorf("fetching groups: returned %s: %s",
response.Status, responseBody)
}
groupsResponse := GroupsResponse{}
if err := json.NewDecoder(response.Body).Decode(&groupsResponse); err != nil {
return nil, fmt.Errorf("parsing groups response: %s", err)
}
groupNames := []string{}
for _, group := range groupsResponse.Groups {
groupNames = append(groupNames, group.Name)
}
return groupNames, nil
}
示例4: NewDriverGCE
func NewDriverGCE(ui packer.Ui, p string, a *accountFile) (Driver, error) {
var err error
var client *http.Client
// Auth with AccountFile first if provided
if a.PrivateKey != "" {
log.Printf("[INFO] Requesting Google token via AccountFile...")
log.Printf("[INFO] -- Email: %s", a.ClientEmail)
log.Printf("[INFO] -- Scopes: %s", DriverScopes)
log.Printf("[INFO] -- Private Key Length: %d", len(a.PrivateKey))
conf := jwt.Config{
Email: a.ClientEmail,
PrivateKey: []byte(a.PrivateKey),
Scopes: DriverScopes,
TokenURL: "https://accounts.google.com/o/oauth2/token",
}
// 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)
} else {
log.Printf("[INFO] Requesting Google token via GCE Service Role...")
client = &http.Client{
Transport: &oauth2.Transport{
// Fetch from Google Compute Engine's metadata server to retrieve
// an access token for the provided account.
// If no account is specified, "default" is used.
Source: google.ComputeTokenSource(""),
},
}
}
if err != nil {
return nil, err
}
log.Printf("[INFO] Instantiating GCE client...")
service, err := compute.New(client)
// Set UserAgent
versionString := version.FormattedVersion()
service.UserAgent = fmt.Sprintf(
"(%s %s) Packer/%s", runtime.GOOS, runtime.GOARCH, versionString)
if err != nil {
return nil, err
}
return &driverGCE{
projectId: p,
service: service,
ui: ui,
}, nil
}
示例5: NewBigQueryService
// NewBigQueryService returns a new BigQuery service (client), authenticated via OAuth2/JWT.
//
// NOTE: This function authenticates with Google OAuth2 service,
// thus susceptible to network delays and blocks.
func NewBigQueryService(c *jwt.Config) (service *bigquery.Service, err error) {
// Create *http.Client.
client := c.Client(oauth2.NoContext)
// Create authenticated BigQuery service.
service, err = bigquery.New(client)
// No need to check if err != nil since we return anyways.
return
}
示例6: newAPIClient
func newAPIClient(ctx context.Context, jc *jwt.Config) (*APIClient, error) {
var hc *http.Client
if jc != nil {
hc = jc.Client(ctx)
} else {
var err error
hc, err = google.DefaultClient(ctx, identitytoolkitScope)
if err != nil {
return nil, err
}
}
return &APIClient{
http.Client{
Transport: &transport{hc.Transport},
},
}, nil
}
示例7: Save
func (g *gcsdesc) Save(file string) (url string, err error) {
privateKey, err := ioutil.ReadFile(setting.PrivateKeyFilePath + setting.PrivateKeyFile)
if err != nil {
log.Fatal(err)
}
s := []string{setting.Scope}
conf := jwt.Config{
Email: setting.Clientemail,
PrivateKey: privateKey,
Scopes: s,
TokenURL: google.JWTTokenURL,
}
//new storage service and token, we dont need context here
client := conf.Client(oauth2.NoContext)
gcsToken, err := conf.TokenSource(oauth2.NoContext).Token()
service, err := storage.New(client)
if err != nil {
log.Fatalf("GCS unable to create storage service: %v", err)
}
//Split filename as a objectName
var objectName string
for _, objectName = range strings.Split(file, "/") {
}
object := &storage.Object{Name: objectName}
// Insert an object into a bucket.
fileDes, err := os.Open(file)
if err != nil {
log.Fatalf("Error opening %q: %v", file, err)
}
objs, err := service.Objects.Insert(setting.Bucket, object).Media(fileDes).Do()
if err != nil {
log.Fatalf("GCS Objects.Insert failed: %v", err)
}
retUrl := objs.MediaLink + "&access_token=" + gcsToken.AccessToken
if err != nil {
return "", err
} else {
return retUrl, nil
}
}
示例8: NewClient
// NewClient ...
func NewClient(email, pemKeyPath string) (*Client, error) {
pemKeyBytes, err := ioutil.ReadFile(pemKeyPath)
if err != nil {
return nil, err
}
conf := jwt.Config{
Email: email,
PrivateKey: pemKeyBytes,
Scopes: []string{bigquery.BigqueryScope},
TokenURL: google.JWTTokenURL,
}
client := conf.Client(oauth2.NoContext)
service, err := bigquery.New(client)
if err != nil {
return nil, err
}
return &Client{BigQueryService: service}, nil
}
示例9: Connect
func (w *Writer) Connect(email string, pem []byte) error {
cfg := jwt.Config{
Email: email,
PrivateKey: pem,
Scopes: []string{bq.BigqueryScope},
TokenURL: "https://accounts.google.com/o/oauth2/token",
}
ctx := context.Background()
client := cfg.Client(ctx)
bq, err := bq.New(client)
if err != nil {
w.warnf("connect error %v", err)
return err
}
w.service = &bigqueryService{bq}
w.debugf("connected")
return nil
}
示例10: FromParameters
// FromParameters constructs a new Driver with a given parameters map
// Required parameters:
// - bucket
func FromParameters(parameters map[string]interface{}) (storagedriver.StorageDriver, error) {
bucket, ok := parameters["bucket"]
if !ok || fmt.Sprint(bucket) == "" {
return nil, fmt.Errorf("No bucket parameter provided")
}
rootDirectory, ok := parameters["rootdirectory"]
if !ok {
rootDirectory = ""
}
var ts oauth2.TokenSource
jwtConf := new(jwt.Config)
if keyfile, ok := parameters["keyfile"]; ok {
jsonKey, err := ioutil.ReadFile(fmt.Sprint(keyfile))
if err != nil {
return nil, err
}
jwtConf, err = google.JWTConfigFromJSON(jsonKey, storage.ScopeFullControl)
if err != nil {
return nil, err
}
ts = jwtConf.TokenSource(context.Background())
} else {
var err error
ts, err = google.DefaultTokenSource(context.Background(), storage.ScopeFullControl)
if err != nil {
return nil, err
}
}
params := driverParameters{
bucket: fmt.Sprint(bucket),
rootDirectory: fmt.Sprint(rootDirectory),
email: jwtConf.Email,
privateKey: jwtConf.PrivateKey,
client: oauth2.NewClient(context.Background(), ts),
}
return New(params)
}
示例11: initBigQueryService
func initBigQueryService(credentialsFileName string) error {
var client *http.Client
credentialsData, err := ioutil.ReadFile(credentialsFileName)
if err != nil {
return err
}
var conf *jwt.Config
conf, err = google.JWTConfigFromJSON(credentialsData, bigQueryScope)
if err != nil {
return err
}
client = conf.Client(oauth2.NoContext)
if bq, err = bigquery.New(client); err != nil {
return err
}
return nil
}
示例12: NewBigQueryService
func NewBigQueryService(c *jwt.Config) (service *bigquery.Service, err error) {
client := c.Client(oauth2.NoContext)
service, err = bigquery.New(client)
return
}
示例13: loadAndValidate
func (c *Config) loadAndValidate() error {
var account accountFile
// TODO: validation that it isn't blank
if c.AccountFile == "" {
c.AccountFile = os.Getenv("GOOGLE_ACCOUNT_FILE")
}
if c.Project == "" {
c.Project = os.Getenv("GOOGLE_PROJECT")
}
if c.Region == "" {
c.Region = os.Getenv("GOOGLE_REGION")
}
var client *http.Client
if c.AccountFile != "" {
if err := loadJSON(&account, c.AccountFile); err != nil {
return fmt.Errorf(
"Error loading account file '%s': %s",
c.AccountFile,
err)
}
clientScopes := []string{"https://www.googleapis.com/auth/compute"}
// Get the token for use in our requests
log.Printf("[INFO] Requesting Google token...")
log.Printf("[INFO] -- Email: %s", account.ClientEmail)
log.Printf("[INFO] -- Scopes: %s", clientScopes)
log.Printf("[INFO] -- Private Key Length: %d", len(account.PrivateKey))
conf := jwt.Config{
Email: account.ClientEmail,
PrivateKey: []byte(account.PrivateKey),
Scopes: clientScopes,
TokenURL: "https://accounts.google.com/o/oauth2/token",
}
// 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)
} else {
log.Printf("[INFO] Requesting Google token via GCE Service Role...")
client = &http.Client{
Transport: &oauth2.Transport{
// Fetch from Google Compute Engine's metadata server to retrieve
// an access token for the provided account.
// If no account is specified, "default" is used.
Source: google.ComputeTokenSource(""),
},
}
}
log.Printf("[INFO] Instantiating GCE client...")
var err error
c.clientCompute, err = compute.New(client)
if err != nil {
return err
}
return nil
}
示例14: loadAndValidate
func (c *Config) loadAndValidate() error {
var account accountFile
// TODO: validation that it isn't blank
if c.AccountFile == "" {
c.AccountFile = os.Getenv("GOOGLE_ACCOUNT_FILE")
}
if c.Project == "" {
c.Project = os.Getenv("GOOGLE_PROJECT")
}
if c.Region == "" {
c.Region = os.Getenv("GOOGLE_REGION")
}
var client *http.Client
if c.AccountFile != "" {
if err := loadJSON(&account, c.AccountFile); err != nil {
return fmt.Errorf(
"Error loading account file '%s': %s",
c.AccountFile,
err)
}
clientScopes := []string{
"https://www.googleapis.com/auth/compute",
"https://www.googleapis.com/auth/ndev.clouddns.readwrite",
"https://www.googleapis.com/auth/devstorage.full_control",
}
// Get the token for use in our requests
log.Printf("[INFO] Requesting Google token...")
log.Printf("[INFO] -- Email: %s", account.ClientEmail)
log.Printf("[INFO] -- Scopes: %s", clientScopes)
log.Printf("[INFO] -- Private Key Length: %d", len(account.PrivateKey))
conf := jwt.Config{
Email: account.ClientEmail,
PrivateKey: []byte(account.PrivateKey),
Scopes: clientScopes,
TokenURL: "https://accounts.google.com/o/oauth2/token",
}
// 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)
} else {
log.Printf("[INFO] Requesting Google token via GCE Service Role...")
client = &http.Client{
Transport: &oauth2.Transport{
// Fetch from Google Compute Engine's metadata server to retrieve
// an access token for the provided account.
// If no account is specified, "default" is used.
Source: google.ComputeTokenSource(""),
},
}
}
// Build UserAgent
versionString := "0.0.0"
// TODO(dcunnin): Use Terraform's version code from version.go
// versionString := main.Version
// if main.VersionPrerelease != "" {
// versionString = fmt.Sprintf("%s-%s", versionString, main.VersionPrerelease)
// }
userAgent := fmt.Sprintf(
"(%s %s) Terraform/%s", runtime.GOOS, runtime.GOARCH, versionString)
var err error
log.Printf("[INFO] Instantiating GCE client...")
c.clientCompute, err = compute.New(client)
if err != nil {
return err
}
c.clientCompute.UserAgent = userAgent
log.Printf("[INFO] Instantiating Beta GCE client...")
c.clientComputeBeta, err = computeBeta.New(client)
if err != nil {
return err
}
c.clientComputeBeta.UserAgent = userAgent
log.Printf("[INFO] Instantiating Google Cloud DNS client...")
c.clientDns, err = dns.New(client)
if err != nil {
return err
}
c.clientDns.UserAgent = userAgent
log.Printf("[INFO] Instantiating Google Storage Client...")
c.clientStorage, err = storage.New(client)
if err != nil {
return err
}
c.clientStorage.UserAgent = userAgent
//.........这里部分代码省略.........
示例15: loadAndValidate
func (c *Config) loadAndValidate() error {
var account accountFile
clientScopes := []string{
"https://www.googleapis.com/auth/compute",
"https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/ndev.clouddns.readwrite",
"https://www.googleapis.com/auth/devstorage.full_control",
}
var client *http.Client
if c.Credentials != "" {
contents, _, err := pathorcontents.Read(c.Credentials)
if err != nil {
return fmt.Errorf("Error loading credentials: %s", err)
}
// Assume account_file is a JSON string
if err := parseJSON(&account, contents); err != nil {
return fmt.Errorf("Error parsing credentials '%s': %s", contents, err)
}
// Get the token for use in our requests
log.Printf("[INFO] Requesting Google token...")
log.Printf("[INFO] -- Email: %s", account.ClientEmail)
log.Printf("[INFO] -- Scopes: %s", clientScopes)
log.Printf("[INFO] -- Private Key Length: %d", len(account.PrivateKey))
conf := jwt.Config{
Email: account.ClientEmail,
PrivateKey: []byte(account.PrivateKey),
Scopes: clientScopes,
TokenURL: "https://accounts.google.com/o/oauth2/token",
}
// 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)
} else {
log.Printf("[INFO] Authenticating using DefaultClient")
err := error(nil)
client, err = google.DefaultClient(oauth2.NoContext, clientScopes...)
if err != nil {
return err
}
}
versionString := terraform.Version
prerelease := terraform.VersionPrerelease
if len(prerelease) > 0 {
versionString = fmt.Sprintf("%s-%s", versionString, prerelease)
}
userAgent := fmt.Sprintf(
"(%s %s) Terraform/%s", runtime.GOOS, runtime.GOARCH, versionString)
var err error
log.Printf("[INFO] Instantiating Google Storage Client...")
c.clientStorage, err = storage.New(client)
if err != nil {
return err
}
c.clientStorage.UserAgent = userAgent
log.Printf("[INFO] Instantiating Google Appengine Client...")
c.clientAppengine, err = appengine.New(client)
if err != nil {
return err
}
c.clientAppengine.UserAgent = userAgent
return nil
}