Authentication/businessnxtapi/authenticationsectionAuthentication to Business NXT API via Visma Connect involves multi-tenant identity providers. Requires creating an app in Visma Developer Portal.2024-09-24T15:57:29+02:00
# Authentication
Authentication to Business NXT API via Visma Connect involves multi-tenant identity providers. Requires creating an app in Visma Developer Portal.
Authentication to Business NXT API is done through Visma Connect. Visma Connect is a multi-tenant identity provider. Tenants are organizations (businesses) that provide an API-context. A given user may have access to multiple tenants and will choose which to connect to your application upon each single sign-on flow.
> [!TIP]
> You'll need to create an application in the Visma Developer Portal, available at , before getting started.
> [!TIP]
> To learn more about this process see this document . Please explore Visma Developer Portal documentation.
## Endpoints
Visma Connect endpoint details:
| Endpoint | URL |
| -------- | --- |
| Discovery | |
| Authorization | |
| Token | |
| Userinfo | |
| Endsession | |
## Visma Connect Token
Your application requests specific permission scopes and is granted an access token upon a user's approval.
There are two scenarious that are supported by Visma Connect:
- Interactive authentication of users, that must provide their credentials in a login form. That requires the authentication flow to use the *Authorization Code with PKCE* grant type.
- Authentication of a service, using a client ID and a client secret. That requires the authentication flow to use the *Client credentials* grant type.
Once the authentication process has completed successfully, you can make API calls by providing the valid access token with each API request using the `authorization` header.
## Visma Connect Webhooks
Rather than authenticating yourself against connect, your application will have to validate that the webhooks comes from Visma Connect. You will have to make a public endpoint that can take a POST from Visma Connect. The validation
Understanding OAuth/businessnxtapi/authentication/oauthpageUnderstanding OAuth2 for Visma API integration, including roles, tokens, scopes, grants, and necessary endpoints for secure resource access.2024-09-24T15:57:29+02:00
# Understanding OAuth
Understanding OAuth2 for Visma API integration, including roles, tokens, scopes, grants, and necessary endpoints for secure resource access.
Access to resouces and APIs in Visma is done through Visma Connect. This is an identity provider. The OAuth2 flow is used to authorize users and services to access the desired resources. You need to know the basics of OAuth in order to understand the authorization process and build your integration with Business NXT.
## What is OAuth2?
OAuth is a standard that allows websites or applications to access, on behalf of an user, resources hosted by other apps (servers). The term OAuth stands for "Open Autorization" and the number 2 refers to the 2.0 version of the standard. The standard allows users to grant client applications consented access to what resources they can access without sharing credentials.
OAuth is not intended to authenticate users (that is verifying that a user is who he claims to be) but to authorize them. That means granting access to resources such as remove APIs.
> [!NOTE]
>
> You can read more about OAuth2 here:
>
> - [OAuth 2.0](https://oauth.net/2/)
> - [What is OAuth 2.0?](https://auth0.com/intro-to-iam/what-is-oauth-2/)
## Roles
The OAuth standard defines a set of roles that represent components of an authorization system. These roles/components are the following:
- **Resource owner**: the system/user that owns a resource and that grants access to that resouce.
- **Client**: the system that requires access to a protected resource.
- **Authorization server**: a server that receives requests from the **Client** for access tokens and issues them after authenticating the **Resource owner** and obtaining consent for the requested access.
- **Resource server**: a server that protects the resources and receives access requests to them from the **Client**.
The interactions between these componets are illustrated in the following image:

## Access tokens
In order to grant access to resources, OAuth2 uses *access tokens*. An access token is basically a document that describes the authorization to access resouces on behalf of a user. The OAuth2 standard does not define a format. The JSON Web Token (JWT) is the widely used format. Visma Connect uses the JWT format for access tokens.
The JWT token is a base64 encoded document. Typically, you should not be concerned with the content of a token. For debugging purposes, however, you can use the [jwt.io](https://jwt.io) website to inspect the content of a JWT access token. Its payload looks as follows:
```json
{
"nbf": 1648744531,
"exp": 1648748131,
"iss": "https://connect.visma.com",
"aud": "https://business.visma.net/api/graphql",
"client_id": "...",
"sub": "42fd1681...",
"auth_time": 1648744530,
"idp": "Visma Connect",
"llt": 1648641021,
"acr": "3",
"jti": "0271242A...",
"sid": "203b1c01...",
"iat": 1648744531,
"scope": [
"openid",
"email",
"profile",
"business-graphql-api:access-group-based"
],
"amr": [
"pwd",
"otp"
]
}
```
An access token contains information such as:
- issuer (`iss`)
- the destination of the token (`aud`)
- issued time (`iat`)
- expiration time (`exp`)
- subject - whom the token refers to (`sub`)
- scopes - list of granted scopes (`scope`)
The one what you need to know about are the scopes.
>[!NOTE]
>
> You can read more about access tokens here:
>
> - [OpenID Connect specifications](https://openid.net/specs/openid-connect-core-1_0.html)
> - [Introduction to JSON Web Tokens](https://jwt.io/introduction)
## ID token vs Access token vs Refresh token
When you read about OAuth tokens, there are three terms that come up and can be confusing:
- **ID token**: this is a document that proves that a user has been authenticated and can carry information about the user. The ID token was introduced by OpenID Connect (OIDC) which is an open standard for authentication used by many identity providers, including Google, Facebook, and Apple.
- **Access token**: this is a document that carries information about the authorization to a resource.
- **Refresh token**: this is a special kind of token that is used to obtain additional access tokens. An ID or access token is valid for a specific period of time (like 30 seconds or 60 minutes for instance). A refresh token is used to retrieve new access tokens without the need to re-authenticate the user. A refresh token is requested alongside the initial request for an ID and access token and must be stored (securely) by the application.
>[!NOTE]
>
> You can read more about these kinds of tokens here:
>
> - [ID Tokens vs Access Tokens](https://oauth.net/id-tokens-vs-access-tokens/)
> - [ID Token and Access Token: What's the Difference?](https://auth0.com/blog/id-token-access-token-what-is-the-difference/)
> - [What Are Refresh Tokens and How to Use Them Securely](https://auth0.com/blog/refresh-tokens-what-are-they-and-when-to-use-them/)
## Scopes
Scopes are reasons for which access to a resource is requested. For instance, there can be a scope for reading data, one for inserting and updating, one for deleting. Scopes depend on the resource server.
>[!TIP]
>
> Business NXT defines a single scope, called `business-graphql-api:access-group-based` for web applications and `business-graphql-service-api:access-group-based` for services.
>
> However, in case of a web application, when you register it with Visma Developer Portal, you need to set the following scopes: `email`, `openid`, and `profile`. Upon reqesting an access token, you need to specify the following scopes: `business-graphql-api:access-group-based` `openid` `email`. These extra scopes are not necessary for services.
>
> Read more about this here:
>
> [Web applications registration](./web/setup_web.md) and [GraphQL API Integration](./web/integrations_web.md).
>
> [Services registration](/businessnxtapi/authentication/service/application_registration/) and [GraphQL API Integration](./service/integrations_service.md).
## Grants
Grants are steps a client performs to get authorization for accessing a resource. The authorization framework defines several grant types for different scenarios:
- Authorization Code
- Implicit
- Authorization Code with Proof Key for Code Exchange (PKCE)
- Resource Owner Credentials
- Client Credentials
- Device Authorization Flow
- Refresh Token Grant
The grant type used for Business NXT is **Authorization Code with PKCE**. This flow consists of the following steps:
1. The user clicks a login button/link in the application.
2. The application creates a random `code_verifier` and from it generates a `code_challenge`.
3. The application makes an authorization request to the `/authorize` endpoint of the authorization server with the generated `code_challenge`.
4. The authorization server redirects the user to the login and authorization page.
5. The user authenticates (using a selected option) and may be displayed a consent page that lists the permissions the application is requesting.
6. The authorization server stores the `code_challenge` and redirects the user back to the application, providing a one-time-use `authorization_code`.
7. The application sends the `code_verifier` and the `authorization_code` to the `/token` endpoint of the authorization server.
8. The authorization server verifies the `code_challenge` and the `code_verifier`.
9. The authorization server returns an *ID token*, an *access token*, and optionally, a *refresh token*.
10. The application uses the access token to call an API.
11. The API responds with the requested data.

>[!NOTE]
>
> You can read more about grants here:
>
> - [Authentication and Authorization Flows](https://auth0.com/docs/get-started/authentication-and-authorization-flow)
> - [OAuth Grant Types: Explained](https://frontegg.com/blog/oauth-grant-types)
> - [OpenID Connect & OAuth 2.0 API](https://developer.okta.com/docs/reference/api/oidc/)
## Endpoints and redirect URLs
Endpoints and a redirect URL are key parts of the OAuth flow.
An authorization server exposes several endpoints that are used at various steps in the authorization flows:
| Endpoint | Description |
| -------- | ----------- |
| `/authorize` | Interact with the resource owner and obtain an authorization grant. |
| `/token` | Obtain an access token and/or an ID token by providing an authorization grant or refresh token. |
| `/endsession` | End the session associated with the given ID token. |
| `/userinfo` | Return claims about the authenticated end user. |
>[!TIP]
>
> To get the URLs of the Visma Connect endpoints check [this page](/businessnxtapi/authentication/).
A *redirect URL* is a URL to which the authorization server will redirect the user after the user successfully authorizes an application. A redirect URL contains sensitive information. The authorization server must not redirect the user to arbitrary (unsecure) locations. In order to ensure the user is redirected to an apppropriate location, the developers of the application are required to register one or more redirect URL when they create the application.
>[!TIP]
>
> Visma Developer Portal requires you to provide a redirect URL when you register your application in the system. You can read more about that here: [Web Application registration](/businessnxtapi/authentication/web/).
Services/businessnxtapi/authentication/servicesectionGuide for integrating services with Business NXT via GraphQL, including registration, authentication, and setup instructions on Visma Developer Portal.2024-09-24T15:57:29+02:00
# Services
Guide for integrating services with Business NXT via GraphQL, including registration, authentication, and setup instructions on Visma Developer Portal.
In order to integrate with Business NXT you must register an application in the Visma Developer Portal and add an integration to Business NXT GraphQL. Here, you will learn how to do this.
Services are application do not require user interaction. They enable a machine-to-machine integration. If you do not require user interaction, this is the type of application you should use.
To integrate your service with Business NXT using GraphQL, you must do the following:
1. Register your service with the Visma Developer Portal.
2. Register an integration with the Business NXT GraphQL API.
3. Register a user to impersonate your service in Business NXT.
4. Perform authentication with the *client credentials* grant type.
5. Use the URL for queries.
In this section, we discuss each of these points.
>[!TIP]
>
> If you are not familiar with the OAuth authorization flows, we recommend that you first read carefully the page [Understanding OAuth](../oauth.md) to familiarize yourself with concepts such as authentication and authorization, access tokens, scopes, grants, endpoints and redirect URLs. You need to have a basic understanding of these concepts in order to properly register your application and setup an integration with Business NXT GraphQL Service API.Application registration/businessnxtapi/authentication/service/application_registrationpageGuidance on registering a service application in the Visma Developer Portal, covering steps, approval, credentials, and local development setup.2024-09-24T15:57:29+02:00
# Application registration
Guidance on registering a service application in the Visma Developer Portal, covering steps, approval, credentials, and local development setup.
Registering a service application in the Visma Developer Portal is very similar to registering a web application, although some options are different.
You must follow these steps:
1. Logon to [Visma Developer Portal](https://oauth.developers.visma.com).
2. From the menu, select My **Applications** and then press the **Add applications** button.

3. Select the **Service** application type.

4. Fill in the registration form. You must select an application name, a unique client identifier, and a description of your application. When completed, you must press the **Save as draft** button and then **Send for approval**.

5. Your application must be approve by Visma before you can start using it. Before approval, it will display the *Pending approval* status.
> [!WARNING]
>
> Because the **client ID** needs to be stored in the **User** table (see [User setup](vbnxt_service.md) page) and there is a limitation of 24 characters for names in this table, please make sure the value for the **client ID** does not exceed this limit.
After the approval process complete, you can add integrations to your application. See [GraphQL API integration](integrations_service.md) to learn how to do that.
## Application Credentials
In order to perform the authentication flow using the client credentials grant type, you must have both a *client identifier* and a *client secret*. Client secrets can be generated (and deleted) from the **Credentials** tab in Visma Developer Portal.

> [!NOTE]
>
> A secret is only visible when it is generated after which you can no longer read it. You must copy and preserve it in a secure place.
## Local App Development
For the development of your application on local machines, you must register a local URL for login and redirect. The use of `localhost` is not supported in the Visma Developer Portal but `app.local` can be used instead. Assuming your application runs locally on the 12345 port, use the following configuration:
```
Initiate Login URI: https://app.local:12345/
Frontchannel Logout URI: https://app.local:12345/logout
Redirect URIs: https://app.local:12345/signin-oidc
```GraphQL API integration/businessnxtapi/authentication/service/integrations_servicepageGuide for integrating Visma's Business NXT GraphQL API, including selecting APIs, confirming integrations, and initiating OAuth flow post-approval.2024-09-24T15:57:29+02:00
# GraphQL API integration
Guide for integrating Visma's Business NXT GraphQL API, including selecting APIs, confirming integrations, and initiating OAuth flow post-approval.
After the approval of the registration of your service application, you can add integrations to Visma APIs. To integrate with Business NXT GraphQL API do the following:
1. Select your application from the **My Applications** main tab and go to **Integrations**.
2. Press the **New integration** button.
3. Search and select the **Business NXT GraphQL Service API** in the combo with available APIs and press **Continue**.

4. Select the `business-graphql-service-api:access-group-based` and press **Continue**.

5. Review the selection and confirm the integration by pressing the **Confirm Integration** button.

6. Wait for the integration to be approved by Visma. Once approved, the integrations become active.

Once your application is integrated with **Business NXT GraphQL Service API**, you can initiate the OAuth flow and create tokens. However, access to a company requires additional steps that must be performed in the Business NXT application. This is described next.
User Setup/businessnxtapi/authentication/service/user_setuppageAPI documentation for setting up a new user in Business NXT, including creating layouts and assigning application access roles.2024-09-24T15:57:29+02:00
# User Setup
API documentation for setting up a new user in Business NXT, including creating layouts and assigning application access roles.
In order to perform operations in company in Business NXT using GraphQL from a service (using an access token with *client credentials* grant type), you must perform in Business NXT the registration steps described below.
> [!TIP]
>
> In order to be able to add users to the `User` table, your Visma.net user must have the `Application access` and `System supervisor` roles assign in `Visma.net Admin`.
>
> 
The setup consists of the following steps:
1. Create a new layout and add the **User** table.

2. Unhide the **Connect Application** column from this table.

3. Add a new user having the same name as the client identifier (*client_id*) of your newly registered service. You must check the *Connect application* checkbox before saving the new user.

4. Either create a new layout or use the same layout and add the **Connect Application Access** table.

5. Add the newly created user to this table. Select the company to which you want to grant access to your service by entering its number in the **Column no.** field.

6. Select the desired access group that defines the access rights for this company.

7. Save the changes to the table.
You must repeat the steps 5 and 6 for each company to which you want to grant access for your service.
Examples for setting up authorization/businessnxtapi/authentication/service/examplessectionHere you can find some examples for how to set up authorization.2024-09-24T15:57:29+02:00
# Examples for setting up authorization
Here you can find some examples for how to set up authorization.
Click the links below to look at examples for how to set up authorization for either Postman or Insomnia.
Postman/businessnxtapi/authentication/service/examples/postmanpageSet up OAuth2.0 with Client Credentials grant type in Postman for authenticating your service via Visma Connect.2024-09-24T15:57:29+02:00
# Postman
Set up OAuth2.0 with Client Credentials grant type in Postman for authenticating your service via Visma Connect.
In Postman, you can set the authorization method and details either per request or collection. To authenticate your service, perform the following setup:
1. Choose the **OAuth2.0** authorization type.
2. Select the **Client credentials** grant type.
3. Use the following access token URL: .
4. Fill in the client ID and the client secret.
5. Enter the scope `business-graphql-service-api:access-group-based`.
6. Select **Send as Basic Auth header** option for *Client Authentication*.
These settings are shown in the following image:

> [!TIP]
>
> You can learn more about about authentication in Postman from its official documentation. See [Authorizing requests](https://learning.postman.com/docs/sending-requests/authorization/).
Insomnia/businessnxtapi/authentication/service/examples/insomniapageGuide to setting up OAuth2 Client Credentials in Insomnia for authenticating your service.2024-09-24T15:57:29+02:00
# Insomnia
Guide to setting up OAuth2 Client Credentials in Insomnia for authenticating your service.
In Insomnia, you can set the authorization method and details per request. To authenticate your service, perform the following setup:
1. Choose the **OAuth2** authorization type.
2. Select the **Client Credentials** grant type.
3. Use the following access token URL: .
4. Fill in the client ID and the client secret.
5. Enter the scope `business-graphql-service-api:access-group-based`.
6. Select **As Basic Auth Header** option for *Credentials* combo.
These settings are shown in the following image:

> [!TIP]
>
> You can read more about authentication in Insomnia [here](https://docs.insomnia.rest/insomnia/authentication).
Web applications/businessnxtapi/authentication/websectionLearn how to set up web applications for integrating with Business NXT, including OAuth authorization essentials.2024-09-24T15:57:29+02:00
# Web applications
Learn how to set up web applications for integrating with Business NXT, including OAuth authorization essentials.
For integrating with Business NXT, you can choose one of these two type of applications:
- Service: suitable for web services that require a machine-to-machine integration (with no user interation).
- Web: suitable for web applications that require user interaction.
In this section, you will learn about the setup required for web applications.
> [!TIP]
>
> If you are not familiar with the OAuth authorization flows, we recommend that you first read carefully the page [Understanding OAuth](../oauth.md) to familiarize yourself with concepts such as authentication and authorization, access tokens, scopes, grants, endpoints and redirect URLs. You need to have a basic understanding of these concepts in order to properly register your application and setup an integration with Business NXT GraphQL API.
Application registration/businessnxtapi/authentication/web/setup_webpageLearn how to register a web application on Visma Developer Portal to integrate with Business NXT GraphQL API.2024-09-24T15:57:29+02:00
# Application registration
Learn how to register a web application on Visma Developer Portal to integrate with Business NXT GraphQL API.
In order to integrate with Business NXT you must register an application in the Visma Developer Portal and add an integration to Business NXT GraphQL. Here, you will learn how to do this. This section describes how to register a web application.
> [TIP]
>
> If you are not familiar with the OAuth authorization flows, we recommend that you first read carefully the page [Understanding OAuth](../oauth.md) to familiarize yourself with concepts such as authentication and authorization, access tokens, scopes, grants, endpoints and redirect URLs. You need to have a basic understanding of these concepts in order to properly register your application and setup an integration with Business NXT GraphQL API.
You must follow these steps:
1. Logon to [Visma Developer Portal](https://oauth.developers.visma.com).
2. From the menu, select My **Applications** and then press the **Add applications** button.

3. Select the **Web** application type.

4. Fill in the registration form. You must select an application name, a unique client identifier, a description of your application, as well as URLs for the authentication workflow. From this form, you can customize application policies and branding. When completed, you must press the **Save as draft** button and then **Send for approval**.

5. Your application must be approve by Visma before you can start using it. Before approval, it will display the *Pending approval* status.

After the approval process complete, you can add integrations to your application. See [GraphQL API integration](integrations_web.md) to learn how to do that.
## Application Credentials
If you plan to use an web application with client credentials (performing the OAuth flow using the client credentials grant type), this requires both a *client ID* and a *client secret*. In this case, you also need to generate a client secret.
Secrets can be generated and deleted from the **Credentials** tab in Visma Developer Portal.

> [!NOTE]
>
> A secret is only visible when it is generated after which you can no longer read it. You must copy and preserve it in a secure place.
## Local App Development
For the development of your application on local machines, you must register a local URL for login and redirect. The use of `localhost` is not supported in the Visma Developer Portal but `app.local` can be used instead. Assuming your application runs locally on the 12345 port, use the following configuration:
```
Initiate Login URI: https://app.local:12345/
Frontchannel Logout URI: https://app.local:12345/logout
Redirect URIs: https://app.local:12345/signin-oidc
```GraphQL API integration/businessnxtapi/authentication/web/integrations_webpageStep-by-step guide to integrate a web application with Business NXT GraphQL API and initiate the OAuth flow for creating tokens2024-09-24T15:57:29+02:00
# GraphQL API integration
Step-by-step guide to integrate a web application with Business NXT GraphQL API and initiate the OAuth flow for creating tokens
After the approval of the registration of your web application, you can add integrations to Visma APIs. To integrate with Business NXT GraphQL API do the following:
1. Select your application from the **My Applications** main tab and go to **Integrations**.

2. Press the **New integration** button.
3. Search and select the **Business NXT Graphql API** in the combo with available APIs and press **Continue**.

If you plan to use the client credentials grant type, then you need search for **Business NXT GraphQL API** in the combo with available APIs and press **Continue**.

4. Select the `business-graphql-api:access-group-based` scope (or `business-graphql-service-api:access-group-based` if you seleced **Business NXT Graphql Service API** in the previous step) and press **Continue**.

5. Review the selection and confirm the integration by pressing the **Confirm Integration** button.

6. Wait for the integration to be approved by Visma.

Once approved, the integrations become active.

Once your application is integrated with **Business NXT Graphql API**, you can initiate the OAuth flow and create tokens.
The minimum required claims for a valid OAuth 2.0 JWT token are:
```text
Default OAuth 2.0 Claim required:
sub
Scope Claims required:
email
openid
business-graphql-api:access-group-based
```
Company access is determined by the corresponding user for whom the OAuth JWT token was created. The rights for the user are managed in Visma.net.Setting up user nightly jobs with unattended access/businessnxtapi/authentication/web/unattendedaccesspageGuide to setting up unattended nightly jobs using OIDC refresh tokens for data import from Business NXT in web applications.2024-09-24T15:57:29+02:00
# Setting up user nightly jobs with unattended access
Guide to setting up unattended nightly jobs using OIDC refresh tokens for data import from Business NXT in web applications.
When using a web application, setting up a nightly job for importing data from Business NXT can be done with the help of OIDC *refresh tokens*.
> [!TIP]
>
> For this kind of scenario, the best approach is to use a service application. To learn more about this see [Services](/businessnxtapi/authentication/service/).
Only web applications in the Visma Developer Portal can have a refresh token and they require an OIDC-enabled backend to store the refresh token. You will also need to include the `offline_access` scope for the application.
After checking offline access, you will gain access to more settings related to the refresh token:

You can create a **job user** in Visma.net and assign its correct privileges to certain companies and company groups. It can even be your currently logged in user under which the job will run. After loging in with the user under which the unattended job will run, you will need to store this refresh token to refresh tokens and use it after the regular tokens expire, without requiring the user (that the nightly job will run under) to login again.
> [!TIP]
>
> See more information about refresh tokens in the [Visma Developer Portal documentation](https://oauth.developers.visma.com/service-registry/documentation/authentication#offlineAccess).
Examples for setting up authorization/businessnxtapi/authentication/web/examplessectionHere you can find some examples for how to set up authorization.2024-09-24T15:57:29+02:00
# Examples for setting up authorization
Here you can find some examples for how to set up authorization.
Click the links below to look at examples for how to set up authorization for either .NET, Postman, or Insomnia.
.NET Code Sample/businessnxtapi/authentication/web/examples/codepage.NET sample app for integrating with Business NXT using OAuth flow. Clone or create ASP.NET app, setup configs, run to authenticate.2024-09-24T15:57:29+02:00
# .NET Code Sample
.NET sample app for integrating with Business NXT using OAuth flow. Clone or create ASP.NET app, setup configs, run to authenticate.
If you're using .NET (3.1/5/6) to build your application that integrates with Business NXT, you can set it up as described below to perform the oauth flow.
> [!NOTE]
>
> The code for the application described here is available on GitHub at [GraphQLSamples/MvcCode](https://github.com/Visma-Business/GraphQLSamples/tree/main/MvcCode).
>
> This application is a modified version of the [MvcCode sample](https://github.com/IdentityServer/IdentityServer4/tree/main/samples/Clients/src/MvcCode) from the [IdentityServer](https://github.com/IdentityServer) project.
## Getting started
You can either clone the MvcCode sample repository or create an Asp.Net application from scratch. The sample application described here has the following structure:

## Application setup
The `Program.cs` source file has the following content:
```
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
namespace MvcCode
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup();
});
}
}
```
The `Setup.cs` source file contains the following:
```
using IdentityModel;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Net.Http;
using IdentityModel.Client;
using Microsoft.IdentityModel.Logging;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
namespace MvcCode
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
JwtSecurityTokenHandler.DefaultMapInboundClaims = false;
services.AddControllersWithViews();
services.AddHttpClient();
services.AddOptions();
services.Configure(Configuration);
services.AddSingleton(r =>
{
var factory = r.GetRequiredService();
return new DiscoveryCache(Configuration.GetValue("Authority"),
() => factory.CreateClient());
});
services.AddAuthentication(options =>
{
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = "oidc";
})
.AddCookie(options =>
{
options.Cookie.Name = "mvccode";
})
.AddOpenIdConnect("oidc", options =>
{
options.Events.OnTokenResponseReceived = (tokenResponse) =>
{
var accessToken = tokenResponse.TokenEndpointResponse.AccessToken;
return Task.CompletedTask;
};
options.Events.OnRemoteFailure = (err) =>
{
return Task.CompletedTask;
};
options.Events.OnMessageReceived = (msg) =>
{
return Task.CompletedTask;
};
options.Authority = Configuration.GetValue("Authority");
options.RequireHttpsMetadata = false;
options.ClientId = Configuration.GetValue("ClientId");
options.ClientSecret = Configuration.GetValue("ClientSecret");
options.ResponseType = "code id_token";
options.UsePkce = true;
options.Scope.Clear();
options.Scope.Add("openid");
options.Scope.Add("profile");
options.Scope.Add("email");
options.Scope.Add("business-graphql-api:access-group-based");
options.Scope.Add("offline_access");
options.GetClaimsFromUserInfoEndpoint = true;
options.SaveTokens = true;
options.TokenValidationParameters = new TokenValidationParameters
{
NameClaimType = JwtClaimTypes.Name,
RoleClaimType = JwtClaimTypes.Role,
};
});
}
public void Configure(IApplicationBuilder app)
{
IdentityModelEventSource.ShowPII = true;
app.UseDeveloperExceptionPage();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapDefaultControllerRoute()
.RequireAuthorization();
});
}
}
}
```
From this snippet, you should notice the following:
- Authority, client ID, and client secret are read from the application settings.
- The response type is `code id_token`.
- The requested scopes are `openid`, `profile`, `email`, `business-graphql-api:access-group-based`, and `offline_access`. The latter is only needed when offline access is required.
## Application Settings
The JSON file with the application settings (`appsettings.json`) looks as follows:
```
{
"ClientId": "...",
"ClientSecret": "...",
"Authority": "https://connect.visma.com",
"SampleApi": "https://localhost:5005/"
}
```
The client ID is the one you specified when you registered your application with the Visma Developer Portal. The client secret is a value generated in the **Credentials** tab of the application propertys in the Visma Developer Portal.
> [!NOTE]
>
> Make sure you do not upload the content of this file to a public repository such as on GitHub.
The `AppSettings.cs` file contains the following class definition used to help with accessing the settings:
```
namespace MvcCode
{
public class AppSettings
{
public string ClientId { get; set; }
public string ClientSecret { get; set; }
public string Authority { get; set; }
public string SampleApi { get; set; }
}
}
```
## Controllers
The `HomeController` class is implemented as follows:
```
using System;
using System.Globalization;
using System.Net.Http;
using System.Threading.Tasks;
using IdentityModel.Client;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Newtonsoft.Json.Linq;
namespace MvcCode.Controllers
{
public class HomeController : Controller
{
private readonly IHttpClientFactory _httpClientFactory;
private readonly IDiscoveryCache _discoveryCache;
private readonly AppSettings _authSettings;
public HomeController(IHttpClientFactory httpClientFactory, IDiscoveryCache discoveryCache, IOptions authSettings)
{
_httpClientFactory = httpClientFactory;
_discoveryCache = discoveryCache;
_authSettings = authSettings.Value;
}
[AllowAnonymous]
public IActionResult Index() => View();
public IActionResult Secure() => View();
public IActionResult Logout() => SignOut("oidc");
public async Task CallApi()
{
var token = await HttpContext.GetTokenAsync("access_token");
var client = _httpClientFactory.CreateClient();
client.SetBearerToken(token);
var response = await client.GetStringAsync(_authSettings.SampleApi + "identity");
ViewBag.Json = JArray.Parse(response).ToString();
return View();
}
public async Task RenewTokens()
{
var disco = await _discoveryCache.GetAsync();
if (disco.IsError) throw new Exception(disco.Error);
var rt = await HttpContext.GetTokenAsync("refresh_token");
var tokenClient = _httpClientFactory.CreateClient();
var tokenResult = await tokenClient.RequestRefreshTokenAsync(new RefreshTokenRequest
{
Address = disco.TokenEndpoint,
ClientId = _authSettings.ClientId,
ClientSecret = _authSettings.ClientSecret,
RefreshToken = rt
});
if (!tokenResult.IsError)
{
var oldIdToken = await HttpContext.GetTokenAsync("id_token");
var newAccessToken = tokenResult.AccessToken;
var newRefreshToken = tokenResult.RefreshToken;
var expiresAt = DateTime.UtcNow + TimeSpan.FromSeconds(tokenResult.ExpiresIn);
var info = await HttpContext.AuthenticateAsync("Cookies");
info.Properties.UpdateTokenValue("refresh_token", newRefreshToken);
info.Properties.UpdateTokenValue("access_token", newAccessToken);
info.Properties.UpdateTokenValue("expires_at", expiresAt.ToString("o", CultureInfo.InvariantCulture));
await HttpContext.SignInAsync("Cookies", info.Principal, info.Properties);
return Redirect("~/Home/Secure");
}
ViewData["Error"] = tokenResult.Error;
return View("Error");
}
}
}
```
In this snippet:
- `CallApi()` is a function that makes an HTTP request to (or whatever base URL is specified in the `SampleApi` property in the application settings).
- `RenewTokens()` is a function that runs the oauth flow to refesh the access token.
## Views
The view files are as follows:
- `Index.cshtml`
```
@{
ViewData["Title"] = "Home Page";
}
```
## Running the Application
When you run the application (for instance on port 44303 at or ) you get the following welcome page:

When you click on **Secure** you are redirected to Visma Connect for authentication:

After completing the authentication, the **Secure** page lists your user identity claims:

You can also find, on the same page, the authentication properties, such as the ID token, the access token, and the refresh token:

Postman/businessnxtapi/authentication/web/examples/postmanpageConfigure Postman authorization using Bearer tokens per request or collection. Learn more in the official Postman documentation.2024-09-24T15:57:29+02:00
# Postman
Configure Postman authorization using Bearer tokens per request or collection. Learn more in the official Postman documentation.
In Postman, you can set the authorization method and details either per request or collection.
You must use the **Bearer token** authorization type and specify an access token. You can fetch an access token in different ways. A possible way is using the .NET sample application described [here](code.md).

> [!TIP]
>
> You can learn more about about authentication in Postman from its official documentation. See [Authorizing requests](https://learning.postman.com/docs/sending-requests/authorization/).
Insomnia/businessnxtapi/authentication/web/examples/insomniapageSet up Insomnia with Bearer Token authorization, fetch access tokens via .NET application, and learn more about authentication techniques.2024-09-24T15:57:29+02:00
# Insomnia
Set up Insomnia with Bearer Token authorization, fetch access tokens via .NET application, and learn more about authentication techniques.
In Insomnia, you can set the authorization method and details per request.
You must use the **Bearer Token** authorization type and specify an access token. You can fetch an access token in different ways. A possible way is using the .NET sample application described [here](code.md).

> [!TIP]
>
> You can read more about authentication in Insomnia [here](https://docs.insomnia.rest/insomnia/authentication).