bankid

package module
v1.1.2 Latest Latest
Warning

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

Go to latest
Published: Apr 12, 2024 License: MIT Imports: 14 Imported by: 0

README

Kansuler/bankid

License Version Codacy Badge

A package to simplify integrations against the authentication and signing service BankID.

It is recommended to read through the developer guide thoroughly to understand the the process, and what responses that can occur.

API and detailed documentation can be found at https://godoc.org/github.com/Kansuler/bankid

Installation

go get github.com/Kansuler/bankid

Functions

// create new client
New(opts Options) (*bankID, error)

// authenticate user 
(b *bankID) Auth(ctx context.Context, opts AuthOptions) (result authSignResponse, err error)

// authenticate user over phone
(b *BankID) PhoneAuth(ctx context.Context, opts PhoneAuthOptions) (result phoneAuthResponse, err error)

// sign legal document
(b *bankID) Sign(ctx context.Context, opts SignOptions) (result authSignResponse, err error)

// collect status of sign or auth order
(b *bankID) Collect(ctx context.Context, opts CollectOptions) (result collectResponse, err error)

// cancel current pending order
(b *bankID) Cancel(ctx context.Context, opts CancelOptions) error

// generate hashed string for animated qr code
Qr(startToken, startSecret string, seconds int64) (string, error)

Usage

ctx := context.Background()

// For testing, you can use `bankid.TestSSLCertificate`
cert, err := ioutil.ReadFile("/path/to/your/cert.p12")
if err != nil {
	return err
}

b, err := bankid.New(bankid.Options{
    Passphrase:           "qwerty123",
    SSLCertificate:       cert,
	CertificateAuthority: bankid.TestCertificate,
    URL:                  bankid.TestURL,
    Timeout:              5,
})

response, err := b.Sign(ctx, bankid.SignOptions{
    EndUserIP:              "192.168.0.2",
    UserVisibleData:        base64.StdEncoding.EncodeToString([]byte("Signing test user")),
    UserVisibleDataFormat:  "simpleMarkdownV1",
})

qr := bankid.Qr(response.QrStartToken, response.QrStartSecret, 0)
if err != nil {
    return err
}

response2, err := b.Collect(ctx, bankid.CollectOptions{
	OrderRef: response.OrderRef,
})

if err != nil {
    return err
}

Contributing

Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.

Please make sure to update tests as appropriate.

Documentation

Overview

Package bankid provides methods that align with the BankID v6.0 API contract.

Index

Constants

View Source
const (
	TestURL = "https://appapi2.test.bankid.com"
	ProdURL = "https://appapi2.bankid.com"
)

Variables

View Source
var (
	//go:embed prod.ca.crt
	ProdCACertificate []byte

	//go:embed test.ca.crt
	TestCACertificate []byte

	//go:embed testcert.p12
	TestSSLCertificate []byte
)

Functions

func Qr

func Qr(startToken, startSecret string, seconds int64) (string, error)

Qr is a helper function that generates a string that is transformed into a QR code. It takes startToken, startSecret and seconds since the auth order was created. The QR Code need to be updated every second.

Types

type AuthOptions

type AuthOptions struct {
	// Required: The user IP address as seen by RP. String. IPv4 and IPv6 is allowed. Correct IP address must be the IP
	// address representing the user agent (the end user device) as seen by the RP. In case of inbound proxy, special
	// considerations may need to be taken into account to get the correct address. In some use cases the IP address is
	// not available, for instance in voice-based services. In these cases, the internal representation of those
	// systems’ IP address may be used.
	EndUserIp string `json:"endUserIp"`

	// Optional: Text displayed to the user during authentication with BankID, with the purpose of providing context for
	// the authentication and to enable users to detect identification errors and averting fraud attempts. The text can
	// be formatted using CR, LF and CRLF for new lines. The text must be encoded as UTF-8 and then base 64 encoded.
	// 1—1 500 characters after base 64 encoding.
	UserVisibleData string `json:"userVisibleData,omitempty"`

	// Optional: Data not displayed to the user. String. The value must be base 64-encoded. 1-1 500 characters after
	// base 64-encoding.
	UserNonVisibleData string `json:"userNonVisibleData,omitempty"`

	// Optional: If present, and set to “simpleMarkdownV1”, this parameter indicates that userVisibleData holds
	// formatting characters which, will potentially make the text displayed to the user nicer to look at. For further
	// information of formatting options, please see the Guidelines for formatting text.
	UserVisibleDataFormat string `json:"userVisibleDataFormat,omitempty"`

	// Optional: Requirements on how the auth or sign order must be performed.
	Requirement Requirement `json:"requirement,omitempty"` // Optional settings for the authentication process
}

AuthOptions for the authentication request

type AuthSignResponse added in v1.1.1

type AuthSignResponse struct {
	OrderRef       string `json:"orderRef"`
	AutoStartToken string `json:"autoStartToken"`
	QrStartToken   string `json:"qrStartToken"`
	QrStartSecret  string `json:"qrStartSecret"`
}

AuthSignResponse is the response from the auth request

type BankID

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

BankID holds settings for this session

func New

func New(opts Options) (*BankID, error)

New creates a new client

func (*BankID) Auth

func (b *BankID) Auth(ctx context.Context, opts AuthOptions) (result AuthSignResponse, err error)

Auth initiates an authentication order. Use the collect method to query the status of the order. If the request is successful the response includes orderRef, autoStartToken, qrStartToken and qrStartSecret.

func (*BankID) Cancel

func (b *BankID) Cancel(ctx context.Context, opts CancelOptions) error

Cancel 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(ctx context.Context, opts CollectOptions) (result CollectResponse, err error)

Collect provides the result of a sign or auth order using the orderRef as reference. You should keep on calling collect every two seconds as long as status indicates pending. You must abort if status indicates failed. The user identity is returned when complete.

func (*BankID) PhoneAuth added in v1.1.0

func (b *BankID) PhoneAuth(ctx context.Context, opts PhoneAuthOptions) (result PhoneAuthResponse, err error)

PhoneAuth initiates a phone authentication order. Use the collect method to query the status of the order. If the request is successful the response includes orderRef, autoStartToken, qrStartToken and qrStartSecret.

func (*BankID) Sign

func (b *BankID) Sign(ctx context.Context, opts SignOptions) (result AuthSignResponse, err error)

Sign initiates an signing order. Use the collect method to query the status of the order. If the request is successful the response includes orderRef, autoStartToken, qrStartToken and qrStartSecret.

type CancelOptions

type CancelOptions struct {
	// OrderRef as given by either sign or auth request
	OrderRef string `json:"orderRef"`
}

CancelOptions for the cancel method

type CollectOptions

type CollectOptions struct {
	// OrderRef as given by either sign or auth request
	OrderRef string `json:"orderRef"`
}

CollectOptions for the collect method

type CollectResponse added in v1.1.1

type CollectResponse struct {
	OrderRef       string             `json:"orderRef"`
	Status         StatusType         `json:"status"` // pending, failed, complete
	HintCode       HintCodeType       `json:"hintCode"`
	CompletionData CompletionDataType `json:"completionData"`
}

type CompletionDataDeviceType added in v1.1.1

type CompletionDataDeviceType struct {
	IpAddress string `json:"ipAddress"`
	Uhi       string `json:"uhi"`
}

type CompletionDataType added in v1.1.1

type CompletionDataType struct {
	User            CompletionDataUserType   `json:"user"`
	Device          CompletionDataDeviceType `json:"device"`
	BankIdIssueDate string                   `json:"bankIdIssueDate"`
	StepUp          bool                     `json:"stepUp"`
	Signature       string                   `json:"signature"`
	OcspResponse    string                   `json:"ocspResponse"`
}

type CompletionDataUserType added in v1.1.1

type CompletionDataUserType struct {
	PersonalNumber string `json:"personalNumber"`
	Name           string `json:"name"`
	GivenName      string `json:"givenName"`
	Surname        string `json:"surname"`
}

type HintCodeType added in v1.1.1

type HintCodeType string
const (
	// OutstandingTransaction Order is pending. The BankID app has not yet received the order. The hintCode will later
	// change to noClient, started or userSign.
	OutstandingTransaction HintCodeType = "outstandingTransaction"

	// NoClient Order is pending. The client has not yet received the order.
	NoClient HintCodeType = "noClient"

	// Started Order is pending. A BankID client has launched with autostarttoken but a usable ID has not yet been found
	// in the client. When the client launches there may be a short delay until all IDs are registered. The user may not
	// have any usable IDs, or is yet to insert their smart card.
	Started HintCodeType = "started"

	// UserMrtd Order is pending. A client has launched and received the order but additional steps for providing MRTD
	// information is required to proceed with the order.
	UserMrtd HintCodeType = "userMrtd"

	// UserCallConfirm Order is waiting for the user to confirm that they have received this order while in a call with
	// the RP.
	UserCallConfirm HintCodeType = "userCallConfirm"

	// UserSign Order is pending. The BankID client has received the order.
	UserSign HintCodeType = "userSign"

	// ExpiredTransaction The order has expired. The BankID security app/program did not launch, the user did not
	// finalize the signing or the RP called collect too late.
	ExpiredTransaction HintCodeType = "expiredTransaction"

	// CertificateErr This error is returned if:
	// 1. The user has entered the wrong PIN code too many times. The BankID cannot be used.
	// 2. The user’s BankID is blocked.
	// 3. The user’s BankID is invalid.
	CertificateErr HintCodeType = "certificateErr"

	// UserCancel The order was cancelled by the user. userCancel may also be returned in some rare cases related to
	// other user interactions.
	UserCancel HintCodeType = "userCancel"

	// Cancelled The order was cancelled. The system received a new order for the user.
	Cancelled HintCodeType = "cancelled"

	// StartFailed The user did not provide their ID or the client did not launch within a certain time limit. Potential
	// causes are:
	// 1. RP did not use autoStartToken when launching the BankID security app. RP must correct this in their
	// implementation.
	// 2. Client software was not installed or other problem with the user’s device.
	StartFailed HintCodeType = "startFailed"
)

These are possible, but not exclusive hint codes. You need to handle other codes as well

type Options

type Options struct {
	// Passphrase is the password for the p12 encoded SSL certificate
	Passphrase string

	// SSLCertificate is a byte encoded array with the SSL certificate content
	SSLCertificate []byte

	// CertificateAuthority is a byte encoded array with the CA certificate content
	CertificateAuthority []byte

	// URL is the endpoint which we use to talk with BankID and can be replaced
	URL string

	// Timeout in seconds for the http client
	Timeout int // Client timeout in seconds
}

Options are settings that is used by the http client

type PhoneAuthOptions added in v1.1.0

type PhoneAuthOptions struct {
	// Required: The personal number of the user. String. 12 digits.
	PersonalNumber string `json:"personalNumber"`

	// Required: Indicate if the user or the RP initiated the phone call.
	// user: user called the RP
	CallInitiator string `json:"callInitiator"`

	// Optional: Text displayed to the user during authentication with BankID, with the purpose of providing context for
	// the authentication and to enable users to detect identification errors and averting fraud attempts. The text can
	// be formatted using CR, LF and CRLF for new lines. The text must be encoded as UTF-8 and then base 64 encoded.
	// 1—1 500 characters after base 64 encoding.
	UserVisibleData string `json:"userVisibleData,omitempty"`

	// Optional: Data not displayed to the user. String. The value must be base 64-encoded. 1-1 500 characters after
	// base 64-encoding.
	UserNonVisibleData string `json:"userNonVisibleData,omitempty"`

	// Optional: If present, and set to “simpleMarkdownV1”, this parameter indicates that userVisibleData holds
	// formatting characters which, will potentially make the text displayed to the user nicer to look at. For further
	// information of formatting options, please see the Guidelines for formatting text.
	UserVisibleDataFormat string `json:"userVisibleDataFormat,omitempty"`

	// Optional: Requirements on how the auth or sign order must be performed.
	Requirement Requirement `json:"requirement,omitempty"` // Optional settings for the authentication process
}

PhoneAuthOptions for the phone authentication request

type PhoneAuthResponse added in v1.1.1

type PhoneAuthResponse struct {
	OrderRef string `json:"orderRef"`
}

PhoneAuthResponse is the response from the phone auth request

type Requirement

type Requirement struct {
	PinCode             bool     `json:"pinCode,omitempty"`
	Mrtd                bool     `json:"mrtd,omitempty"`
	CardReader          string   `json:"cardReader,omitempty"`
	CertificatePolicies []string `json:"certificatePolicies,omitempty"`
	PersonalNumber      string   `json:"personalNumber,omitempty"`
}

Requirement is optional parameters that control the authentication process Read more about these on https://www.bankid.com/utvecklare/guider/teknisk-integrationsguide/graenssnittsbeskrivning/auth-and-sign Requirements

type ServiceError added in v1.1.1

type ServiceError struct {
	ErrorCode string `json:"errorCode"`
	Details   string `json:"details"`
}

ServiceError is the error response from the BankID Api

type SignOptions

type SignOptions struct {
	// Required: The user IP address as seen by RP. String. IPv4 and IPv6 is allowed. Correct IP address must be the IP
	// address representing the user agent (the end user device) as seen by the RP. In case of inbound proxy, special
	// considerations may need to be taken into account to get the correct address. In some use cases the IP address is
	// not available, for instance in voice-based services. In these cases, the internal representation of those
	// systems’ IP address may be used.
	EndUserIp string `json:"endUserIp"`

	// Required: Text to be displayed to the user. String. The text can be formatted using CR, LF and CRLF for new
	// lines. The text must be encoded as UTF-8 and then base 64 encoded. 1 – 40,000 characters after base 64 encoding.
	UserVisibleData string `json:"userVisibleData,omitempty"`

	// Optional: Data not displayed to the user. String. The value must be base 64 encoded. 1 – 200,000 characters after
	// base 64-encoding.
	UserNonVisibleData string `json:"userNonVisibleData,omitempty"`

	// Optional: If present, and set to “simpleMarkdownV1”, this parameter indicates that userVisibleData holds
	// formatting characters which, will potentially make the text displayed to the user nicer to look at. For further
	// information of formatting options, please see the Guidelines for formatting text.
	UserVisibleDataFormat string `json:"userVisibleDataFormat,omitempty"`

	// Optional: Requirements on how the sign order must be performed
	Requirement *Requirement `json:"requirement,omitempty"`
}

SignOptions for the sign request

type StatusType added in v1.1.1

type StatusType string
const (
	// Pending is the status of a pending order and means hintCode was provided
	Pending StatusType = "pending"

	// Failed is the status of a failed order and means hintCode was provided
	Failed StatusType = "failed"

	// Complete is the status of a completed order and means completionData was provided
	Complete StatusType = "complete"
)

Jump to

Keyboard shortcuts

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