cognitoclientgo

package module
v0.0.0-...-a296dd0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 13, 2019 License: Apache-2.0 Imports: 9 Imported by: 0

README

cognitoclientgo GoDoc Go Report Card Build

Implements authentication against AWS Cognito the same way as the client browser does (so you don't need the AWS IAM credentials to call the API).

Use client.Auth() before all requests. If client has a valid and fresh tokens it uses them. If client holds refresh token, it uses this one to get new JWT token and for the first time or after even refresh token expires it uses full SRP auth.

Use it if you want to write app or cli that has the same access as the regular registered user to your AWS Cognito User pool. I needed it to obtain the JWT token to authorize API calls to API Gateway that with Cognito Authorizer.

It doesn't support federated identities for now.

Usage

import "github.com/dacz/cognitoclientgo"

Example usage

c, err := cognitoclientgo.NewClient(client.Input{
    UserPoolID: os.Getenv("COGNITO_USER_POOL_ID"),
    ClientID:   os.Getenv("COGNITO_CLIENT_ID"),
    SecretHash: os.Getenv("COGNITO_SECRET_HASH"), // OPTIONAL if configured with you client app
    UserName:   os.Getenv("COGNITO_USERNAME"),
    Password:   os.Getenv("COGNITO_PASSWORD"),
})
if err != nil {
    ...
}

// jwtToken can be used in Authorization header sent to API GW
jwtToken, err := c.Auth()
if err != nil {
    ...
}

// once authorized you can call getUser to get info about user from Cognito
user, err := c.GetUser()
if err != nil {
    ...
}

Credits

SRP package: Alex Rudd (https://github.com/AlexRudd/cognito-srp) - lightly modified.

LICENSE

Apache License (see license file)

Documentation

Overview

Package cognitoclientgo implements authentication against AWS Cognito the same way as the client browser does.

Use it if you want to write app or cli that has the same access as the regular registered user to your AWS Cognito User pool. I needed it to obtain the JWT token to authorize API calls to API Gateway that with Cognito Authorizer.

You don't need the AWS IAM credentials. Currently it doesn't support federated identities.

Credentials

You'll need to specify:

UserPoolID: <string>
ClientID:   <string>
SecretHash: [OPTIONAL if configured with you client app] string
UserName:   <string>
Password:   <string>

You can get all these params from AWS web console.

Example usage

c, err := cognitoclientgo.NewClient(auth.Input{
	UserPoolID: os.Getenv("COGNITO_USER_POOL_ID"),
	ClientID:   os.Getenv("COGNITO_CLIENT_ID"),
	SecretHash: os.Getenv("COGNITO_SECRET_HASH"),
	UserName:   os.Getenv("COGNITO_USERNAME"),
	Password:   os.Getenv("COGNITO_PASSWORD"),
})
if err != nil {
	...
}

// jwtToken can be used in Authorization header sent to API GW
jwtToken, err := c.Auth()
if err != nil {
	...
}

// once authorized you can call getUser to get info about user from Cognito
user, err := c.GetUser()
if err != nil {
	...
}

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client is the main struct that enables auth

func NewClient

func NewClient(inp Input) (*Client, error)

NewClient initializes client to auth

func (*Client) Auth

func (c *Client) Auth() (string, error)

Auth returns the JWTToken and if needed it will start authorization flow

Example
package main

import (
	"encoding/json"
	"fmt"
	"log"
	"os"

	// "github.com/dacz/cognitoclientgo"
	"github.com/joho/godotenv"
)

func printAndExit(err error) {
	fmt.Printf("message: %s\ntype: %T\nvalue: %#v\n", err.Error(), err, err)
	os.Exit(1)
}

func main() {
	err := godotenv.Load()
	if err != nil {
		log.Fatal("Error loading .env file")
	}
	c, err := NewClient(Input{
		UserPoolID: os.Getenv("COGNITO_USER_POOL_ID"),
		ClientID:   os.Getenv("COGNITO_CLIENT_ID"),
		SecretHash: os.Getenv("COGNITO_SECRET_HASH"),
		UserName:   os.Getenv("COGNITO_USERNAME"),
		Password:   os.Getenv("COGNITO_PASSWORD"),
	})
	if err != nil {
		printAndExit(err)
	}

	jwtToken, err := c.Auth()
	if err != nil {
		printAndExit(err)
	}

	fmt.Printf("Token to use as JWT token is:\n%s\n", jwtToken)

	user, err := c.GetUser()
	if err != nil {
		printAndExit(err)
	}

	upretty, err := json.MarshalIndent(user, "", "    ")
	if err != nil {
		fmt.Printf("User data:\n%#v\n", *user)
	} else {
		fmt.Println(string(upretty))
	}

	fmt.Printf("%#v\n", c.Tokens())

	// should go from cache next time
	// user, err = c.GetUser()
	// if err != nil {
	// 	printAndExit(err)
	// }

	// should force to obtain fresh user data from Cognito no matter the cache
	// user, err = c.GetUser(true)
	// if err != nil {
	// 	printAndExit(err)
	// }
}
Output:

func (*Client) GetUser

func (c *Client) GetUser(forcesl ...bool) (*User, error)

GetUser asks for Cognito user data if send an argument 'true', it will force download data even if they are cached (pointer is not used because we don't want allow any modifications)

func (*Client) JWTToken

func (c *Client) JWTToken() string

JWTToken returns the token that can be sent in Authorization header to API Gateway to authorize against the Cognito UserPool

func (*Client) Tokens

func (c *Client) Tokens() map[string]string

Tokens returns all three tokens when they are empty, you probably need to Auth

type Input

type Input struct {
	UserPoolID string `json:"userPoolId"`
	ClientID   string `json:"clientId"`
	SecretHash string `json:"clientSecret"`
	UserName   string `json:"userName"`
	Password   string `json:"password"`
}

Input describes required parameters to login

type User

type User map[string]string

User holds user data from cognito

Directories

Path Synopsis
Package srp calculates the responses to cognito srp challenges to authenticate client and get tokens This is de facto utility package for main Auth package Is is de facto copy-paste from https://github.com/AlexRudd/cognito-srp (which is based on capless warrant: https://github.com/capless/warrant) The only changed thing is that I removed the dependency to aws sdk and aws cognitoidentityprovider because for this package they are not needed.
Package srp calculates the responses to cognito srp challenges to authenticate client and get tokens This is de facto utility package for main Auth package Is is de facto copy-paste from https://github.com/AlexRudd/cognito-srp (which is based on capless warrant: https://github.com/capless/warrant) The only changed thing is that I removed the dependency to aws sdk and aws cognitoidentityprovider because for this package they are not needed.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL