Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

added docs for prefilling by query params #1998

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ weight: 30
aliases:
- /altinn-studio/guides/prefill/
---
As of today, Altinn offers three methods for prefilling data in an app for a user.
As of today, Altinn offers four methods for prefilling data in an app for a user.
These methods can be combined freely to reach the desired result.

{{<children />}}
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ weight: 30
aliases:
- /nb/altinn-studio/guides/prefill/
---
Altinn tilbyr i dag tre fremgangsmåter for å forhåndsutfylle data i en app for en sluttbruker.
Altinn tilbyr i dag fire fremgangsmåter for å forhåndsutfylle data i en app for en sluttbruker.
Disse metodene kan kombineres fritt for å oppnå ønsket resultat.

{{<children />}}
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
---
title: Prefilling data based on query parameters
linktitle: Query parameters
description: How to configure prefill for an app based on query parameters.
toc: false
weight: 400
---

Altinn apps support prefill based on query parameters.

This allows users to click a link like https://ttd.apps.tt02.altinn.no/ttd/stateless-app/set-query-params?jobTitle=designer,
and have the word 'designer' be prefilled into a datamodel field.

However, there are a few important caveats regarding security when using this approach.

Firstly, query parameter prefill can only be used in a stateless task.
If we did not have this requirement, it would be possible to for an attacker to change the value in the parameter and have that value show up directly in the receivers altinn inbox.

By going via a stateless task, we ensure that the data is displayed to the user before instantiating, so that the user is still in control of what data is saved.

Second we highly recommend inspecting the value of the query parameters in your application. This way you ensure that only valid data can be prefilled, so that an attacker can't send someone a link like:

https%3A%2F%2Fttd.apps.tt02.altinn.no%2Fttd%2Fstateless-app%2Fset-query-params%3FjobTitle%3DIm%20a%20scammer

and have the text "Im a scammer" show up in your application.

## How to configure query parameter prefill

### 1. configure <stateless_datamodel>.prefill.json

In your models folder, create a file called <stateless_datamodel>.prefill.json (if the name of your model is tax_return, the file should be called tax_return.prefill.json).

Example:

```json
{
"$schema": "https://altinncdn.no/schemas/json/prefill/prefill.schema.v1.json",
"QueryParameters": {
"jobTitle": "JobTitle"
}
}
```

This requires you to have a field called ```JobTitle``` in your datamodel, and allows you to prefill this field with a link like:

https://ttd.apps.tt02.altinn.no/ttd/stateless-app/set-query-params?jobTitle=designer

Important note: the link to prefill only works on the path ```:org/:app/set-query-params```, like in the example above.

Also note that only query parameters defined in <stateless_datamodel>.prefill.json will work. If you try to link to https://ttd.apps.tt02.altinn.no/ttd/stateless-app/set-query-params?somethingelse=designer,
you will get an error.

### 2. Configure InstantiationProcessor and InstantiationButton

To save the value from the query parameter when instantiating from the stateless task, you need to implement an InstantiationProcessor.

Here you will save the prefilled value from your stateless task, into your stateful task.

In the example below we transfer the value of JobTitle from the stateless task into a value called PrefilledJobTitle in the stateful task.

```c#
namespace Altinn.App.AppLogic.DataProcessing
{
/// <summary>
/// Represents a business logic class responsible for running logic related to instantiation.
/// </summary>
public class InstantiationProcessor: IInstantiationProcessor
{


public async Task DataCreation(Instance instance, object data, Dictionary<string, string> prefill)
{
if (data.GetType() == typeof(Skjema))
{
if (prefill.ContainsKey("JobTitle"))
{
skjema.PrefilledJobTitle = prefill["JobTitle"];
}
}
await Task.CompletedTask;
}
}
```

You also need to configure an InstantiationButton in your layout with the mapping:

```json
{
"id": "instantiation-button-query-param",
"type": "InstantiationButton",
"textResourceBindings": {
"title": "Start instans"
},
"mapping": {
"JobTitle": "PrefilledJobTitle"
}
}
```

### 3. (Optional but highly recommended) validate query parameter values

To validate query parameter values, implement in your /logic folder.
Here is barebones example:

```c#
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Altinn.App.Core.Features;

namespace Altinn.App.AppLogic.DataProcessing
{
public class ValidateQueryParamPrefill : IValidateQueryParamPrefill
{
public async Task PrefillFromQueryParamsIsValid(Dictionary<string, string> prefill)
{
// For example, only "Developer", "Manager", or "Tester" are allowed for JobTitle
if (prefill.TryGetValue("JobTitle", out var jobTitle))
{
var allowedJobTitles = new HashSet<string> { "Developer", "Manager", "Tester" };
if (!allowedJobTitles.Contains(jobTitle))
{
throw new Exception($"Invalid JobTitle '{jobTitle}'.");
}
}

// No issues found
await Task.CompletedTask;
}
}
}
```
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
---
title: Forhåndsutfylling av data basert på spørringsparametere
linktitle: Spørringsparametere
description: Hvordan konfigurere prefyll for en app basert på spørringsparametere.
toc: false
weight: 400
---

Altinn-apper støtter prefyll basert på spørringsparametere.

Dette gjør det mulig for brukere å klikke på en lenke som https://ttd.apps.tt02.altinn.no/ttd/stateless-app/set-query-params?jobTitle=designer,
og få ordet 'designer' forhåndsutfylt i et datamodellfelt.

Det er imidlertid noen viktige forbehold knyttet til sikkerhet når du bruker denne tilnærmingen.

For det første kan prefyll med spørringsparametere kun brukes i en stateless-oppgave.
Hvis vi ikke hadde dette kravet, ville det vært mulig for en angriper å endre verdien i parameteren og få den verdien til å dukke opp direkte i mottakerens Altinn-innboks.

Ved å gå via en stateless-oppgave sikrer vi at dataene blir vist til brukeren før instansiering, slik at brukeren fortsatt har kontroll over hvilke data som lagres.

For det andre anbefaler vi på det sterkeste at du inspiserer verdien av spørringsparametere i applikasjonen din. På denne måten sikrer du at kun gyldige data kan forhåndsutfylles, slik at en angriper ikke kan sende noen en lenke som:

https%3A%2F%2Fttd.apps.tt02.altinn.no%2Fttd%2Fstateless-app%2Fset-query-params%3FjobTitle%3DIm%20a%20scammer

og få teksten "Im a scammer" til å vises i applikasjonen din.

## Hvordan konfigurere prefyll basert på spørringsparametere

### 1. Konfigurer <stateless_datamodel>.prefill.json

I din models-mappe, opprett en fil kalt <stateless_datamodel>.prefill.json (hvis navnet på modellen din er tax_return, skal filen hete tax_return.prefill.json).

Example:

```json
{
"$schema": "https://altinncdn.no/schemas/json/prefill/prefill.schema.v1.json",
"QueryParameters": {
"jobTitle": "JobTitle"
}
}

Dette krever at du har et felt kalt JobTitle i datamodellen din, og lar deg forhåndsutfylle dette feltet med en lenke som:

https://ttd.apps.tt02.altinn.no/ttd/stateless-app/set-query-params?jobTitle=designer

Viktig merknad: lenken for prefyll fungerer kun på stien :org/:app/set-query-params, som i eksempelet ovenfor.

Legg også merke til at kun spørringsparametere som er definert i <stateless_datamodel>.prefill.json vil fungere. Hvis du prøver å lenke til https://ttd.apps.tt02.altinn.no/ttd/stateless-app/set-query-params?somethingelse=designer, vil du få en feil.

### 2. Konfigurer InstantiationProcessor og InstantiationButton
For å lagre verdien fra spørringsparameteren når du instansierer fra stateless-oppgaven, må du implementere en InstantiationProcessor.

Her lagrer du den forhåndsutfylte verdien fra stateless-oppgaven inn i stateful-oppgaven din.

I eksempelet under overfører vi verdien av JobTitle fra stateless-oppgaven til en verdi kalt PrefilledJobTitle i stateful-oppgaven.
```c#
namespace Altinn.App.AppLogic.DataProcessing
{
/// <summary>
/// Represents a business logic class responsible for running logic related to instantiation.
/// </summary>
public class InstantiationProcessor: IInstantiationProcessor
{


public async Task DataCreation(Instance instance, object data, Dictionary<string, string> prefill)
{
if (data.GetType() == typeof(Skjema))
{
if (prefill.ContainsKey("JobTitle"))
{
skjema.PrefilledJobTitle = prefill["JobTitle"];
}
}
await Task.CompletedTask;
}
}
```

Du må også konfigurere en InstantiationButton i layouten din med følgende mapping:

```json
{
"id": "instantiation-button-query-param",
"type": "InstantiationButton",
"textResourceBindings": {
"title": "Start instans"
},
"mapping": {
"JobTitle": "PrefilledJobTitle"
}
}
```

### 3. (Valgfritt, men sterkt anbefalt) valider verdier for spørringsparametere

For å validere spørringsparametere, implementer i /logic-mappen din. Her er et enkelt eksempel:

```c#
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Altinn.App.Core.Features;

namespace Altinn.App.AppLogic.DataProcessing
{
public class ValidateQueryParamPrefill : IValidateQueryParamPrefill
{
public async Task PrefillFromQueryParamsIsValid(Dictionary<string, string> prefill)
{
// For example, only "Developer", "Manager", or "Tester" are allowed for JobTitle
if (prefill.TryGetValue("JobTitle", out var jobTitle))
{
var allowedJobTitles = new HashSet<string> { "Developer", "Manager", "Tester" };
if (!allowedJobTitles.Contains(jobTitle))
{
throw new Exception($"Invalid JobTitle '{jobTitle}'.");
}
}

// No issues found
await Task.CompletedTask;
}
}
}
```
2 changes: 2 additions & 0 deletions content/altinn-studio/reference/data/prefill/_index.en.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ Instantiation will fail if you attempt to prefill ER-data, but do not have an or
- **UserProfile** here you enter fields from the data model that are to be prefilled with data from the users profile in Altinn.
Note that it is the logged in user who instantiates the app the data is collected for.

- **QueryParameters** here you can define fields from the datamodel that can be prefilled based on query parameters from the url. Note that this requires custom setup to work, see instructions [here](../../../guides/development/prefill/config/).

## Available prefill values

The JSON-schema definition of the prefill file is also available [here](https://altinncdn.no/schemas/json/prefill/prefill.schema.v1.json).
Expand Down