Coder Social home page Coder Social logo

identity-toolkit-go-client's Introduction

Google Identity Toolkit Go client

Build Status

This is the Go client library for Google Identity Toolkit services. Documentation at http://godoc.org/github.com/google/identity-toolkit-go-client/gitkit

The gitkit package provides convenient utilities for websites to integrate with the Google Identity Toolkit service.

See more at https://developers.google.com/identity-toolkit

To use Identity Toolkit Go client:

// ClientID is the OAuth2 web client ID for your server.
const clientID string = "123.apps.googleusercontent.com"
var client *gitkit.Client

func handleSignIn(w http.ResponseWriter, r *http.Request) {
	// If there is no valid session, check identity tookit ID token.
	ts := client.TokenFromRequest(r)
	token, err := client.ValidateToken(context.Background(), ts, []string{clientID})
	if err != nil {
		// Not a valid token. Handle error.
	}
	// Token is valid and it contains the user account information
	// including user ID, email address, etc.
	// Issue your own session cookie to finish the sign in.
}

func main() {
	// Provide configuration. gitkit.LoadConfig() can also be used to load
	// the configuration from a JSON file.
	config := &gitkit.Config{
		WidgetURL:  "http://localhost/gitkit",
		CookieName: "gtoken",
	}
	var err error
	client, err = gitkit.New(context.Background(), config)
	if err != nil {
		// Handle error.
	}

	// Provide HTTP handler.
	http.HandleFunc("/signIn", handleSignIn)
	// Start the server.
	log.Fatal(http.ListenAndServe(":8080", nil))
}

The integration with Google App Engine is similar except for the context variable should be created from the request, i.e., appengine.NewContext(r):

// ClientID is the OAuth2 web client ID for your server.
const clientID string = "123.apps.googleusercontent.com"
var client *gitkit.Client

func handleSignIn(w http.ResponseWriter, r *http.Request) {
	// If there is no valid session, check identity tookit ID token.
	ts := client.TokenFromRequest(r)
	token, err := client.ValidateToken(appengine.NewContext(r), ts, []string{clientID})
	if err != nil {
		// Not a valid token. Handle error.
	}
	// Token is valid and it contains the user account information
	// including user ID, email address, etc.
	// Issue your own session cookie to finish the sign in.
}

func init() {
	// Provide configuration. gitkit.LoadConfig() can also be used to load
	// the configuration from a JSON file.
	config := &gitkit.Config{
		WidgetURL:	"http://localhost/gitkit",
		CookieName:	"gtoken",
	}
	// Set the JSON key file path if running dev server in local.
	if appengine.IsDevAppServer() {
		config.GoogleAppCredentialsPath = googleAppCredentialsPath
	}
	var err error
	client, err = gitkit.New(context.Background(), config)
	if err != nil {
		// Handle error.
	}

	// Provide HTTP handler.
	http.HandleFunc("/signIn", handleSignIn)
	// Start the server.
	log.Fatal(http.ListenAndServe(":8080", nil))
}

The client also provides other methods to help manage user accounts, for example,

To validate the token and also fetch the account information from the identity toolkit service:

user, err := client.UserByToken(ctx, token, []string{clientID})

or:

user, err := client.UserByEmail(ctx, email)

or:

user, err := client.UserByLocalID(ctx, localID)

To update, or delete the account information of a user:

err := client.UpdateUser(ctx, user)
err := client.DeleteUser(ctx, user)

The Go client uses Google Application Default Credentials to access authentication required Identity Toolkit API. The credentials returned are determined by the environment the code is running in. Conditions are checked in the following order:

  1. The environment variable GOOGLE_APPLICATION_CREDENTIALS is checked. If this variable is specified it should point to a file that defines the credentials. The simplest way to get a credential for this purpose is to create a service account using the Google Developers Console in the section APIs & Auth, in the sub-section Credentials. Create a service account or choose an existing one and select Generate new JSON key. Set the environment variable to the path of the JSON file downloaded.
  2. If you have installed the Google Cloud SDK on your machine and have run the command gcloud auth login, your identity can be used as a proxy to test code calling APIs from that machine.
  3. If you are running in Google App Engine production, the built-in service account associated with the application will be used.
  4. If you are running in Google Compute Engine production, the built-in service account associated with the virtual machine instance will be used.
  5. If none of these conditions is true, an error will occur.

If Application Default Credentials doesn't work for your use case, you can set GoogleAppCredentialsPath in the config to the JSON key file path.

identity-toolkit-go-client's People

Contributors

broady avatar dereksalama avatar iainmcgin avatar jonprice avatar liujin-google avatar mcduan avatar mdietz avatar naokigoogle avatar rikhul avatar tjohns avatar wuyanna avatar wyhao31 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

identity-toolkit-go-client's Issues

Add a NewWithContext function to the non appengine build

The switch to google.golang.org/appengine means that app engine projects can be be built using the standard go tools, this is useful as goapp dosn't work well with oracle, gocode etc.

The issue is there is no NewWithContext function on the non appengine build. If this was added GitKit could could be used in app engine projects and use the go tools.

Supporting hosted domain claims

Currently, the claims parsed from the ID Token are restricted to a specific set of hardcoded values. I'm working on a project where I would like to have support for the hd hosted domain claim as documented in Use Google Sign-In with IT Apps.

I think the simplest way to implement this would be to just add a field to the deserialization and Token struct. A more general approach could use an Extra() method similar to that on the golang.org/x/oauth2.Token type. In addition to deserializing the claims here, a map could be created and stored in a private raw field, just as oauth2 does.

I'm happy to submit a PR for either (or both) of these routes.

Panic cause closing a closed chanel when ListUsers followed by UserByEmail

When I change the order (first call UserByEmail then ListUsers), everything works fine.

package main

import (
    "fmt"
    "github.com/google/identity-toolkit-go-client/gitkit"
    "golang.org/x/net/context"
)

func main() {
    fmt.Println("staring...")
    config := &gitkit.Config{
        WidgetURL:                "http://localhost/gitkit",
        CookieName:               "gtoken",
        GoogleAppCredentialsPath: "/home/orian/tmp/google-identity-toolkit/validation/project-service-account.json",
    }
    client, err := gitkit.New(context.Background(), config)
    if err != nil {
        fmt.Printf("some problem: %s", err)
        return
    }

    fmt.Println("users")
    ul := client.ListUsers(context.Background())
    if ul.Error != nil {
        fmt.Printf("Err: %s", ul.Error)
        return
    }
    for u := range ul.C {
        fmt.Println(u.Email)
    }

    fmt.Println("a specific user")
    u,err := client.UserByEmail(context.Background(), "[email protected]")
    if err != nil {
        fmt.Printf("err getting user: %s\n", err)
        return
    }else {
        fmt.Printf("got user: %s\n", u.DisplayName)
    }

    fmt.Println("...ending")
}
panic: close of closed channel

goroutine 5 [running]:
github.com/google/identity-toolkit-go-client/gitkit.(*UserList).start.func1(0xc820011680, 0x7fe077c68668, 0xc82000ad80, 0xc8200222a0)
    /gopath/src/github.com/google/identity-toolkit-go-client/gitkit/gitkit.go:243 +0x217
created by github.com/google/identity-toolkit-go-client/gitkit.(*UserList).start
    /gopath/src/github.com/google/identity-toolkit-go-client/gitkit/gitkit.go:251 +0x8c

Usage with AppEngine

The documentation says:

 ctx := appengine.NewContext(r)
 c, err := gitkit.NewWithContext(ctx, client)

But gitkit.NewWithContext requires a context.Context
not an appengine.Context

But even with suppying a context.Context does make it work.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.