# Authentication

> Pass your API key to the client: a credentials profile, environment variables, or options.

Source: https://docs.stxapp.io/sdks/go/authentication/

Building an app that acts for other STX members? See [Apps](/sdks/go/apps/) and [Sign in with STX](/sdks/go/sign-in-with-stx/).

The client needs your API key ID and its Ed25519 private key, as a path to the PEM file or as the PEM text. Creating a key, how requests are signed, and why a signature fails are covered on [Authentication](/api/authentication/).

There are three ways to hand the key to the client. When more than one is set, options win over environment variables, and environment variables win over the profile.

## A credentials profile

Add a profile to `~/.stx/credentials`:

```ini
[default]
region   = us
env      = demo
key_id   = 3f1c9a52-7d4e-4b8a-9c21-5e6f7a8b9c0d
key_file = ~/.stx/stx-key.pem
```

`region` and `env` pick the exchange; the values for each are listed under [Environments](/sdks/go/environments/). `stx.New()` with no options reads `STX_PROFILE`, then the `[default]` section, so the examples in this guide work as written:

```go
client, err := stx.New()
```

An API key works on one exchange only. To keep keys for more than one, add a section per key under any name you like, and pick one with `stx.WithProfile`:

```go
client, err := stx.New(stx.WithProfile("my-demo"))
```

`stx.WithCredentialsFile` reads a file other than `~/.stx/credentials`.

## Environment variables

```bash
export STX_REGION=us STX_ENV=demo
export STX_KEY_ID=3f1c9a52-7d4e-4b8a-9c21-5e6f7a8b9c0d
export STX_PRIVATE_KEY=~/.stx/stx-key.pem   # a path, or the PEM text
```

`STX_HOST`, `STX_PROFILE` and `STX_CREDENTIALS` (the path of the credentials file) are also read.

## Options

```go
client, err := stx.New(
	stx.WithEnvironment(stx.USDemo),
	stx.WithKey(os.Getenv("MY_KEY_ID"), os.Getenv("MY_KEY_PEM")), // a path or the PEM text
)
```

If the key lives in an HSM or KMS, pass a `crypto.Signer` whose public key is Ed25519 instead of the PEM:

```go
var signer crypto.Signer // from your KMS client
client, err := stx.New(stx.WithEnvironment(stx.USDemo), stx.WithSigner("3f1c9a52-7d4e-4b8a-9c21-5e6f7a8b9c0d", signer))
```

`stx.WithAuth` takes any other `stx.Auth`, such as an OAuth token from the [oauth package](/sdks/go/apps/).

## Check it works

```go
me, err := client.Account.Me(ctx)
if err != nil {
	log.Fatal(err)
}
fmt.Println(me.UserID, me.Scope) // scope: "read_only" or "read_write"
// e6528824-b4e0-4ff8-bd70-36e5904738d1 read_write
```

A bad key, or a machine clock that has drifted, returns an error that matches `stx.ErrUnauthorized`. A client created without a key still works for the public WebSocket channels; REST calls return an error that matches `stx.ErrConfig`.
