OAuth
This library simplifies OAuth flow. It reads configuration from the json file and stores the token in a gob file. The files are stored in the following locations:
$HOME/.config/oauth-<clientName>.json
- configuration file
$HOME/.credentials/oauth-<clientName>.gob
- saved token file
Configuration
To use the library you will need to create a file with configuration that would define Client ID, secret etc.
Example of the file to use with Spotify:
{
"ClientID": "<your client id>",
"ClientSecret": "<your client_secret>",
"Scopes": ["playlist-modify-public"],
"RedirectURL": "https://birnenlabs.com/code",
"Endpoint": {
"AuthURL": "https://accounts.spotify.com/authorize",
"TokenURL": "https://accounts.spotify.com/api/token"
}
}
The file should be saved in the following conf directory: $HOME/.config/oauth-spotify.json
. Values of the ClientID
and the ClientSecret
should be created in Spotify developer dashboard.
Redirect URL
The OAuth library is meant to be used in local applications, so the user needs to copy and paste the code.
Some providers allows urn:ietf:wg:oauth:2.0:oob
as the RedirectUri
- the code will be listed in the webpage. When urn:ietf:wg:oauth:2.0:oob
is not supported you can use https://birnenlabs.com/code
- it is a simple javascript page that will display all the parameters sent to it - see the example.
Code
Create
Creates OAuth object and sets the configuration. It does not make any request to the server. Error will be returned if there is problem with reading configuration file.
func Create(clientName string) (*OAuth, error)
VerifyToken
Checks if the token is stored in a gob file and if not the user will be requested to open the url and paste the code generated by the OAuth server.
func (o *OAuth) VerifyToken(ctx context.Context) error
CreateAuthenticatedHttpClient
Creates authenticated http client. It will return an error if there is no token in gob file, so the VerifyToken method should be called first.
func (o *OAuth) CreateAuthenticatedHttpClient(ctx context.Context) (*http.Client, error) {
Snippet
package main
import (
"context"
"fmt"
"io/ioutil"
"birnenlabs.com/lib/oauth"
)
func main() {
// "spotify" is a client name, the library will search for configuration
// in the $HOME/.config/oauth-spotify.json file.
o, _ := oauth.Create("spotify")
ctx := context.Background()
o.VerifyToken(ctx)
httpClient, _ := o.CreateAuthenticatedHttpClient(ctx)
resp, _ := httpClient.Get("https://api.spotify.com/v1/search?type=track&limit=2&q=Queen")
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
fmt.Printf(string(body))
}