---
title: "Authentication Setup for Nettskjema API"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Authentication Setup for Nettskjema API}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r}
#| label: setup
#| include: false

knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  error = FALSE,
  fig.path = "static"
)

vcr::setup_knitr(prefix = "auth-")
nettskjemar:::mock_if_no_auth()

```

This vignette explains how to set up authentication with the Nettskjema API.
Authentication is required to connect to the API endpoints and perform operations.

## Setting Up Authentication

The Nettskjema API uses OAuth 2.1 for authentication.
This involves creating a registered API client in the Nettskjema system, which provides you with a client ID and client secret.

### Setting up a client

Before using the functions, you need the following:

1. **A registered API client** in Nettskjema.
2. **Your client credentials** (client ID and client secret). These are provided when you register the client.

To register a client go to the [nettskjema authorization portal](https://authorization.nettskjema.no/) or use the `ns_create_client()` function to open the url.
Here you will be asked to log in with your user account, so you can create the client.


### Add Credentials to Your `.Renviron` File

To prevent hardcoding your credentials in your scripts, add the following entries to your `.Renviron` file. 
The `.Renviron` file is a hidden file in your home directory that R reads on startup.

1. Open your `.Renviron` file. You can create or edit it with:

```r
file.edit(fs::path_home(".Renviron"))
```

2. Add your credentials:

```
NETTSKJEMA_CLIENT_ID=your_client_id
NETTSKJEMA_CLIENT_SECRET=your_client_secret
```

Replace `your_client_id` and `your_client_secret` with the actual values you received from Nettskjema.

3. Save and close the file.

4. Restart your R session to the load changes.

### Check your Situation report

Once you have these two environment variables set, you should check your status with connecting to the API by running `ns_sitrep()`. 
This function should give you a clear report on whether you are ready to connect to the API.

```{r}
#| label: sitrep
#| cassette: true

library(nettskjemar)

ns_sitrep()
```

The situation report will inform you if:

- Your client ID and client secret are set.
- You can successfully authenticate with the Nettskjema API.
- You have access to any forms through the API.

If everything is set up correctly, you should see a message indicating that you are authenticated and ready to use the API.

### Accessing forms

To access forms, you need to add the client to each form you want it to have access to.
This is similar to the procedures necessary in api v2, for those who had experience with that.

![Screenshot of the Nettskjema Authorization portal. There is a table with "My clients", with the header row: Client Id, Username, Client Name, Created and Expires, with three dots at the end for more options. The client id is a SHA hash, and the username is the same SHA has appended with @apiclient.](static/client_overview.png)

You will need to go to each Nettskjema forms `Settings -> Permissions -> Editing permissions` and add the client id in the username format `<cliendId>@apiclient` to every form you want this specific client to have access to.

This means you can create custom clients with specific user access to particular forms, rather than having a single client with overall access to everything you have access to.
While this creates an initial burden of set up, it also allows more control and granularity for security.

## Working with the client

The clients you set up are _not_ user-centered.
That means they are intended to be shared with trusted collaborators you want to also access you form through the API.
While it is important to keep the client secret an actual secret, it is a secret you _can_ share with those you trust to have API access. 
This makes it possible for teams to work efficiently with the API collaboratively, without the need for each individual to make a client.

**Note that** sharing the client id and client secret will not give any _user_ access to forms in the nettskjema portal, only access to the specific forms that one client has access to _through the API_.

With that being said, here we have provided information about [adding the secret to you `.Renviron` file](#add-credentials-to-your--renviron-file).
Please note, that if you do this, you should **not by any means** share this file openly.
If you and your team work with `git` for instance, this should **never** be added to your git history.

If you by mistake share the secret with someone who should not have access, or you only wanted to grant temporary access, the easiest way to revoke the access, is to [Renew the client](#renewing-the-client-secret).
This will create a new client secret, and render the old invalid.

### Renewing the client secret

The client is valid for one year, at which point you will need to renew it for it to continue working.
Renewing means getting a new secret, not a whole new client, meaning the client will retain access to all the forms you have added it to, and you won't need to re-do that part of the work.

To renew the client, go to the [authorization portal](https://authorization.nettskjema.no/), and click the three dots next to the client you want to renew, and choose "Renew".
You will then get a new secret, which you will need to add to you .Renviron file, [like before](#add-credentials-to-your--renviron-file), by replacing the one you already have there.

### Adding colleagues

You can give colleagues administrative access to the client by adding them as an "Editor".
**Note that** adding someone as an editor does not grant them direct access to forms through their user, only to the credentials needed to access specific forms through the API.

By having more editors to a client, means sharing the responsibility of keeping the client up-to-date and renewing it when needed. 
This is advised so that more people can act quickly if the secret has been leaked by mistake by other team members.
Having a couple of editors is a good idea for redundancy, but make sure to limit to only necessary team members.


## Troubleshooting

1. **Invalid Credentials**: Ensure your client ID and client secret are correct and have been properly registered in Nettskjema.
2. **Environment Variables Not Loaded**: Ensure you've added your credentials to `.Renviron` **and** restarted your R session, the last part is necessary for R to access the new information. 
Subsequent R sessions should automatically load the credentials from `.Renviron`.

## More information

More information about the client authentication can be found on the [UiO webpages](https://www.uio.no/tjenester/it/adm-app/nettskjema/hjelp/api-clients-v3.md), where the remaining API is documented.
