Documentation ¶
Overview ¶
Package oauth2device provides a small shim around the golang.org/x/oauth2 package to support device authorization flows for Google. See the included examples.
Example ¶
An simple example of using this package for device authorization.
// The usual OAuth2 configuration var clientOAuthConfig = &oauth2.Config{ ClientID: "<insert client id here>", ClientSecret: "<insert client secret here>", Endpoint: google.Endpoint, // for example... Scopes: []string{youtube.YoutubeReadonlyScope}, } // Augment OAuth2 configuration with device endpoints. var clientDeviceOAuthConfig = &oauth2device.Config{ Config: clientOAuthConfig, DeviceEndpoint: googledevice.DeviceEndpoint, } // Use default HTTP client. client := http.DefaultClient // Get URL and code for user. dcr, err := oauth2device.RequestDeviceCode(client, clientDeviceOAuthConfig) if err != nil { log.Fatal(err) } fmt.Printf("Visit: %v and enter: %v\n", dcr.VerificationURL, dcr.UserCode) // Wait for a token. It will be a standard oauth2.Token. accessToken, err := oauth2device.WaitForDeviceAuthorization(client, clientDeviceOAuthConfig, dcr) if err != nil { log.Fatal(err) } fmt.Printf("Access token: %v\n", accessToken) // Now use the token as usual...
Output:
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ( // ErrAccessDenied is an error returned when the user has denied this // app access to their account. ErrAccessDenied = errors.New("access denied by user") )
Functions ¶
func WaitForDeviceAuthorization ¶
func WaitForDeviceAuthorization(client *http.Client, config *Config, code *DeviceCode) (*oauth2.Token, error)
WaitForDeviceAuthorization polls the token URL waiting for the user to authorize the app. Upon authorization, it returns the new token. If authorization fails then an error is returned. If that failure was due to a user explicitly denying access, the error is ErrAccessDenied.
Types ¶
type Config ¶
type Config struct { *oauth2.Config DeviceEndpoint DeviceEndpoint }
A version of oauth2.Config augmented with device endpoints
type DeviceCode ¶
type DeviceCode struct { DeviceCode string `json:"device_code"` UserCode string `json:"user_code"` VerificationURL string `json:"verification_url"` ExpiresIn int64 `json:"expires_in"` Interval int64 `json:"interval"` }
A DeviceCode represents the user-visible code, verification URL and device-visible code used to allow for user authorisation of this app. The app should show UserCode and VerificationURL to the user.
func RequestDeviceCode ¶
func RequestDeviceCode(client *http.Client, config *Config) (*DeviceCode, error)
RequestDeviceCode will initiate the OAuth2 device authorization flow. It requests a device code and information on the code and URL to show to the user. Pass the returned DeviceCode to WaitForDeviceAuthorization.
type DeviceEndpoint ¶
type DeviceEndpoint struct {
CodeURL string
}
DeviceEndpoint contains the URLs required to initiate the OAuth2.0 flow for a provider's device flow.