Authentication and authorization
To authenticate, a bearer token needs to be provided as a header in the HTTP request. The bearer token must be obtained from HelseId. We use the token to verify access and to identify who is using the API.
How to obtain and use a Machine to machine HelseId token
A m2m (machine to machine) token is the way an EPJ system will authenticate with the CommunicationParty API. This token contains an Organization number.
Set up a HelseId Client through Selvbetjening
- Read up on how to create a client configuration for your organization in HelseId.
- In production this requires the organzation to delegate access through Altinn.
- In the test environment you can configure which organization you want to represent in the Selvbetjening portal.
- Log on to the Selvbetjening portal
- Select Dine klientsystemer to configure your client systems.
- If your client system is already configured here and it supports API calls, you may add "CommunicationParty REST API" to its supported services.
- Otherwise, add a new client system, set it to support API calls, and add "CommunicationParty REST API" to its supported services.
- Now, select Ta i bruk HelseId from the left menu to create a client configuration for an instance of your system.
- Create a new client configuration (Ny klientkonfigurasjon)
- Choose the client system that you just configured as the Fagsystem.
- Choose CommunicationParty REST API as the service to consume.
- Complete the rest of the wizard to issue and download a JSON Web Key, that will be used later to authenticate.
- It is also possible to upload your own JSON Web Key here, which is a much more secure option than having it issued by us.
Request a token
Now that HelseId knows about your client configuration, your application may request a bearer token from HelseId at any time. This is achieved by posting a request to HelseId's token endpoint. This request must be authenticated by your application by signing a JWT (Json Web Token) with the JWK (Json Web Key) issued in the previous step. This mechanism is called Client assertion.
Example token request (C#, .NET 6+)
- First, find your ClientId, and your JWK. If you downloaded the configuration file from Selvbetjening, open the json file, and find the values of
clientId
andprivateJwk
. - Add the following NuGet packages:
<PackageReference Include="IdentityModel" Version="6.1.0" /> <PackageReference Include="Microsoft.IdentityModel.Tokens" Version="6.30.0" /> <PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="6.30.0" />
- Substitute your clientId and privateJwk into the following example. :
using System.IdentityModel.Tokens.Jwt; using IdentityModel.Client; using Microsoft.IdentityModel.Tokens; const string clientId = "15f46f78-xxxx-xxxx-xxxx-xxxxxxxxxxxx"; // Insert your client id here const string privateJwk = "{\u0022d\u0022:\u0022PXvMfT1d2hNSzpTip.........."; // Insert your private jwk here const string tokenEndpoint = "https://helseid-sts.test.nhn.no/connect/token"; const string scopeName = "nhn:cp-api/access"; ClientCredentialsTokenRequest CreateClientAssertionsRequest() { var request = new ClientCredentialsTokenRequest { ClientId = clientId, Address = tokenEndpoint, Scope = scopeName, GrantType = IdentityModel.OidcConstants.GrantTypes.ClientCredentials, ClientCredentialStyle = ClientCredentialStyle.PostBody, ClientAssertion = new ClientAssertion { Type = IdentityModel.OidcConstants.ClientAssertionTypes.JwtBearer, Value = CreateJwtToken() } }; return request; } string CreateJwtToken() { var tokenIssuedAtEpochTimeSeconds = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); var signingCredentials = new SigningCredentials(new JsonWebKey (privateJwk), SecurityAlgorithms.RsaSha512); var header = new JwtHeader(signingCredentials); var payload = new JwtPayload { [JwtRegisteredClaimNames.Iss] = clientId, [JwtRegisteredClaimNames.Sub] = clientId, [JwtRegisteredClaimNames.Aud] = tokenEndpoint, [JwtRegisteredClaimNames.Exp] = tokenIssuedAtEpochTimeSeconds + 60, [JwtRegisteredClaimNames.Nbf] = tokenIssuedAtEpochTimeSeconds, [JwtRegisteredClaimNames.Iat] = tokenIssuedAtEpochTimeSeconds, [JwtRegisteredClaimNames.Jti] = Guid.NewGuid().ToString("N"), }; var token = new JwtSecurityToken(header, payload); var serializedToken = new JwtSecurityTokenHandler().WriteToken(token); return serializedToken; } ClientCredentialsTokenRequest request = CreateClientAssertionsRequest(); TokenResponse response = await new HttpClient().RequestClientCredentialsTokenAsync(request); if (response.IsError) { Console.WriteLine($"Error: {response.Error} - {response.ErrorDescription}"); } else { Console.WriteLine("Bearer: " + response.AccessToken); }
Use the token
Now that you have the access token, making an authenticated request is as simple as adding the token as a header.
- In C#, it could be done like this:
var cpeHttpClient = new HttpClient { BaseAddress = new Uri("https://cpe.test.grunndata.nhn.no"), }; cpeHttpClient.SetBearerToken(response.AccessToken); // Add the bearer token to all requests made through this HttpClient. var response = await cpeHttpClient.GetAsync("/CommunicationPartyEvents"); response.EnsureSuccessStatusCode(); Console.WriteLine(await response.Content.ReadAsStringAsync());
How to test with Swagger and a bearer token
The user needs to have set up HelseId and generated a bearer token from the private JWK that is supplied from HelseId.
- Open Swagger UI: https://cpe.test.grunndata.nhn.no/swagger/index.html
- Click the Authorize padlock in the top right corner
- Fill in the bearer token