bankid

package module
v1.3.0 Latest Latest
Warning

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

Go to latest
Published: Jun 14, 2022 License: MIT Imports: 19 Imported by: 1

README

BankID library

A library for providing BankID services as an RP (Relying party). Supports the latest v5 features.

Build Status Reviewdog Go Report Card GoDoc Codacy Badge

Check out the API Documentation http://godoc.org/github.com/NicklasWallgren/bankid

Installation

The library can be installed through go get

go get github.com/NicklasWallgren/bankid

Supported versions

We support the two major Go versions, which are 1.17 and 1.18 at the moment.

Features

  • Supports all v5.1 features

SDK

// Creates new BankID instance
New(configuration *configuration.Configuration) (*BankID)

// Initiates an authentication order 
(b BankID) Authenticate(context context.Context, payload *AuthenticationPayload) (*AuthenticateResponse, error)

// Initiates an sign order
(b BankID) Sign(context context.Context, payload *SignPayload) (*SignResponse, error)

// Collects the result of a sign or auth order suing the orderRef as reference
(b BankID) Collect(context context.Context, payload *CollectPayload) (*CollectResponse, error)

// Cancels an ongoing sign or auth order
(b BankID) Cancel(context context.Context, payload *CancelPayload) (*CancelResponse, error)

Examples

Initiate sign request

import (
    "context"
    "fmt"
    "io/ioutil"

    "github.com/NicklasWallgren/bankid"
    "github.com/NicklasWallgren/bankid/configuration"
)

certificate, err := ioutil.ReadFile("path/to/environment.p12")
if err != nil {
    panic(err)
}

config := configuration.New(
    configuration.TestEnvironment,
    &configuration.Pkcs12{Content: certificate, Password: "p12 password"},
)

bankId := bankid.New(config)

payload := bankid.SignPayload{PersonalNumber: "<INSERT PERSONAL NUMBER>", EndUserIP: "192.168.1.1", UserVisibleData: "Test"}

response, err := bankId.Sign(context.Background(), &payload)

if err != nil {
	if response, ok := err.(*bankid.ErrorResponse); ok {
        fmt.Printf("ErrResponse: %s - %s \n", response.Details, response.ErrorCode)
    }

    fmt.Printf("%#v", err)
    return
}

fmt.Println(response.Collect(ctx))

Unit tests

go test -v -race $(go list ./... | grep -v vendor)
Code Guide

We use GitHub Actions to make sure the codebase is consistent (golangci-lint run) and continuously tested (go test -v -race $(go list ./... | grep -v vendor)). We try to keep comments at a maximum of 120 characters of length and code at 120.

Contributing

If you find any problems or have suggestions about this library, please submit an issue. Moreover, any pull request, code review and feedback are welcome.

Contributors

License

MIT

Documentation

Index

Constants

View Source
const (
	// StatusPending is the status of a pending order. hintCode describes the status of the order.
	StatusPending = "pending"
	// StatusComplete is the status of a complete order. completionData holds user information.
	StatusComplete = "complete"
	// StatusFailed is the status of a failed order. hintCode describes the error.
	StatusFailed = "failed"
	// StatusAlreadyInProgress is the hint for a order where an auth or sign request with personal number was sent, but an order for the user is already in progress. The order is aborted. No order is created.
	// Details are found in details.
	StatusAlreadyInProgress = "alreadyInProgress"
	// HintCodeOutstandingTransaction is the hint for a order that is pending. The client has not yet received the order.
	// The hintCode will later change to noClient, started or userSign.
	HintCodeOutstandingTransaction = "outstandingTransaction"
	// HintCodeNoClient is the hint for a order that is pending. The client has not yet received the order.
	HintCodeNoClient = "noClient"
	// HintCodeStarted is the hint for a order that is pending. A Client has started with the 'autostarttoken' but a usable ID has not yet been found in the started client.
	// When the client start the may be a short delay until all ID:s are registered.
	// The user may not have any usable ID:s at all, or has not yet inserted their smart card.
	HintCodeStarted = "started"
	// HintCodeUserSign is the hint for a order that is pending. A client has received the order.
	HintCodeUserSign = "userSign"
	// HintCodeExpiredTransaction is the hint for a order that has expired.
	HintCodeExpiredTransaction = "expiredTransaction"
	// HintCodeCertificateError is a hint for when the provided certificate is invalid.
	HintCodeCertificateError = "certificateErr"
	// HintCodeUserCancel is a hint for when a user has cancelled a order.
	HintCodeUserCancel = "userCancel"
	// HintCodeCancelled is a hint for a order that has been cancelled.
	HintCodeCancelled = "cancelled"
	// HintCodeStartFailed is a hint for when a order could not be initialized.
	HintCodeStartFailed = "startFailed"
)

Variables

This section is empty.

Functions

This section is empty.

Types

type AuthenticateResponse

type AuthenticateResponse struct {
	// Used as reference to this order when the client is started automatically.
	AutoStartToken string `json:"autoStartToken"`
	// Used to collect the status of the order.
	OrderRef string `json:"orderRef"`
	// Used to compute the animated QR code.
	QrStartToken string `json:"qrStartToken"`
	// Used to compute the animated QR code.
	QrStartSecret string `json:"qrStartSecret"`
	// The time when response was returned.
	TimeOfResponse time.Time
	// contains filtered or unexported fields
}

AuthenticateResponse contains the fields specific for the authentication response.

func (AuthenticateResponse) Cancel

Cancel - Cancels an ongoing sign or auth order.

This is typically used if the user cancels the order in your service or app.

func (AuthenticateResponse) Collect

func (a AuthenticateResponse) Collect(context context.Context) (*CollectResponse, error)

Collect - Collects the result of a sign or auth order suing the orderRef as reference.

RP should keep calling collect every two seconds as long as status indicates pending. RP must abort if status indicates failed. The user identity is returned when complete.

func (*AuthenticateResponse) Decode

func (a *AuthenticateResponse) Decode(subject io.ReadCloser, bankID *BankID) (Response, error)

Decode reads the JSON-encoded value and stories it in a authenticate response struct.

func (AuthenticateResponse) QrCodeContent added in v1.3.0

func (a AuthenticateResponse) QrCodeContent() (string, error)

QrCodeContent - Generates the QR code content based on qrStartToken, qrStartSecret and seconds elapsed since response.

The QR code is generated by the RP every second using the pattern "bankid.qrStartToken.time.qrAuthCode" as input.

func (*AuthenticateResponse) String

func (a *AuthenticateResponse) String() string

type AuthenticationPayload

type AuthenticationPayload struct {
	Payload `json:"-"`
	// The personal number of the user. String 12 digits. Century must be included.
	// If the personal number is excluded, the client must be started with
	// the autoStartToken returned in the response.
	PersonalNumber string `validate:"omitempty,numeric" json:"personalNumber,omitempty"`
	// The user IP address as seen by RP. String, IPv4 and IPv6 is allowed.
	EndUserIP string `validate:"ip" json:"endUserIp"`
	// Requirements on how the auth or sign order must be performed.
	Requirement *Requirement `json:"requirement,omitempty"`
}

AuthenticationPayload holds the required and optional fields of the authentication request.

type BankID

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

BankID contains the validator and configuration context.

func New

func New(configuration *configuration.Configuration) *BankID

New returns a new instance of 'BankID'.

func (BankID) Authenticate

func (b BankID) Authenticate(context context.Context, payload *AuthenticationPayload) (*AuthenticateResponse, error)

Authenticate - Initiates an authentication order.

Use the collect method to query the status of the order. If the request is successful, the orderRef and autoStartToken is returned.

func (BankID) Cancel

func (b BankID) Cancel(context context.Context, payload *CancelPayload) (*CancelResponse, error)

Cancel - Cancels an ongoing sign or auth order.

This is typically used if the user cancels the order in your service or app.

func (BankID) Collect

func (b BankID) Collect(context context.Context, payload *CollectPayload) (*CollectResponse, error)

Collect - Collects the result of a sign or auth order suing the orderRef as reference.

RP should keep calling collect every two seconds as long as status indicates pending. RP must abort if status indicates failed. The user identity is returned when complete.

func (BankID) QRCodeContent added in v1.3.0

func (b BankID) QRCodeContent(qrStartToken, qrStartSecret string, seconds int) (string, error)

QRCodeContent - Generates the QR code content based on qrStartToken, qrStartSecret and seconds elapsed since response.

The QR code is generated by the RP every second using the pattern "bankid.qrStartToken.time.qrAuthCode" as input.

func (BankID) Sign

func (b BankID) Sign(context context.Context, payload *SignPayload) (*SignResponse, error)

Sign - Initiates a sign order.

Use the collect method to query the status of the order. If the request is successful, the orderRef and autoStartToken is returned.

type CancelPayload

type CancelPayload struct {
	Payload `json:"-"`
	// The orderRef from the response from authentication or sign.
	OrderRef string `json:"orderRef"`
}

CancelPayload holds the required fields of the collect Payload.

type CancelResponse

type CancelResponse struct{}

CancelResponse contrains fields for the cancel response.

func (*CancelResponse) Decode

func (c *CancelResponse) Decode(subject io.ReadCloser, bankID *BankID) (Response, error)

Decode reads the JSON-encoded value and stories it in a cancel response struct.

type Client

type Client interface {
	// contains filtered or unexported methods
}

Client is the interface implemented by types that can invoke the BankID REST API.

type CollectPayload

type CollectPayload struct {
	Payload `json:"-"`
	// The orderRef from the response from authentication or sign.
	OrderRef string `json:"orderRef"`
}

CollectPayload holds the required fields of the collect Payload.

type CollectResponse

type CollectResponse struct {
	OrderRef       string         `json:"orderRef"`
	Status         string         `json:"status"`
	HintCode       string         `json:"hintCode"`
	CompletionData completionData `json:"completionData"`
}

CollectResponse contains the fields specific for the collect response.

func (*CollectResponse) Decode

func (c *CollectResponse) Decode(subject io.ReadCloser, bankID *BankID) (Response, error)

Decode reads the JSON-encoded value and stories it in a collect response struct.

func (CollectResponse) IsComplete

func (c CollectResponse) IsComplete() bool

IsComplete return true if the order is complete. completionData holds user information.

func (CollectResponse) IsFailed

func (c CollectResponse) IsFailed() bool

IsFailed return true if something went wrong with the order. hintCode describes the error.

func (CollectResponse) IsPending

func (c CollectResponse) IsPending() bool

IsPending return true if the order is being processed. hintCode describes the status of the order.

func (CollectResponse) String

func (c CollectResponse) String() string

type ErrorResponse

type ErrorResponse struct {
	ErrorCode string `json:"errorCode"`
	Details   string `json:"details"`
	// contains filtered or unexported fields
}

ErrorResponse contains fields for the error response.

func (*ErrorResponse) Decode

func (e *ErrorResponse) Decode(subject io.ReadCloser, bankID *BankID) (Response, error)

Decode reads the JSON-encoded value and stories it in a error response struct.

func (ErrorResponse) Error

func (e ErrorResponse) Error() string

func (*ErrorResponse) String

func (e *ErrorResponse) String() string

type Option

type Option func(*client)

Option definition.

type Payload

type Payload interface{}

Payload is the interface implemented by types that holds the fields to be delivered to the API.

type Request

type Request interface {
	URI() string
	Payload() Payload
	Response() Response
}

Request is the interface implemented by types that holds the request context fields.

type Requirement

type Requirement struct {
	CardReader             string `validate:"omitempty,len=10" json:"cardReader,omitempty"`
	CertificatePolicies    string `validate:"omitempty,len=10" json:"certificatePolicies,omitempty"`
	IssuerCn               string `validate:"omitempty,len=10" json:"issuerCn,omitempty"`
	AutoStartTokenRequired bool   `json:"autoStartTokenRequired,omitempty"`
	AllowFingerprint       bool   `json:"allowFingerprint,omitempty"`
	TokenStartRequired     bool   `json:"tokenStartRequired,omitempty"`
}

Requirement holds the required and optional fields of the Requirement DTO.

type Response

type Response interface {
	Decode(subject io.ReadCloser, bankID *BankID) (Response, error)
}

Response is the interface implemented by types that holds the response context fields.

type SignPayload

type SignPayload struct {
	Payload `json:"-"`
	// The personal number of the user. String 12 digits. Century must be included.
	// If the personal number is excluded, the client must be started with
	// the autoStartToken returned in the response.
	PersonalNumber string `validate:"numeric,len=12" json:"personalNumber"`
	// The user IP address as seen by RP. String, IPv4 and IPv6 is allowed.
	EndUserIP string `validate:"ip" json:"endUserIp"`
	// The text to be displayed and signed. The text can be formatted using CR, LF and CRLF for new lines.
	// 1--40 000 characters after base 64 encoding.
	UserVisibleData string `validate:"required,base64Length=40000" json:"userVisibleData"`
	// Data not displayed for the user.
	// 1-200 000 characters after base 64-encoding.
	UserNonVisibleData string `json:"userNonVisibleData,omitempty"`
	// Requirements on how the auth or sign order must be performed.
	Requirement *Requirement `json:"requirement,omitempty"`
}

SignPayload holds the required and optional fields for the sign Payload.

func (SignPayload) MarshalJSON

func (s SignPayload) MarshalJSON() ([]byte, error)

MarshalJSON returns a JSON encoded 'SignPayload'.

type SignResponse

type SignResponse struct {
	AuthenticateResponse
}

SignResponse contains the fields specific for the sign response.

func (*SignResponse) Decode

func (s *SignResponse) Decode(subject io.ReadCloser, bankID *BankID) (Response, error)

Decode reads the JSON-encoded value and stories it in a sign response struct.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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