SDK for .NET

Deprecated

The SDK uses the Hybrid Flow. Existing applications can continue to use the Hybrid Flow and the SDK, but new applications should use the Code Flow. For further information see OAuth2.0 & OpenID connect and OAuth2.0 Code Flow with PKCE .NET Sample.

 

Overview

The DATEV Cloud Authentication Library (DCAL) is a framework for authenticating the user and authorizing .NET applications with the DATEV data center to call DATEV APIs.

To authenticate, the end user requires a DATEV authentication medium (SmartLogin, SmartCard, ..).

Terms of a licence

DATEV eG entitles the licensee to use and to duplicate DATEV Cloud Authentication Library and to make it accessible as part of an own program.

Registration at DATEV as a third-party .NET client

The steps to use the DATEV authentication library for .NET applications are:

  • Download the library and use it
  • Register at DATEV as a DATEV client
    • Get a client_id
    • Get a client_secret

To register, please prepare the following information for DATEV:

NameTypeDescription
Third-party web application namestringName of the third-party .NET client in the consent page.
Vendor namestringCompany name of the provider of the third-party .NET client.
List of redirect_URIshttp://localhostThe DATEV authentication library uses fix the redirect URI http://localhost.

You will receive the following parameters for the authorization process from DATEV:

NameTypeDescription
client_idstring (max. 60 characters)The client_id is a unique ID assigned by DATEV for the third party web application.
client_secretstringThe client_secret is received from DATEV at the end of the registration process.

Environments of the DATEV data center

DATEV’s data center offers a „sandbox“-environment as a test environment and a productive environment. Which of the environments is used depends on the addressed URI for the discovery server (authority) and the addressed API.

DATEV Endpoints

NameDescriptionEndpoints
<discoveryServer> (authority)Destination address to ask for further DATEV addresses and start the login processProductive environment:
https://login.datev.de/openid/

Sandbox environment:
https://login.datev.de/openidsandbox/
<resourceServer>Destination address for the application-specific calls of DATEVconnect online (API calls)Productive environment:
https://api.datev.de/

Sandbox environment:
https://sandbox-api.datev.de/

 

Implementation Information

Download and setup

The DCAL .NET library is available for download via NuGet.

  1. Download the Datev.Cloud.Authentication NuGet-package from nugetpackage (self extracting exe)
  2. Integrate the NuGet-package into Visual Studio:
    • In Visual Studio, select the menu item Tools | NuGet Package Manager | Package Manager Settings.
    • Go to Options | NuGet Package Manager | Package Sources and add the local folder containing the NuGet package Datev.Cloud.Authentication as an additional Package Source
    • In Visual Studio, select the menu item Tools | NuGet Package Manager | Manage NuGet Packages
    • Go to NuGet Solution and select the package Datev.Cloud.Authentication. Select the project on the right and install the latest version by clicking the Install button. This adds all required references to the project.

Using the Datev.Cloud.Authentication

3rd-party applications use the NuGet package Datev.Cloud.Authentication with the Datev.Cloud.Authentication.dll dependent on the NuGet package IdentityModel.OidcClient. The NuGet Packet Manager resolves other dependencies automatically. All DLLs must be provided together with the application to the application folder.

Make Datev.Cloud.Authentication types directly usable:

    using Datev.Cloud.Authentication;
                   

Then create ClientOptions:

    var options = new ClientOptions(
                    authority,
                    clientId,
                    clientSecret,
                    clientScopes,
                    clientRedirectPort);
  • authority = Identity provider, either https://login.datev.de/openidsandbox/ or https://login.datev.de/openid/
  • clientId = ID of the application, has to be requested from DATEV
  • clientSecret = Password for clientId, has to be stored securely in the client
  • clientScopes = Scope for which authorization is requested. Format: openid <scope> … (all parameters in lowercase letters and separated by blanks)
  • clientRedirectPort = The port the web browser connects to after authentication. Datev.Cloud.Authentication generates a Redirect URL from the port: http://localhost:<port>/datev/authorize/<randomvalue> 

    A URLACL registration is not necessary. The DLL listens to the port per http.sys.

Then create a new Client:

    var client = new Datev.Cloud.Authentication.Client(options);

Call the LoginAsync method:

    var loginResult = await client.LoginAsync();

The web browser is opened; log in via SmartCard or another medium; if necessary, continue with OK on the consent page.

The redirection to the previously configured port is carried out; close the web browser manually, if necessary.

The LoginResult consists of 4 Strings and a Bool:

  • AccessToken = String required to access the API
  • RefreshToken = String used to create new AccessTokens
  • Error = String containing an error text in case of a failed login
  • IdentityToken = String containing the unique ID of the use
  • Success = true: Login was successful; false: Login failed

Create a RefreshTokenHandler and HTTP client:

    RefreshTokenHandler refreshTokenHandler = new RefreshTokenHandler(client, loginResult.RefreshToken, loginResult.AccessToken);
    
    var apiClient=new HttpClient(refreshTokenHandler);

The RefreshTokenHandler also sets the access token internally. The refresh token may only be used once.

CAUTION: Use this one HTTP client for all HTTP connections. Do not create multiple HTTP clients with identical tokens. When a refresh token is used a second time, all tokens of the current login become invalid.

Call the API with the apiClient:

    var apiresult = await apiClient.GetAsync(new Uri("https://sandbox-api.datev.de/<required API>"));

If the access token is expired, a new access token and a new refresh token are collected automatically via the RefreshTokenHandler. This works until the refresh token expires. The token lifetime depends on the ClientID, and is usually 15 minutes for access tokens, and 11 hours for refresh tokens.

After expiration of a token, the API returns the status code HTTP 401. At that point, the application has to react with a new login via LoginAsync, which results in the web browser reopening the login and consent page.

Special case: If sending data (http put OR http post) via System.Net.Http.StreamContent takes longer than the lifetime of the access token (status code HTTP 401), the request does not retry automatically (streams can only be read once). In this case, it is necessary to set up a new stream. Do not use the same stream twice, or else a System.InvalidOperationException will be thrown with the following message: „The stream was already consumed. It cannot be read again.” (resp. in German: „Der Stream wurde bereits verbraucht. Er kann nicht noch einmal gelesen werden.“)

The RefreshTokenHandler also sets certain DATEV-specific headers in the HTTP request.

 

Web browser

The login uses the default browser that the user has configured. Supported web browsers are Chrome, Edge (Chromium), or Internet Explorer. The DATEV login does not work with other web browsers (e.g. Firefox) and falls back on using Edge instead.

Since version 1.5.1 the option RequireBrowserType is no longer supported.

 

Enforce logon medium

You can use

client.ConfigOptions.RequireAuthenticationMethod=AuthenticationMethod.SmartCard;

to enforce authentication via SmartCard. This is necessary if other logon media are not supported.

You can use

client.ConfigOptions.RequireAuthenticationMethod=AuthenticationMethod.SmartLogin;

to enforce authentication via SmartLogin.

 

HTTP proxy support on the user’s side

To use an HTTP proxy, you have to pass an IWebProxy at client creation.

Sample for a proxy with basic authentication using the WebProxy class:

var cred = new NetworkCredential(<user name>, <password>);
var proxy = new WebProxy(<proxy name>:<port number>, false, new string[] { }, cred);
var client = new Client(options, proxy);

If the proxy supports Windows authentication (NTLM or Kerberos) you can also take the login credentials of the current user.

The HTTP client has to use the same proxy for the API. For that, you have to pass an HttpClientHandler as InnerHandler to the RefreshTokenHandler.

    var proxyHandler = new HttpClientHandler 
                    {
                        Proxy = proxy,
                        UseProxy = true,
                    };
    var refreshTokenHandler = new RefreshTokenHandler(client, 
                                   result.RefreshToken,
                                   result.AccessToken,
                                   proxyHandler);
    using (HttpClient httpClient = new HttpClient(refreshTokenHandler))
    {
       // use httpClient ->
    }
    

In a LAN without direct internet access, a proxy must also be configured in the web browser in use.

 

Medium “DATEV-Benutzer” for users with a “DATEV-Kommunikationsserver”

The login with a DATEV-Benutzer (i.e. DATEV user) in conjunction with a DATEV Kommunikationsserver (i.e. DATEV-communication server) is supported, provided that:

a) A DATEV-Kommunikationsserver (chargeable DATEV product) version 2.0 or higher is installed on one PC in the LAN, and

b) The RZ-Kommunikation (i.e. datacenter communication software) version 2.0 or higher is installed on the LAN workplace PC.

To use the DATEV-Benutzer (i.e. DATEV user) as a logon medium in conjunction with the central SmartCard at the DATEV Kommunikationsserver PC, the DFÜ-Profil (remote data transmission profile) on the LAN workplace PC must be set to DFÜ im Netzbetrieb (remote data transmission in network operation). The DATEV Benutzer must be linked to a Person im the DATEV-Rechenzentrum (person in the DATEV datacenter).

You will find further information in the following documents (only available in German language so far):

If you use client.ConfigOptions.RequireAuthenticationMethod to enforce the logon medium SmartCard or SmartLogin, the logon via DATEV Benutzer will not be utilized.

Logging

Datev.Cloud.Authentication as well as the underlying IdentityModel.OidcClient provide a logging mechanism via Liblog. For further information, see http://www.nuget.org/packages/LibLog/.

Use the NuGet package Serilog to pull the logging data (see https://serilog.net/).

Install the NuGet package Serilog as well as Serilog.Sinks.Console to activate console logging:

Log.Logger = new LoggerConfiguration() .MinimumLevel.Information().WriteTo.Console().CreateLogger();

Call

MinimumLevel.Debug()

to generate verbose logs. Further information on other logging variants can be found at https://github.com/serilog/serilog/wiki/Provided-Sinks.

For a sample of a console application see https://download.datev.de/download/developer-portal/dcal/datev.cloud.authentication.sample.zip

Changelog

[1.6.3] - 2024-04-25

Fixed:

  • Redirect endpoint for Hybrid Flow responds correctly to OPTIONS request with the header Access-Control-Request-Private-Network with the header Access-Control-Allow-Private-Network. Necessary for a new browser feature Private Network Access, see Private Network Access and Private Network Access Preflight.

[1.6.2] - 2024-03-27

Added:

  • Redirect endpoint for Hybrid Flow handles CORS OPTIONS request from browser.