{"body":"DATEV uses its own implementation of the **OpenID Connect Authorization Code Flow with PKCE**, allowing third-party applications to gain authorization for accessing the DATEV data center. To configure DATEV authentication for using our Online APIs, please follow these steps:\n \n1. Register your application to establish communication with our APIs.\n2. After completing the registration process, you will be provided with a Client ID and a Client secret.\n   - Give the app a name. The name should be known to the user as it will appear on the consent page.\n   - In the Redirect URL(s) field, enter a single URL or a list of URLs to which the identity provider (IdP) is permitted to redirect the code for this Client ID. For web applications, this is the endpoint of the application that receives the code. For on-premises applications, an endpoint running on localhost or a custom URL scheme can be used to transport the code back to the application. The URL http://localhost is treated as a wildcard for http://localhost:{anyPort}/{anyPath}. All other URLs must be specified 1:1 as requested in the authorize request.\n   - Select \"OpenID Connect Authorisation Code Flow\". The \"Hybrid Flow\" is deprecated and should not be used for new applications.\n   - The client type Public is sufficient in most cases. For web applications that follow the backend for frontend pattern (see Best Practice for browser-based applications), Confidential can be selected if a long-lasting token is required.\n3. Implement the standard Authorization Code Flow with PKCE, as specified in OAuth 2.0 and OpenID Connect.\n\n\n## Authentication\nThe login process adheres to the OAuth/OIDC Authentication Code Flow with PKCE, as outlined in [RFC 6749 Section 4.1](https://datatracker.ietf.org/doc/html/rfc6749#section-4.1).\n\nUpon successful completion of the login process, the access token becomes available for making calls to the DATEV APIs. Any error codes for requests will follow the standard HTTP and error code definitions specified in OAuth 2.0, as per RFC 6749.\n\n**Within the specification, some adjustments are necessary:**\n\n| **Adjustment** | **Description** |\n| --- | --- |\n| **State Parameter** | Required parameter with a minimum length of 20 characters. |\n| **single-use refresh tokens** | Since we provide single-use refresh tokens, you have to make sure that the refresh tokens will only be used once. See \"Token validity\" |\n| **Scope Parameter** | At least, it must include \"openid.\" Multiple scopes can be combined using spaces, e.g., \"openid profile email\". |\n| **PKCE Usage** | PKCE must be used, and the code\\_challenge\\_method must be set to \"S256.\" |\n| **Nonce Parameter** | Required parameter with a minimum length of 20 characters. |\n| **enableWindowsSso** | Include the additional parameter \"enableWindowsSso=true\" in the authorization request to enable Windows Single Sign-On. This is optional but recommended. |\n| **Basic Authorization** | Use Basic Authorization for Code/Token Exchange [(RFC 6749 Section 2.3.1)](https://tools.ietf.org/html/rfc6749#section-2.3.1) |\n| **Token revocation** | `token_type_hint` is mandatory [(RFC 7009 Section 2.1)](https://datatracker.ietf.org/doc/html/rfc7009) |\n\nYou can utilize any available OAuth/OIDC library in your development environment that supports the authorization code grant (with PKCE). Please note that only spaces and plus signs can be used as separators between the scopes. You find an example of a implementation in C# of OAuth2.0 Code Flow with PKCE Sample at the end of this site. \n\n## OAuth/OIDC Endpoints\n**OIDC Discovery Endpoint for the Sandbox environment:**\n[https://login.datev.de/openidsandbox/.well-known/openid-configuration](https://login.datev.de/openidsandbox/.well-known/openid-configuration)\n\n**OIDC Discovery Endpoint for the Productive environment:**\n[https://login.datev.de/openid/.well-known/openid-configuration](https://login.datev.de/openid/.well-known/openid-configuration)\n\nYou can obtain information about other OAuth endpoints (such as token, authorize, jwks) via the discovery endpoint.\n\n\n## Enable Windows SSO with DATEV-Identity (DATEV-Benutzer)\nThe optional authorization request parameter `enableWindowsSso=true` facilitates single sign-on using Windows credentials, commonly referred to as DATEV-Identity (DATEV-Benutzer). When this option is activated and Windows single sign-on is available, it will be employed automatically. The user will not be presented with the method choice if \"EnableWindowsSso\" is set to \"true\" and single sign-on (DATEV-Benutzer) is accessible within the current environment.\n\nIf the user's environment is not configured for single sign-on, the user can select an authentication method, such as DATEV SmartCard / DATEV mIDentity or DATEV SmartLogin.\n\n## Token validity\nThe first access token is requested using the authorization code. Each access token is valid for 15 minutes. A refresh token is issued with each access token. The refresh token is valid for a maximum of 11 hours and can be used to request a new access token. If a refresh token is redeemed, this refresh token and the existing access token **will be invalidated**.\n\nAn unlimited number of refresh tokens can be redeemed in the 11-hour period after the first access token is issued. If the client submits the final refresh token 11 hours after the first access token is generated, the user can carry on working for a maximum of 15 minutes (the lifetime of the access token). After this time period, the user must reauthenticate himself, and the entire authentication process needs to be repeated.\n\nThe aim is for every user to be able to work for 11 hours without signing in again, as they only have to reauthenticate themselves after this period. In other words, it should be possible to work for one workday without reauthentication.\n\nIf you make a request with scope **offline_access**, the generated refresh token can be used for at least 2 years to request a new access tokens. Requests with scope **offline_access** are restricted to a single client. \n\nThe refresh tokens provided are \"single-use refresh tokens.\" It's essential to ensure that each refresh token is used only once. If a refresh token is mistakenly used more than once, it will result in the invalidation of all access and refresh tokens for that session, necessitating the user to go through the authentication process once more. \n\n\n## Request with offline access\n\nWhen you include the additional scope \"offline_access,\" you can request a refresh token with a duration of 2 years. Each time you refresh the token, obtaining a new access and refresh token, the refresh token's expiration will be extended to 2 years from that point. As long as you refresh it within this 2-year window, the refresh token remains valid. However, if 2 years pass without refreshing, the user will need to reauthenticate.\n\nOur 2-year refresh token comes with specific requirements. It is tied to a single consultant and client number (referred to as the `{client-id}`, note the term _client-id_ is used twice here; it does **not** refer to the client-id from the login). As a result, you must request an additional scope formatted as follows: `datev:iam:client:<consultant_number>-<client_number>`.\n\nPlease note that due to the restriction to a single {client-id}, this token will only function with APIs where the {client-id} is part of the URL path.\n\n*   Won't work: ...[api.datev.de/accounting/v1/clients](http://api.datev.de/accounting/v1/clients)\n*   Works: ...[api.datev.de/accounting/v1/clients/{client-id](http://api.datev.de/accounting/v1/clients/%7bclient-id)}\n\nIn addition to these technical aspects, DATEV has specific requirements for the use of this token:\n\n1.  Before you request the token with offline access, you have to check the accessibility to the single client. Therefore you can request the list of the accessible clients or a list of basic data about a given client. \n2.  If you integrate this token into your app, you must also implement token revocation, allowing users to disconnect their accounts from your app.\n3.  Users can also revoke tokens using the DATEV app \"Verbundene Anwendungen\" at [https://apps.datev.de/tokrevui](https://apps.datev.de/tokrevui). Ensure that your app prominently features a link to this DATEV app so that users can easily access it. Also see [**further information**](http://www.datev.de/hilfe/1006477) for that.\n\n\n## Token revocation\nTo revoke previously granted access authorizations, DATEV provides support for the request revocation mechanism as outlined in [RFC7009](https://tools.ietf.org/html/rfc7009). Therefore, it is necessary that your application submits two revocation requests: one for the access token and one for the refresh token. These token revocation requests should be sent to the revocation endpoint.\n\n## Redirect URL Requirements in the Production Environment\nTo ensure secure operation of applications, especially when using refresh tokens (e.g., with the offline_access scope), stricter redirect URL rules will apply starting July 2025. These rules follow the OAuth 2.0 RFC 6749 – Section 2.1.\n\nConfidential Clients\nFor applications with the Confidential client type, the following rules apply in the production environment:\n\n- Only HTTPS redirect URLs are permitted.\n- IP addresses are not allowed (e.g., https://127.0.0.1).\n- localhost is not allowed (http://localhost and https://localhost).\n- Custom URL schemes like myapp://callback are not allowed.\nThese restrictions apply only in the production stage. In the sandbox environment, localhost and IP-based redirects can still be used for development and testing. Before switching to the production environment, all non-compliant URLs must be removed.\n\nPublic Clients\nFor applications with the Public client type, the following restrictions apply:\n\n- No IP addresses (e.g., https://192.168.0.1)\n- No https://localhost\n\nLegacy Support\n- Applications that have already been approved for production are grandfathered in under their current configuration.\n- However, any change to the app configuration (e.g., adding a new redirect URL or renaming the app) will revoke the legacy support.\n- Starting in mid-July 2025, the Developer Portal will automatically prevent saving non-compliant redirect URLs – even for existing apps\nNote: These rules are particularly important for applications implementing long-lived authentication mechanisms such as the 2-year refresh token.\n\nA compliant and secure redirect URL configuration is required in these cases.\n\n\n## Request User Info from the UserInfo Endpoint\nYou can obtain user information about the currently logged-in user by making a request to the UserInfo endpoint. This step is optional and occurs at the conclusion of the login process.\n\nThe UserInfo endpoint is implemented in accordance with the [OpenID Connect Core 1.0 specification](https://openid.net/specs/openid-connect-core-1_0.html#UserInfo).\n\nThe Access Token must be sent as a Bearer Token using the Authorization Header.\n\nThe UserInfo Endpoint Claims are provided as members within a JSON object. The specific Claims included in the response JSON object are determined by the OAuth 2.0 Scopes, as outlined in the following table.\n\nAllowed Scopes:\n\n| **Scope Name** | **Response Claim** | **Type** | **Description** |\n| --- | --- | --- | --- |\n| **profile** | given\\_name | string | Given name of the user |\n|     | family\\_name | string | Family name of the user |\n|     | name | string | Full name of the user |\n| **email** | email | string | E-mail address of the user (not unique). Is no email available, this property will be not returned |\n|     | email\\_verified | boolean | True if the e-mail address of the user is verified. |\n| **business\\_partner** | is\\_member | boolean | True if user is DATEV or office member. |\n| **account\\_id** | account\\_id | string | Media-independent user id. |\n\n## Hints for web applications\nWeb applications must follow the so-called backend for frontend pattern (see [Best Practice for browser-based applications](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-browser-based-apps-18#name-backend-for-frontend-bff)).\n\nThe individual endpoints for logging in (login.datev.de, api.datev.de or sandbox-api.datev.de) do not allow CORS access from other websites, so it is not possible to log in directly in a browser application. \n\nThe idea is that only the backend performs the requests to login.datev.de, api.datev.de / sandbox-api.datev.de and holds the access/refresh tokens. The frontend receives an HttpOnly and secure session cookie from the backend. The backend adds the access token to the API calls to DATEV.\n\n### Hints for Spring Security\n\nThe Spring Security oAuth library only uses PKCE if a public client is configured, but assumes that the client ID has no secret. However, DATEV uses PCKE and expects a client secret, so Basic Authentication must be configured and a separate RequestResolver must be written for PKCE.\n\nIn addition, the OAuth library in Spring forwards to the OAuth client (itself) by default. In the frontend + backend context, a separate success handler must therefore be built, which forwards back to the frontend or the caller of the login endpoint if the login is successful (e.g. by setting a cookie in the frontend before leaving the login page).\n\n## .NET Sample\n\nThis .NET 9 sample project is based on the Duende.IdentityModel.OidcClient 6.0.1 nuget package. You will need a client ID for Code Flow with the redirect URI http://localhost and a subscription to the API accounting clients.\n\nSample code:\n\n```plaintext\nusing System.Diagnostics;\nusing System.Net;\nusing System.Text;\nusing Duende.IdentityModel.Client;\nusing Duende.IdentityModel.OidcClient;\n\nstring myClientId = \"6e9bb4a9feff3dcb49b6bafa3e82ea4e\";\n\nConsole.WriteLine(\"How to use Code Flow with PKCE with the IdP https://login.datev.de/openid / https://login.datev.de/openidsandbox\");\n// DATEV IdP uses endpoints on other hosts\nvar datevEndpointBaseAddresses = new List<string>()\n     {\n         \"https://sandbox-api.datev.de\",\n         \"https://api.datev.de\",\n     };\n\nvar options = new OidcClientOptions()\n{\n    Authority = \"https://login.datev.de/openidsandbox\", // use https://login.datev.de/openid for production\n    ClientId = myClientId,\n    ClientSecret = \"1477515a8afe4cfadd33fede3ff26dae\",\n    Scope = \"openid datev:accounting:clients\", // Scope for Online API accounting:clients\n    RedirectUri = $\"http://localhost:58455/redirect/{Guid.NewGuid()}/\",\n    // Redirect URI with random path to avoid collisions on multi user environments like WTS\n    Policy = new Policy()\n    {\n        Discovery = new DiscoveryPolicy()\n        {\n            AdditionalEndpointBaseAddresses = datevEndpointBaseAddresses\n        }\n    },\n    TokenClientCredentialStyle = ClientCredentialStyle.AuthorizationHeader, // credentials not in body\n    RefreshTokenInnerHttpHandler = new HttpClientHandler()\n    // usage of own httpclienthandler possible (i. e. for http-proxys)\n};\nvar client = new OidcClient(options);\n\nConsole.WriteLine(\"\\nPrepareLogin\");\nvar state = await client.PrepareLoginAsync();\nusing (var http = new HttpListener())\n{\n    http.Prefixes.Add(client.Options.RedirectUri);\n    http.Start();\n    Console.WriteLine(\"Listening for Browser Redirect...\");\n    // Parameter enableWindowsSso for login.datev.de:\n    // if you have DATEV-software with Kommunikationsserver installed, you can login with DATEV-Benutzer (DID).\n    string startUrlWithSuffix = state.StartUrl + \"&enableWindowsSso=true\";\n    var startInfo = new ProcessStartInfo(startUrlWithSuffix);\n    startInfo.UseShellExecute = true;\n    Console.WriteLine($\"\\nStart browser with URL '{startUrlWithSuffix}'\");\n    Process.Start(startInfo);\n    var context = await http.GetContextAsync();\n    // handle OPTIONS request (PNA / CORS preflight request)\n    if (context.Request.HttpMethod == \"OPTIONS\")\n    {\n        Console.WriteLine($\"Request with {context.Request.HttpMethod} instead of expected GET\");\n        var optionsResponse = context.Response;\n        var requestHeaders = context.Request.Headers;\n        var origin = requestHeaders[\"Origin\"];\n        if (origin != null && origin.EndsWith(\".datev.de\"))\n        {\n            optionsResponse.AppendHeader(\"Access-Control-Allow-Headers\", \"Content-Type, Accept\");\n            optionsResponse.AppendHeader(\"Access-Control-Allow-Methods\", \"GET, OPTIONS\");\n            optionsResponse.AppendHeader(\"Access-Control-Max-Age\", \"86400\");\n            optionsResponse.AppendHeader(\"Access-Control-Allow-Origin\", origin);\n            if (requestHeaders[\"Access-Control-Request-Private-Network\"] != null)\n            {\n                optionsResponse.AppendHeader(\"Access-Control-Allow-Private-Network\", \"true\");\n            }\n        }\n        optionsResponse.StatusCode = 204;\n        optionsResponse.Close();\n        context = await http.GetContextAsync();\n    }\n    // sends an HTTP response to the browser.\n    var response = context.Response;\n    string responseString = \"<html lang=\\\"en\\\"><head><title>DATEV Login finished</title></head><body>Please return to the app.</body></html>\";\n    var buffer = Encoding.UTF8.GetBytes(responseString);\n    response.ContentLength64 = buffer.Length;\n    var responseOutput = response.OutputStream;\n    await responseOutput.WriteAsync(buffer, 0, buffer.Length);\n    responseOutput.Close();\n    http.Stop();\n    var query = context.Request.Url?.Query;\n    Console.WriteLine($\"\\nQuery: {query}\");\n    var result = await client.ProcessResponseAsync(query, state);\n    if (result.IsError)\n    {\n        Console.WriteLine($\"\\n\\nError:\\n{result.Error}\");\n    }\n    else\n    {\n        Console.WriteLine();\n        Console.WriteLine($\"Access token:\\n{result.AccessToken}, expires {result.AccessTokenExpiration}\");\n        if (!string.IsNullOrWhiteSpace(result.RefreshToken))\n        {\n            Console.WriteLine($\"Refresh token:\\n{result.RefreshToken}\");\n        }\n    }\n\n    var apiClient = new HttpClient(new RefreshHandler(client, result));\n\n    Console.WriteLine(\"Start API request\");\n    var apiResponse = await apiClient.GetAsync(\"https://accounting-clients.api.datev.de/platform-sandbox/v2/clients\");\n\n    // Reuse the apiClient for all other calls, the RefreshHandler updates expired access token for up to 11 hours \n    // use https://accounting-clients.api.datev.de/platform/v2  with IdP/Authority https://login.datev.de/openid for stage production\n\n    var apiResponseBody = await apiResponse.Content.ReadAsStringAsync();\n\n    Console.WriteLine($\"API response: {apiResponseBody}, http Statuscode: {(int)apiResponse.StatusCode} ({apiResponse.StatusCode})\");\n\n    Console.ReadLine();\n}\n\nclass RefreshHandler : DelegatingHandler\n{\n    private readonly OidcClient client;\n    private string accessToken;\n    private string refreshToken;\n\n    private DateTimeOffset expires;\n\n    public RefreshHandler(OidcClient client, LoginResult result)\n        : base(new HttpClientHandler())\n    {\n        this.client = client;\n        accessToken = result.AccessToken;\n        refreshToken = result.RefreshToken;\n        expires = result.AccessTokenExpiration;\n    }\n    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)\n    {\n        // Refresh access token 1 minute before expiry to avoid problems with incorrect system time\n        var nowPlus1Min = DateTimeOffset.Now + new TimeSpan(0, 1, 0); \n        \n        if (nowPlus1Min > expires) \n        {\n            Console.WriteLine(\"refresh necessary\");\n            var refreshResult= await client.RefreshTokenAsync(refreshToken);\n            if (refreshResult.IsError)\n            {\n                throw new Exception($\"error during refresh: {refreshResult.Error} {refreshResult.ErrorDescription}\");\n            }\n            accessToken = refreshResult.AccessToken;\n            refreshToken = refreshResult.RefreshToken;\n            expires = DateTimeOffset.Now + TimeSpan.FromSeconds(refreshResult.ExpiresIn);\n\n            Console.WriteLine($\"refresh successful, new Access Token\\n{accessToken}\");\n            Console.WriteLine($\"new Refresh Token\\n{refreshToken}\");\n            Console.WriteLine($\"new Access Token expires at {expires}\");\n        }\n\n        if (!request.Headers.Contains(\"X-DATEV-Client-Id\"))\n        {\n            request.Headers.Add(\"X-DATEV-Client-Id\", client.Options.ClientId);\n        }\n\n        if (request.Headers.Contains(\"Authorization\"))\n        {\n            request.Headers.Remove(\"Authorization\");\n        }\n        request.Headers.Add(\"Authorization\", \"Bearer \" + accessToken);\n        \n        var result = await base.SendAsync(request, cancellationToken);\n        \n        return result;\n    }\n}\n```\n\nFirst create a .NET 8 or 9 console application project and install the NuGet package Duende.IdentityModel.OidcClient version 6.0.1. Newer version may have breaking changes that require changes to the sample.\n\nThen create the OidcClientOptions for the DATEV IdP, and create a new OidcClient with these options. Call the method PrepareLoginAsync(). You get a StartURL, which should be extended by the parameter &enableWindowsSso=true to support login via DATEV-Benutzer and DATEV Kommunikationsserver.\n\nThen start a browser with this URL. Listen with a HttpListener on the Redirect URI. The result of the login is in the query string of the Redirect URL, then call client.ProcessResponseAsync() to exchange the code into the access token und refresh token.\n\nYou can manually add the Access Token to the http header, but it is more convenient to use a DelegatingHandler. The RefreshHandler updates the Access Token automatically if required. But the refresh token may only be redeemed once at the DATEV IdP. if the apiClient is used in different threads, the RefreshHandler must be extended. In this case, synchronisation is necessary so that only one thread performs the update and the other thread waits for the result of the first thread.\n\nAfter 11 hours, the refresh token also expires and the refresh response is an http 400 with the OpenID error ‘invalid_grant’. API calls with expired access tokens are rejected with http 401 and the OpenID error ‘invalid_token’. In this case you have to start over with a new login:\n\n*   PrepareLoginAsync(),\n*   start browser and\n*   ProcessResponseAsync().\n\n## SDK for iOS & Android\n\n### Overview\n\nThe DATEV online APIs uses the standard procedure OAuth 2.0 to authorize a third-party mobile app with the DATEV data center. The DATEV Cloud Authentication Library (DCAL) is a framework for authenticating the user and authorizing the mobile app with the DATEV data center. DCAL is compatible with native Android and iOS apps. For authentication purposes, the user requires the DATEV authentication medium [SmartLogin](https://www.datev.de/smartlogin). \n\n### API endpoints\n\n| Name                   | Description                                                                   | Endpoints                                                                                                         |\n| ---------------------- | ----------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------- |\n| &lt;resourceServer&gt; | Destination address for the application-specific calls of DATEVconnect online | Production environment:<br/>https://api.datev.de/ <br/><br/>Sandbox environment:<br/>https://sandbox-api.datev.de/ |\n\n### Download DCAL mobile\n\nThere is only one DCAL for the production and for the sandbox environment.\n\n| DCAL mobile                                          | Type              | Description                                                                                    |\n|------------------------------------------------------| ----------------- |------------------------------------------------------------------------------------------------|\n| [Download Version 2.4.4](https://developer.datev.de/assets/dcalios_b7f38a2b3c.zip)     | iOS Framework     | Framework for the sandbox/production environment. Minimum iOS Version: 11.0                    |\n| [Download Version 2.4.4](https://developer.datev.de/assets/dcal_android_2_4_4_19b007c900.zip) | Android Framework | Framework for the sandbox/production environment. TargetSDK-Version: 31 CompileSDK-Version: 31 |\n\n\n### Registration of a third-party App\n\nPlease prepare the following information for DATEV:\n\n| Name                 | Type        | Description                                                                         |\n| -------------------- | ----------- | ----------------------------------------------------------------------------------- |\n| third-party app name | string      | Name of the third-party app in the consent page.                                    |\n| vendor name          | string      | Company name of the provider of the third-party app.                                |\n| redirect_URI         | &lt;URI&gt; | A defined URI as destination address is necessary, that is used to call up the app. |\n\nThe details for registering the App with DATEV are specified below. These must be agreed upon with DATEV and passed in during initialization of the DCAL mobile.\n\n| Name          | Type                        | Description                                                                         |\n| ------------- | --------------------------- | ----------------------------------------------------------------------------------- |\n| client_id     | string (max. 60 characters) | The client_id is a unique ID assigned by DATEV for the third party app.             |\n| client_secret | string (max. 60 characters) | The client_secret is a unique ID assigned by DATEV for the third party app.         |\n| scope         | string                      | Blank separated List of Scopes used by the third party app.                         |\n| redirect_URI  | &lt;URI&gt;                 | URI used by the SmartLogin App to call up the app.                 |\n| use_Sandbox   | Bool                        | Boolean if the DCAL should use the Sandbox environment endpoint for authentication. |\n| context \\*    | Context                     | The Android-Application Context                                                     |\n\n**Only necessary for an Android application*\n\n### Implementation Information - Embedding the library\n\n#### iOS\n\nThe DCAL mobil for iOS is distributed as a XCFramework. The DCAL XCFramework must be embedded in the iOS app project.\n\nTo enable the DCAL to verify the redirect when logging in using the OAuth procedure, the UIApplicationDelegate function handleOpenURL must be extended as follows:\n\n```\n//URL-Scheme in Redirect-URI\nfunc application(application: UIApplication, handleOpenURL url:NSURL)-> Bool {\n    let isDcalUrl:Bool = DCAL.handleURL(url)\n    …\n}\n\n// OR //\n\n//Universal-Linking in Redirect-URI\noverride func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([Any]?) -> Void) -> Bool {\n    if(userActivity.activityType == NSUserActivityTypeBrowsingWeb) {\n        let url = userActivity.webpageURL!;\n        let isDcalUrl:Bool = DCAL.handleURL(url: url);\n    }\n    ...\n}\n```\n\n#### Android\n\nTo enable the DCAL to verify the redirect when logging in using the OAuth procedure, the MainActivity function onNewIntent must be extended as follows:\n\n```\n//URL-Scheme handled by onNewIntent in the MainActivity\noverride fun onNewIntent(intent: Intent?) {\n    super.onNewIntent(intent)\n    if (intent != null) {\n        if (intent.data != null) {\n            DCAL.handleUrl(intent.data)\n        }\n    }\n}\n```\n\n### DCAL States\n\nDCAL can be in the following states:\n\n- Initialized\n- Uninitialized\n- LoggedIn\n- LoggedOut\n\n### DCAL API\n\n#### Initialize DCAL\n\nDCAL can either be initialized when starting the app or prior to the authentication of the user with the DATEV data center.\n\nWe recommend that initialization is performed when starting the app.\n\n```\n## iOS & Android #\nDCAL.initialize([Parameter]) -> DCAL_State\n```\n\nReturns the current state of the DCAL (DCAL_State). The DCAL is initialized using the information from the parameters.\n\n#### Return values\n\n| State                                  | Description                                                                                    |\n| -------------------------------------- | ---------------------------------------------------------------------------------------------- |\n| initialized                            | DCAL is initialized.                                                                           |\n| uninitialized                          | DCAL could not be initialized because, for example, the configuration file could not be found. |\n| initialized &#x007C;&#x007C; loggedIn  | DCAL is already initialized, and the user is already logged in with DATEV.                     |\n| initialized &#x007C;&#x007C; loggedOut | DCAL is already initialized, and the user is not logged in with DATEV.                         |\n  \n\n#### Login\n\n```\n## iOS & Android #\nDCAL.requestLogin()\n```\n\nThe authentication of the user and the authorization of the app with the DATEV data center are initiated in an asynchronous process.\n\nWhen the log-in class is registered for DCAL authDelegate, then the log-in class will be informed of a DCAL state change via the delegate method `dcalAuthStateChanged`. The method may contain the following parameters:\n\n| Parameter | Value                                  | Description                                                             |\n| --------- | -------------------------------------- | ----------------------------------------------------------------------- |\n| state     | initialized &#x007C;&#x007C; loggedOut | DCAL is initialized, and the user is not logged in with DATEV.          |\n| state     | initialized &#x007C;&#x007C; loggedIn  | DCAL is initialized, and the user is successfully logged in with DATEV. |\n| state     | uninitialized                          | DCAL is not initialized.                                                |\n| error     | ...                                    | ...                                                                     |\n\nExample of registering a log-in class for the DCAL authDelegate:\n\n```\n## iOS #\nDCAL.authDelegate = self\n\n## Android #\nDCAL.authDelegate = this\n```\n\n#### Log-out user\n\n```\nDCAL.requestLogout()\n```\n\nThe user is logged out of the DATEV data center in an asynchronous process. Therefore, the app is not authorized to conduct data interchange with the DATEV data center.\n\nWhen the log-in class is registered for DCAL authDelegate, then the log-in class will be informed of a DCAL state change via the delegate method `dcalAuthStateChanged`.\n\nThe method may contain the following parameters:\n\n| Parameter | Value                                  | Description                                                             |\n| --------- | -------------------------------------- | ----------------------------------------------------------------------- |\n| state     | initialized &#x007C;&#x007C; loggedOut | DCAL is initialized, and the user is not logged in with DATEV.          |\n| state     | initialized &#x007C;&#x007C; loggedIn  | DCAL is initialized, and the user is successfully logged in with DATEV. |\n| state     | uninitialized                          | DCAL is not initialized.                                                |\n| error     | ...                                    | ...                                                                     |\n\nExample of registering a log-in class for the DCAL authDelegate:\n\n```\n## iOS #\nDCAL.authDelegate = self\n\n## Android #\nDCAL.authDelegate = this\n```\n\n#### Create a URLSession in iOS\n\n```\nDCAL.createSession() throws -> URLSession //new\n```\n\n```\nDCAL.session() -> URLSession  //deprecated since DCAL Version 2.1.1\n```\n\nThis function creates a URLSession with adjustments to enable secure communication with the DATEV data center.\n\n#### Android networking (reqires DCAL Version >= 2.0.0)\n\nFor networking with DATEV APIs the DCAL is customizing the nativ Android Volley-API (https://developer.android.com/training/volley).\n\n```\nimport com.android.volley.*\n...\nvar datevConnection: DatevConnection? = DatevConnection.getInstance(this);\n\n// GET-Request\ndatevConnection.getData(url: String, header:Map? = null, successListener:Response.Listener, errorListener: Response.ErrorListener);\n\n// POST-Request\ndatevConnection.postData(url: String, data: ByteArray, header:Map?, successListener:Response.Listener, errorListener: Response.ErrorListener);\n```\n\n#### Create a URLConnection in Android (deprecated since DCAL Version 2.0.0)\n\n```\nDatevUrlConnection([Parameter]) -> DatevUrlConnection\n```\n\nThis function creates a DatevUrlConnection with adjustments to enable secure communication with the DATEV data center.\n\n#### SessionDelegate\n\n```\n## iOS #\nDCAL.sessionDelegate = self\nfunc dcalSession(totalBytesExpectedToSend: Int, totalBytesSent: Int, totalBytesExpectedToReceive: Int, didReceive: Int) {\n...\n}\n\n## Android #\nDCAL.sessionDelegate = this\noverride fun dcalSession(totalBytesExpectedToSend: Long, totalBytesSent: Long, totalBytesExpectedToReceive: Long, totalBytesReceived: Long) {\n...\n}\n```\n\nPeriodically informs the delegate of the progress of sending/receiving content to/from the server.\n\n#### Get the DCAL state\n\n```\nDCAL.getState() -> DCAL_State\n```\n\nReturns the current DCAL state.\n\n#### Reset DCAL\n\n```\nDCAL.clean() -> DCAL_State\n```\n\nResets the DCAL to the state “uninitialized”.\n\n#### Is SmartLogin available\n\nCheck if the SmartLogin App is available on the device.\n\n```\nDCAL.isSmartLoginAvailable() -> Bool\n```\n\nReturns a Boolean if the SmartLogin app is available\n\n\\*\\* iOS only:\nYou must declare the URL scheme 'DATEVSmartLogin'. Do this by adding the LSApplicationQueriesSchemes key to your app's Info.plist file. If you call this methode without the declared DATEVSmartLogin URL scheme, this method always returns false, wether or not the SmartLogin app is installed.\n\n### Changelog\n\nThe DCAL library has different versions. The changes in each version are listed here.\n\n#### iOS\n\n| DCAL Version | Changes                                                       | Date       |\n| ------------ | ------------------------------------------------------------- | ---------- |\n| 2.4.4        | Aktualisierung OpenSSL, LibCURL und NGHTTP                    | 2024-04-26 |\n| 2.4.3        | Bugs fixed + iOS Min Target: 14                               | 2024-01-31 |\n| 2.4.0        | Support new Format for Packaging Frameworks (xcframework); Upgrade OpenSSL to 1.1.1l; including bug and security fixes | 2021-11-11 |\n| 2.1.2        | Swift 5.1.3 Support                                           | 2020-15-01 |\n\n#### Android\n\n| DCAL Version | Changes                                                       | Date       |\n| ------------ | ------------------------------------------------------------- | ---------- |\n| 2.4.4        | Aktualisierung OpenSSL, LibCURL und NGHTTP                    | 2024-04-26 |\n| 2.4.3        | Bugs fixed                                                    | 2024-01-31 |\n| 2.4.0        | Upgrade OpenSSL to 1.1.1l; including bug and security fixes   | 2021-11-11 |\n| 2.1.1        | Fixed bug where access token is not being refreshed correctly | 2019-11-21 |\n","documentId":"iuyshyaz8q21w4vmy3wkwnar","id":53,"localization":{"body":"DATEV verwendet eine eigene Implementierung des **OpenID Connect Authorization Code Flow mit PKCE**, mit der sich Drittanwendungen für den Zugriff auf das DATEV-Rechenzentrum autorisieren können. \n\nSo konfigurieren Sie die DATEV-Authentifizierung für die Nutzung unserer Online-APIs: \n\n1. Erstellen Sie eine App im Dashboard Ihrer Organisation\n   -  Geben Sie der App einen Namen. Der Name sollte dem Nutzer bekannt sein, da er auf der Consent Page erscheint.\n   -  Geben Sie unter Redirect URL(s) eine oder eine Liste von URLs ein, an die der Identity Provider (IdP) den Code für diese Client ID weiterleiten darf. Bei Webanwendungen ist dies der Endpoint der Anwendung, der den Code empfängt. Bei OnPremise-Anwendungen kann ein Endpoint unter localhost oder ein eigenes URL-Schema verwendet werden, um den Code zurück in die Anwendung zu transportieren. Der Eintrag http://localhost wird wie ein Platzhalter behandelt, d. h. für diese Client-ID ist http://localhost:{beliebigerPort}/{beliebigerPfad} erlaubt. Alle anderen URLs sind 1:1 so anzugeben, wie sie später von der Anwendung im Authorize Request angefordert werden. \n   -  Wählen Sie als Flow „OpenID Connect Authorization Code Flow”. Der Hybrid Flow ist deprecated und sollte nicht für neue Anwendungen verwendet werden.\n   -  Der Client Type Public ist in den meisten Fällen ausreichend. Für Webanwendungen die dem Backend for Frontend-Pattern folgen (siehe [Best Practice for browser-based applications](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-browser-based-apps-18#name-backend-for-frontend-bff)) kann Confidential gewählt werden, wenn ein langlebiger Token benötigt wird. \n3. Sie erhalten eine Client-ID und ein Client-Secret.\n4. Implementieren Sie den Standard Authorization Code Flow with PKCE, wie in OAuth 2.0 und OpenID Connect beschrieben.\n\n## Authentifizierung\n\nDer Anmeldeprozess folgt dem OAuth/OIDC Authentication Code Flow mit PKCE, wie in [RFC 6749 Abschnitt 4.1](https://datatracker.ietf.org/doc/html/rfc6749#section-4.1) beschrieben.\n\nNach erfolgreichem Abschluss des Anmeldevorgangs wird das Access-Token für Aufrufe der DATEV-APIs verfügbar. Alle Fehlercodes für Anfragen folgen den Standard-HTTP- und Fehlercode-Definitionen, die in OAuth 2.0 gemäß RFC 6749 festgelegt sind.\n\n**Innerhalb der Spezifikation sind einige Anpassungen erforderlich:**\n\n| **Anpassung** | **Beschreibung** |\n| --- | --- |\n| **State Parameter** | Erforderlicher Parameter mit einer Mindestlänge von 20 Zeichen. |\n| **single-use refresh tokens** | Da wir einmalige Aktualisierungs-Tokens anbieten, müssen Sie sicherstellen, dass die Aktualisierungs-Tokens nur einmal verwendet werden. Siehe \"Token-Gültigkeit\" |\n**Scope Parameter** | Er muss mindestens \"openid\" enthalten. Mehrere Scopes können mit Leerzeichen kombiniert werden, z. B. \"openid profile email\". |\n| **PKCE Usage** | PKCE muss verwendet werden und die code\\_challenge\\_method muss auf \"S256\" gesetzt sein. |\n| **Nonce Parameter** | Erforderlicher Parameter mit einer Mindestlänge von 20 Zeichen. |\n| **enableWindowsSso** | Fügen Sie den zusätzlichen Parameter \"enableWindowsSso=true\" in die Autorisierungsanfrage ein, um Windows Single Sign-On zu aktivieren. Dies ist optional, wird aber empfohlen. |\n| **Basic Authorization** | Verwenden Sie Basic Authorization für Code/Token Exchange [(RFC 6749 Abschnitt 2.3.1)](https://tools.ietf.org/html/rfc6749#section-2.3.1) |\n| **Token revocation** | `token_type_hint` ist erforderlich [(RFC 7009 Abschnitt 2.1)](https://datatracker.ietf.org/doc/html/rfc7009) |\n\nSie können jede verfügbare OAuth/OIDC-Bibliothek in Ihrer Entwicklungsumgebung verwenden, die die Autorisierungscodeerteilung (mit PKCE) unterstützt. Bitte beachten Sie, dass nur Leerzeichen und Pluszeichen als Trennzeichen zwischen den Scopes verwendet werden können. \nWeiter unten auf der Seite finden Sie ein Beispiel für eine Implementierung in C#.\n\n## OAuth/OIDC Endpunkte\n**OIDC Discovery Endpunkt für die Sandbox Umgebung:**\n[https://login.datev.de/openidsandbox/.well-known/openid-configuration](https://login.datev.de/openidsandbox/.well-known/openid-configuration)\n\n**OIDC Discovery Endpunkt für die Produktivumgebung:**\n[https://login.datev.de/openid/.well-known/openid-configuration](https://login.datev.de/openid/.well-known/openid-configuration)\n\nSie können Informationen über andere OAuth-Endpunkte (z. B. Token, authorize, jwks) über den Discovery-Endpunkt erhalten.\n\n## Enable Windows SSO mit DATEV-Identität (DATEV-Benutzer)\nDer optionale Parameter der Autorisierungsanfrage, `enableWindowsSso=true,` erleichtert die einmalige Anmeldung unter Verwendung von Windows-Zugangsdaten, die als DATEV-Identität (DATEV-Benutzer) bezeichnet wird. Wenn diese Option aktiviert ist und Windows Single Sign-On verfügbar ist, wird es automatisch verwendet. Wenn \"EnableWindowsSso\" auf \"true\" gesetzt ist und Single Sign-On (DATEV-Benutzer) in der aktuellen Umgebung verfügbar ist, wird dem Benutzer dieses Anmeldeverfahren nicht zur Auswahl angeboten.\n\nWenn die Umgebung des Benutzers nicht für Single Sign-On konfiguriert ist, kann der Benutzer ein Authentifizierungsverfahren, wie z. B. DATEV SmartCard / DATEV mIDentity oder DATEV SmartLogin, auswählen.\n\n## Token Gültigkeit\nDas erste Access-Token wird mit dem Autorisierungscode angefordert. Jedes Access-Token ist 15 Minuten lang gültig. Mit jedem Access-Token wird ein Refresh-Token ausgegeben. Das Refresh-Token ist maximal 11 Stunden gültig und kann zur Anforderung eines neuen Access-Tokens verwendet werden. Wird ein Refresh-Token eingelöst, werden dieses Refresh-Token und das bestehende Access-Token **ungültig**.\n\nInnerhalb von 11 Stunden nach Ausgabe des ersten Access-Tokens kann eine unbegrenzte Anzahl von Refresh-Token eingelöst werden. Wenn der Kunde das letzte Refresh-Token 11 Stunden nach der Generierung des ersten Access-Tokens einreicht, kann der Benutzer maximal 15 Minuten lang (die Lebensdauer des Access-Tokens) weiterarbeiten. Nach Ablauf dieser Zeitspanne muss sich der Benutzer erneut authentifizieren und der gesamte Authentifizierungsprozess muss wiederholt werden.\n\nZiel ist es, dass jeder Nutzer 11 Stunden lang arbeiten kann, ohne sich erneut anzumelden, da er sich erst nach diesem Zeitraum erneut authentifizieren muss. Mit anderen Worten, es sollte möglich sein, einen Arbeitstag lang zu arbeiten, ohne sich erneut zu authentifizieren.\n\nWenn Sie einen Antrag mit dem Scope **offline_access** stellen, kann das generierte Refresh-Token mindestens 2 Jahre lang verwendet werden, um ein neues Access-Token zu beantragen. Anträge mit dem Scope **offline_access** sind auf einen einzigen Mandanten beschränkt. \n\nDie zur Verfügung gestellten Refresh-Token sind \"single-use Refresh-Token\". Es ist unbedingt darauf zu achten, dass jedes Refresh-Token nur einmal verwendet wird. Wird ein Refresh-Token fälschlicherweise mehr als einmal verwendet, werden alle Access- und Refresh-Token für diese Sitzung ungültig, so dass der Benutzer den Authentifizierungsprozess erneut durchlaufen muss. \n\n## Offline Zugriff erhalten\n\nWenn Sie den zusätzlichen Scope \"offline_access\" angeben, können Sie ein Aktualisierungs-Token mit einer Dauer von 2 Jahren anfordern. Jedes Mal, wenn Sie das Token aktualisieren und ein neues Zugangs- und Refresh-Token erhalten, wird die Gültigkeitsdauer des Refresh-Tokens ab diesem Zeitpunkt auf 2 Jahre verlängert. Solange Sie es innerhalb dieses 2-Jahres-Fensters aktualisieren, bleibt das Refresh-Token gültig. Wenn jedoch 2 Jahre ohne Auffrischung vergehen, muss sich der Benutzer erneut authentifizieren.\n\nUnser 2-Jahres-Refresh-Token ist an bestimmte Voraussetzungen geknüpft. Es ist an eine einzige Berater- und Mandantennummer gebunden (die sogenannte `{Client-ID}`, nicht zu verwechseln mit der Client-ID der App, hier gibt es eine Überschneidung der Bezeichnungen). Daher müssen Sie einen zusätzlichen Scope anfordern, der wie folgt formatiert ist: `datev:iam:client:<Beraternummer>-<Mandantennummer>`.\n\nBitte beachten Sie, dass dieses Token aufgrund der Beschränkung auf eine einzige `{client-id}` nur mit APIs funktioniert, bei denen die `{client-id}` Teil des URL-Pfads ist.\n\n* Funktioniert nicht: ...[api.datev.de/accounting/v1/clients](http://api.datev.de/accounting/v1/clients)\n* Funktioniert: ...[api.datev.de/accounting/v1/clients/{client-id](http://api.datev.de/accounting/v1/clients/%7bclient-id)}\n\nNeben diesen technischen Aspekten gibt es bei DATEV spezifische Anforderungen an die Verwendung dieses Tokens:\n\n1.  Bevor Sie das Token mit Offline-Zugang anfordern, müssen Sie die Erreichbarkeit des einzelnen Mandanten prüfen. Dazu können Sie die Liste der zugänglichen Mandanten oder eine Liste mit Basisdaten zu einem bestimmten Mandanten anfordern. \n2.  Wenn Sie dieses Token in Ihre Anwendung integrieren, müssen Sie auch einen Token-Widerruf implementieren, der es den Nutzern ermöglicht, ihre Konten von Ihrer Anwendung abzumelden.\n3.  Nutzer können Token auch über die DATEV-App \"Verbundene Anwendungen\" unter [https://apps.datev.de/tokrevui](https://apps.datev.de/tokrevui) widerrufen. Stellen Sie sicher, dass in Ihrer App ein Link zu dieser DATEV-App prominent platziert ist, damit die Nutzer diese leicht erreichen können. Siehe dazu auch [**Weitere Informationen**](http://www.datev.de/hilfe/1006477).\n\n## Widerruf von Token\nUm bereits erteilte Zugriffsberechtigungen zu widerrufen, unterstützt DATEV den in [RFC7009](https://tools.ietf.org/html/rfc7009) beschriebenen Mechanismus zum Widerruf von Tokens. Daher ist es erforderlich, dass Ihre Anwendung zwei Widerrufsanfragen stellt: eine für das Access-Token und eine für das Refresh-Token. Diese Token-Widerrufsanfragen sollten an den Widerrufsendpunkt gesendet werden.\n\n## Anforderungen an Redirect-URLs in der Produktivumgebung\nFür den sicheren Betrieb von Anwendungen, insbesondere bei Nutzung von Refresh-Tokens (z. B. mit dem Scope offline_access), gelten ab Juli 2025 verschärfte Anforderungen an die Konfiguration von Redirect-URLs. Diese orientieren sich am OAuth 2.0 RFC 6749 – Abschnitt 2.1.\n\nConfidential Clients\nFür Anwendungen mit dem Client-Typ Confidential gelten in der Produktivumgebung folgende Vorgaben:\n\n- Es dürfen ausschließlich HTTPS-Redirect-URLs verwendet werden.\n- Es sind keine IP-Adressen erlaubt (z. B. https://127.0.0.1).\n- localhost ist nicht zulässig (http://localhost und https://localhost).\n- Custom-URL-Schemes wie myapp://callback sind nicht zulässig.\nDiese Einschränkungen gelten **nur in der Produktionsstufe.** In der Sandbox können weiterhin IP-Adressen und localhost für Tests verwendet werden. Vor dem Upgrade in die Produktivumgebung müssen unzulässige URLs entfernt werden.\n\nPublic Clients\nFür Anwendungen mit dem Client-Typ **Public** gelten ebenfalls Einschränkungen:\n\n- Keine IP-Adressen (z. B. https://192.168.0.1)\n- Kein https://localhost\nBestandsschutz\n- Anwendungen, die bereits eine Freigabe für die Produktivumgebung erhalten haben, genießen Bestandsschutz.\n- Änderungen an der App-Konfiguration (z. B. Hinzufügen einer neuen Redirect-URL oder Änderung des App-Namens) heben den Bestandsschutz auf.\n- Ab Mitte Juli 2025 verhindert das Developer Portal automatisch das Speichern unzulässiger Redirect-URLs – auch für bestehende Apps.\n⚠️ Hinweis: Diese Anforderungen gelten insbesondere für Apps, die langfristige Authentifizierungsmechanismen wie den 2-Jahres-Refresh-Token implementieren. Eine saubere und sichere Redirect-Konfiguration ist hierbei Voraussetzung.\n\n## Abfrage von Benutzerinformationen vom UserInfo-Endpunkt\nSie können Benutzerinformationen über den aktuell angemeldeten Benutzer erhalten, indem Sie eine Anfrage an den UserInfo-Endpunkt stellen. Dieser Schritt ist optional und erfolgt am Ende des Anmeldevorgangs.\n\nDer UserInfo-Endpunkt ist in Übereinstimmung mit der [OpenID Connect Core 1.0 Spezifikation] (https://openid.net/specs/openid-connect-core-1_0.html#UserInfo) implementiert.\n\nDas Access-Token muss als Bearer Token unter Verwendung des Authorization Headers gesendet werden.\n\nDie UserInfo-Endpunkt-Claims werden als Elemente innerhalb eines JSON-Objekts bereitgestellt. Die spezifischen Claims, die im JSON-Objekt der Antwort enthalten sind, werden durch die OAuth 2.0-Scopes bestimmt, wie in der folgenden Tabelle dargestellt.\n\nErlaubte Scopes:\n| **Scope Name** | **Response Claim** | **Typ** | **Beschreibung** |\n| --- | --- | --- | --- |\n| **profile** | given\\_name | string | Vorname des Users |\n|     | family\\_name | string | Nachname des Users |\n|     | name | string | Vollständiger Name des Users |\n| **email** | email | string | E-Mail-Adresse des Benutzers (nicht eindeutig). Ist keine E-Mail verfügbar, wird keine zurückgegeben |\n|     | email\\_verified | boolean | True, wenn die E-Mail Adresse verifiziert ist. |\n| **business\\_partner** | is\\_member | boolean | True wenn der User DATEV- oder Kanzleimitarbeiter:in ist. |\n| **account\\_id** | account\\_id | string | Medien-unabhängige user id. |\n\n## Hinweise für Webanwendungen\n\nWebanwendungen müssen dem sogenannten Backend for Frontend-Pattern folgen (siehe [Best Practice for browser-based applications](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-browser-based-apps-18#name-backend-for-frontend-bff)).\n\nDie einzelnen Endpunkte für die Anmeldung (login.datev.de, api.datev.de oder sandbox-api.datev.de) lassen keinen CORS-Zugriff von anderen Webseiten zu, eine Anmeldung direkt in einer Browseranwendung ist also nicht möglich. \n\nDie Idee ist, dass nur das Backend die Anfragen an login.datev.de, api.datev.de / sandbox-api.datev.de durchführt und die Access-/Refresh Token hält. Das Frontend erhält vom Backend ein HttpOnly und Secure Session Cookie. Das Backend fügt den API-Calls zu DATEV das Access Token als Bearer-Token hinzu.\n\n### Hinweise für Spring Security\n\nDie oAuth-Bibliothek von Spring Security verwendet PKCE nur, wenn man einen public Client konfiguriert, geht aber davon aus, dass die Client-ID kein Secret hat. DATEV verwendet jedoch PCKE und erwartet ein Client Secret, daher muss Basic Authentication konfiguriert und ein eigener RequestResolver für PKCE geschrieben werden.\n\nAußerdem leitet die OAuth Bibliothek in Spring standardmäßig an den OAuth Client (also sich selbst) weiter. Im Kontext Frontend + Backend muss also ein eigener Success-Handler gebaut werden, der bei erfolgreichem Login an das Frontend bzw. den Aufrufer des Login-Endpunkts zurückleitet (z.B. durch Setzen eines Cookies im Frontend vor Verlassen der Login-Seite).\n\n## .NET Beispiel\n\nDieses .NET 9-Beispielprojekt basiert auf dem Nuget-Paket Duende.IdentityModel.OidcClient 6.0.1. Sie benötigen eine Client-ID für Code Flow mit dem Redirect URI http://localhost und ein Abonnement für die API Accounting-Clients.\n\nBeispiel Code: \n```plaintext\nusing System.Diagnostics;\nusing System.Net;\nusing System.Text;\nusing Duende.IdentityModel.Client;\nusing Duende.IdentityModel.OidcClient;\n\nstring myClientId = \"6e9bb4a9feff3dcb49b6bafa3e82ea4e\";\n\nConsole.WriteLine(\"How to use Code Flow with PKCE with the IdP https://login.datev.de/openid / https://login.datev.de/openidsandbox\");\n// DATEV IdP uses endpoints on other hosts\nvar datevEndpointBaseAddresses = new List<string>()\n     {\n         \"https://sandbox-api.datev.de\",\n         \"https://api.datev.de\",\n     };\n\nvar options = new OidcClientOptions()\n{\n    Authority = \"https://login.datev.de/openidsandbox\", // use https://login.datev.de/openid for production\n    ClientId = myClientId,\n    ClientSecret = \"1477515a8afe4cfadd33fede3ff26dae\",\n    Scope = \"openid datev:accounting:clients\", // Scope for Online API accounting:clients\n    RedirectUri = $\"http://localhost:58455/redirect/{Guid.NewGuid()}/\",\n    // Redirect URI with random path to avoid collisions on multi user environments like WTS\n    Policy = new Policy()\n    {\n        Discovery = new DiscoveryPolicy()\n        {\n            AdditionalEndpointBaseAddresses = datevEndpointBaseAddresses\n        }\n    },\n    TokenClientCredentialStyle = ClientCredentialStyle.AuthorizationHeader, // credentials not in body\n    RefreshTokenInnerHttpHandler = new HttpClientHandler()\n    // usage of own httpclienthandler possible (i. e. for http-proxys)\n};\nvar client = new OidcClient(options);\n\nConsole.WriteLine(\"\\nPrepareLogin\");\nvar state = await client.PrepareLoginAsync();\nusing (var http = new HttpListener())\n{\n    http.Prefixes.Add(client.Options.RedirectUri);\n    http.Start();\n    Console.WriteLine(\"Listening for Browser Redirect...\");\n    // Parameter enableWindowsSso for login.datev.de:\n    // if you have DATEV-software with Kommunikationsserver installed, you can login with DATEV-Benutzer (DID).\n    string startUrlWithSuffix = state.StartUrl + \"&enableWindowsSso=true\";\n    var startInfo = new ProcessStartInfo(startUrlWithSuffix);\n    startInfo.UseShellExecute = true;\n    Console.WriteLine($\"\\nStart browser with URL '{startUrlWithSuffix}'\");\n    Process.Start(startInfo);\n    var context = await http.GetContextAsync();\n    // handle OPTIONS request (PNA / CORS preflight request)\n    if (context.Request.HttpMethod == \"OPTIONS\")\n    {\n        Console.WriteLine($\"Request with {context.Request.HttpMethod} instead of expected GET\");\n        var optionsResponse = context.Response;\n        var requestHeaders = context.Request.Headers;\n        var origin = requestHeaders[\"Origin\"];\n        if (origin != null && origin.EndsWith(\".datev.de\"))\n        {\n            optionsResponse.AppendHeader(\"Access-Control-Allow-Headers\", \"Content-Type, Accept\");\n            optionsResponse.AppendHeader(\"Access-Control-Allow-Methods\", \"GET, OPTIONS\");\n            optionsResponse.AppendHeader(\"Access-Control-Max-Age\", \"86400\");\n            optionsResponse.AppendHeader(\"Access-Control-Allow-Origin\", origin);\n            if (requestHeaders[\"Access-Control-Request-Private-Network\"] != null)\n            {\n                optionsResponse.AppendHeader(\"Access-Control-Allow-Private-Network\", \"true\");\n            }\n        }\n        optionsResponse.StatusCode = 204;\n        optionsResponse.Close();\n        context = await http.GetContextAsync();\n    }\n    // sends an HTTP response to the browser.\n    var response = context.Response;\n    string responseString = \"<html lang=\\\"en\\\"><head><title>DATEV Login finished</title></head><body>Please return to the app.</body></html>\";\n    var buffer = Encoding.UTF8.GetBytes(responseString);\n    response.ContentLength64 = buffer.Length;\n    var responseOutput = response.OutputStream;\n    await responseOutput.WriteAsync(buffer, 0, buffer.Length);\n    responseOutput.Close();\n    http.Stop();\n    var query = context.Request.Url?.Query;\n    Console.WriteLine($\"\\nQuery: {query}\");\n    var result = await client.ProcessResponseAsync(query, state);\n    if (result.IsError)\n    {\n        Console.WriteLine($\"\\n\\nError:\\n{result.Error}\");\n    }\n    else\n    {\n        Console.WriteLine();\n        Console.WriteLine($\"Access token:\\n{result.AccessToken}, expires {result.AccessTokenExpiration}\");\n        if (!string.IsNullOrWhiteSpace(result.RefreshToken))\n        {\n            Console.WriteLine($\"Refresh token:\\n{result.RefreshToken}\");\n        }\n    }\n\n    var apiClient = new HttpClient(new RefreshHandler(client, result));\n\n    Console.WriteLine(\"Start API request\");\n    var apiResponse = await apiClient.GetAsync(\"https://accounting-clients.api.datev.de/platform-sandbox/v2/clients\");\n\n    // Reuse the apiClient for all other calls, the RefreshHandler updates expired access token for up to 11 hours \n    // use https://accounting-clients.api.datev.de/platform/v2  with IdP/Authority https://login.datev.de/openid for stage production\n\n    var apiResponseBody = await apiResponse.Content.ReadAsStringAsync();\n\n    Console.WriteLine($\"API response: {apiResponseBody}, http Statuscode: {(int)apiResponse.StatusCode} ({apiResponse.StatusCode})\");\n\n    Console.ReadLine();\n}\n\nclass RefreshHandler : DelegatingHandler\n{\n    private readonly OidcClient client;\n    private string accessToken;\n    private string refreshToken;\n\n    private DateTimeOffset expires;\n\n    public RefreshHandler(OidcClient client, LoginResult result)\n        : base(new HttpClientHandler())\n    {\n        this.client = client;\n        accessToken = result.AccessToken;\n        refreshToken = result.RefreshToken;\n        expires = result.AccessTokenExpiration;\n    }\n    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)\n    {\n        // Refresh access token 1 minute before expiry to avoid problems with incorrect system time\n        var nowPlus1Min = DateTimeOffset.Now + new TimeSpan(0, 1, 0); \n        \n        if (nowPlus1Min > expires) \n        {\n            Console.WriteLine(\"refresh necessary\");\n            var refreshResult= await client.RefreshTokenAsync(refreshToken);\n            if (refreshResult.IsError)\n            {\n                throw new Exception($\"error during refresh: {refreshResult.Error} {refreshResult.ErrorDescription}\");\n            }\n            accessToken = refreshResult.AccessToken;\n            refreshToken = refreshResult.RefreshToken;\n            expires = DateTimeOffset.Now + TimeSpan.FromSeconds(refreshResult.ExpiresIn);\n\n            Console.WriteLine($\"refresh successful, new Access Token\\n{accessToken}\");\n            Console.WriteLine($\"new Refresh Token\\n{refreshToken}\");\n            Console.WriteLine($\"new Access Token expires at {expires}\");\n        }\n\n        if (!request.Headers.Contains(\"X-DATEV-Client-Id\"))\n        {\n            request.Headers.Add(\"X-DATEV-Client-Id\", client.Options.ClientId);\n        }\n\n        if (request.Headers.Contains(\"Authorization\"))\n        {\n            request.Headers.Remove(\"Authorization\");\n        }\n        request.Headers.Add(\"Authorization\", \"Bearer \" + accessToken);\n        \n        var result = await base.SendAsync(request, cancellationToken);\n        \n        return result;\n    }\n}\n```\n\nErstellen Sie zunächst ein .NET 8 oder 9 - Konsolenanwendungsprojekt und installieren Sie das NuGet-Paket Duende.IdentityModel.OidcClient Version 6.0.1. Bei neueren Versionen können sich Änderungen ergeben, die Änderungen am Beispiel erfordern.\n\nErstellen Sie dann die OidcClientOptions für den DATEV IdP und erstellen Sie einen neuen OidcClient mit diesen Optionen. Rufen Sie die Methode PrepareLoginAsync() auf. Sie erhalten eine StartURL, die um den Parameter &enableWindowsSso=true erweitert werden sollte, um die Anmeldung mit DATEV-Benutzer und DATEV Kommunikationsserver zu unterstützen.\n\nStarten Sie dann einen Browser mit dieser URL. Hören Sie mit einem HttpListener auf die Redirect-URI. Das Ergebnis des Logins steht im Query-String der Redirect-URL, dann rufen Sie client.ProcessResponseAsync() auf, um den Code in das Access-Token und Refresh-Token umzuwandeln.\n\nSie können das Access Token manuell in den http-Header einfügen, aber es ist bequemer, einen DelegatingHandler zu verwenden. Der RefreshHandler aktualisiert das Access Token bei Bedarf automatisch. Der RefreshToken darf aber nur einmal beim DATEV IdP eingelöst werden, wenn der apiClient in verschiedenen Threads verwendet wird, muss der RefreshHandler erweitert werden. In diesem Fall ist eine Synchronisation notwendig, so dass nur ein Thread die Aktualisierung durchführt und der andere Thread auf das Ergebnis des ersten Threads wartet.\n\nNach 11 Stunden läuft auch der Refresh-Token ab und der refresh wird mit einem http 400 und dem OpenID Fehler \"invalid_grant\" beantwortet. API-Aufrufe mit abgelaufenen Access Token werden mit http 401 und dem OpenID Fehler \"invalid_token\" zurückgewiesen. In diesem Fall müssen Sie mit einer neuen Anmeldung von vorne beginnen:\n\n* PrepareLoginAsync(),\n* start browser und\n* ProcessResponseAsync().\n\n\n## SDK für iOS & Android\n\n### Überblick\n\nDie DATEV online APIs nutzen das Standardverfahren OAuth 2.0 zur Autorisierung einer mobilen App eines Drittanbieters gegenüber dem DATEV-Rechenzentrum. Die DATEV Cloud Authentication Library (DCAL) ist ein Framework zur Authentifizierung des Nutzers und Autorisierung der mobilen App mit dem DATEV-Rechenzentrum. DCAL ist kompatibel mit nativen Android- und iOS-Apps. Zur Authentifizierung benötigt der Nutzer das DATEV-Authentifizierungsmedium [SmartLogin](https://www.datev.de/smartlogin).\n\n### API endpoints\n\n| Name                   | Beschreibung                                                                   | Endpoints                                                                                                         |\n| ---------------------- | ----------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------- |\n| &lt;resourceServer&gt; | Zieladresse für die anwendungsspezifischen Aufrufe von DATEVconnect online | Production environment:<br/>https://api.datev.de/ <br/><br/>Sandbox environment:<br/>https://sandbox-api.datev.de/ |\n\n### Download DCAL mobile\n\nEs gibt nur eine DCAL für die Produktions- und für die Sandbox-Umgebung.\n\n| DCAL mobile                                          | Typ              | Beschreibung                                                                                 |\n|------------------------------------------------------| ----------------- |---------------------------------------------------------------------------------------------|\n| [Download Version 2.4.4](https://developer.datev.de/assets/dcalios_b7f38a2b3c.zip)     | iOS Framework     | Framework für die Sandbox/Production Umgebung. Minimum iOS Version: 11.0                    |\n| [Download Version 2.4.4](https://developer.datev.de/assets/dcal_android_2_4_4_19b007c900.zip) | Android Framework | Framework für die Sandbox/Production Umgebung. TargetSDK-Version: 31 CompileSDK-Version: 31 |\n\n### Registrierung bei DATEV für 3rd-Party Apps\n\nBitte bereiten Sie die folgenden Informationen für DATEV vor:\n\n| Name                 | Typ         | Beschreibung                                                                  |\n| -------------------- | ----------- | ----------------------------------------------------------------------------- |\n| Name der 3rd-Party App | string      | Name der Drittanbieter-App auf der Zustimmungsseite.                          |\n| Anbietername         | string      | Firmenname des Anbieters der Drittanbieter-App.                               |\n| redirect_URI         | &lt;URI&gt; | Eine definierte URI als Zieladresse, über die die App aufgerufen werden kann. |\n\nIm Folgenden werden die Details zur Registrierung der App bei DATEV aufgeführt. Diese sind mit DATEV abzustimmen und bei der Initialisierung von DCAL mobile mitzugeben.\n\n| Name          | Typ                        | Beschreibung                                                                         |\n| ------------- | --------------------------- | ----------------------------------------------------------------------------------- |\n| client_id     | string (max. 60 characters) | Die client_id ist eine einzigartige ID, die von der DATEV für die 3rd-Party App vergeben wird.            |\n| client_secret | string (max. 60 characters) | Das client_secret wird nach Abschluss des Registrierungsprozesses von der DATEV vergeben.      |\n| scope         | string                      | Durch Leerzeichen getrennte Liste der von der Drittanbieteranwendung verwendeten Scopes.                          |\n| redirect_URI  | &lt;URI&gt;                 | Eine definierte URI als Zieladresse, über die die App aufgerufen werden kann.                |\n| use_Sandbox   | Bool                        | Boolescher Wert, wenn das DCAL den Endpunkt der Sandbox-Umgebung für die Authentifizierung verwenden soll. |\n| context \\*    | Context                     | Der Android-Anwendungskontext.        \n\n**Nur bei Android Apps erforderlich*\n\n### Implementation Information - Embedding the library\n\n#### iOS\nDas DCAL mobil für iOS wird als XCFramework verteilt. Das DCAL XCFramework muss in das iOS-App-Projekt eingebunden werden.\n\nDamit das DCAL bei der Anmeldung über das OAuth-Verfahren den Redirect verifizieren kann, muss die UIApplicationDelegate-Funktion handleOpenURL wie folgt erweitert werden:\n\n```\n//URL-Scheme in Redirect-URI\nfunc application(application: UIApplication, handleOpenURL url:NSURL)-> Bool {\n    let isDcalUrl:Bool = DCAL.handleURL(url)\n    …\n}\n\n// OR //\n\n//Universal-Linking in Redirect-URI\noverride func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([Any]?) -> Void) -> Bool {\n    if(userActivity.activityType == NSUserActivityTypeBrowsingWeb) {\n        let url = userActivity.webpageURL!;\n        let isDcalUrl:Bool = DCAL.handleURL(url: url);\n    }\n    ...\n}\n```\n#### Android\n\nDamit das DCAL den Redirect bei der Anmeldung über das OAuth-Verfahren verifizieren kann, muss die MainActivity-Funktion onNewIntent wie folgt erweitert werden:\n\n```\n//URL-Scheme handled by onNewIntent in the MainActivity\noverride fun onNewIntent(intent: Intent?) {\n    super.onNewIntent(intent)\n    if (intent != null) {\n        if (intent.data != null) {\n            DCAL.handleUrl(intent.data)\n        }\n    }\n}\n```\n### DCAL Zustände\n\nDas DCAL mobil kann folgende Zustände annehmen:\n\n- Initialized\n- Uninitialized\n- LoggedIn\n- LoggedOut\n\n### DCAL API\n\n#### Initialisierung DCAL\n\nDCAL kann entweder beim Start der App oder vor der Authentifizierung des Benutzers beim DATEV-Rechenzentrum initialisiert werden.\n\nWir empfehlen, die Initialisierung beim Starten der App durchzuführen.\n\n```\n## iOS & Android #\nDCAL.initialize([Parameter]) -> DCAL_State\n```\nGibt den aktuellen Zustand des DCAL (DCAL_State) zurück. Der DCAL wird mit den Informationen aus den Parametern initialisiert.\n\n#### Rückgabewerte\n| State                                  | Beschreibung                                                                                    |\n| -------------------------------------- | ---------------------------------------------------------------------------------------------- |\n| initialized                            | DCAL ist initialisiert.                                                                           |\n| uninitialized                          | DCAL konnte nicht initialisiert werden, weil z.B. die Konfigurationsdatei nicht gefunden werden konnte. |\n| initialized &#x007C;&#x007C; loggedIn  | DCAL ist bereits initialisiert, und der Benutzer ist bereits mit DATEV angemeldet.                    |\n| initialized &#x007C;&#x007C; loggedOut | DCAL ist bereits initialisiert, und der Benutzer ist nicht mit DATEV angemeldet.                         |\n\n#### Login\n\n```\n## iOS & Android #\nDCAL.requestLogin()\n```\n\nDie Authentifizierung des Nutzers und die Autorisierung der App beim DATEV-Rechenzentrum werden in einem asynchronen Prozess angestoßen.\n\nWenn die Anmeldeklasse für DCAL authDelegate registriert ist, wird die Anmeldeklasse über die Delegatenmethode `dcalAuthStateChanged` über eine DCAL-Zustandsänderung informiert. Die Methode kann die folgenden Parameter enthalten:\n\n\n| Parameter | Value                                  | Beschreibung                                                             |\n| --------- | -------------------------------------- | ----------------------------------------------------------------------- |\n| state     | initialized &#x007C;&#x007C; loggedOut | DCAL ist bereits initialisiert, und der Benutzer ist nicht mit DATEV angemeldet.          |\n| state     | initialized &#x007C;&#x007C; loggedIn  | DCAL ist bereits initialisiert, und der Benutzer ist erfolgreich mit DATEV angemeldet.  |\n| state     | uninitialized                          | DCAL ist initialisiert.                                                  |\n| error     | ...                                    | ...                                                                     |\n\nBeispiel für die Registrierung einer Anmeldeklasse für das DCAL authDelegate:\n\n```\n## iOS #\nDCAL.authDelegate = self\n\n## Android #\nDCAL.authDelegate = this\n```\n\n#### Logout\n\n```\nDCAL.requestLogout()\n```\n\nDer Benutzer wird in einem asynchronen Prozess aus dem DATEV-Rechenzentrum abgemeldet. Die App ist dann nicht mehr berechtigt, Datenaustausch mit dem DATEV-Rechenzentrum zu betreiben.\n\nWenn die Anmeldeklasse für DCAL authDelegate registriert ist, wird die Anmeldeklasse über die Delegatenmethode `dcalAuthStateChanged` über eine DCAL-Zustandsänderung informiert. Die Methode kann die folgenden Parameter enthalten:\n\n\n| Parameter | Value                                  | Beschreibung                                                             |\n| --------- | -------------------------------------- | ----------------------------------------------------------------------- |\n| state     | initialized &#x007C;&#x007C; loggedOut | DCAL ist bereits initialisiert, und der Benutzer ist nicht mit DATEV angemeldet.          |\n| state     | initialized &#x007C;&#x007C; loggedIn  | DCAL ist bereits initialisiert, und der Benutzer ist erfolgreich mit DATEV angemeldet.  |\n| state     | uninitialized                          | DCAL ist initialisiert.                                                  |\n| error     | ...                                    | ...                                                                     |\n\nBeispiel für die Registrierung einer Anmeldeklasse für das DCAL authDelegate:\n\n```\n## iOS #\nDCAL.authDelegate = self\n\n## Android #\nDCAL.authDelegate = this\n```\n\n#### Erzeugen einer URLSession unter iOS\n```\nDCAL.createSession() throws -> URLSession //new\n```\n\n```\nDCAL.session() -> URLSession  //deprecated since DCAL Version 2.1.1\n```\n\nDiese Funktion erstellt eine URLSession mit Anpassungen, um eine sichere Kommunikation mit dem DATEV-Rechenzentrum zu ermöglichen.\n\n#### Android Kommunikation (Voraussetzung: DCAL Version >= 2.0.0)\n\nFür die Kommunikation mit DATEV-APIs passt das DCAL die native Android Volley-API (https://developer.android.com/training/volley) an.\n\n```\nimport com.android.volley.*\n...\nvar datevConnection: DatevConnection? = DatevConnection.getInstance(this);\n\n// GET-Request\ndatevConnection.getData(url: String, header:Map? = null, successListener:Response.Listener, errorListener: Response.ErrorListener);\n\n// POST-Request\ndatevConnection.postData(url: String, data: ByteArray, header:Map?, successListener:Response.Listener, errorListener: Response.ErrorListener);\n```\n\n#### Erzeugen einer URLConnection unter Android (deprecated seit DCAL Version 2.0.0)\n\n```\nDatevUrlConnection([Parameter]) -> DatevUrlConnection\n```\n\nDiese Funktion erstellt eine DatevUrlConnection mit Einstellungen, die eine sichere Kommunikation mit dem DATEV-Rechenzentrum ermöglichen.\n\n#### SessionDelegate\n```\n## iOS #\nDCAL.sessionDelegate = self\nfunc dcalSession(totalBytesExpectedToSend: Int, totalBytesSent: Int, totalBytesExpectedToReceive: Int, didReceive: Int) {\n...\n}\n\n## Android #\nDCAL.sessionDelegate = this\noverride fun dcalSession(totalBytesExpectedToSend: Long, totalBytesSent: Long, totalBytesExpectedToReceive: Long, totalBytesReceived: Long) {\n...\n}\n```\n\nInformiert den Delegarten regelmäßig über den Fortschritt des Sendens/Empfangens von Inhalten zum/vom Server.\n\n#### Abfragen des DCAL States\n```\nDCAL.getState() -> DCAL_State\n```\n\nGibt den aktuellen DCAL-Status zurück.\n\n#### Reset DCAL\n\n```\nDCAL.clean() -> DCAL_State\n```\n\nSetzt das DCAL auf den Zustand “uninitialized” zurück.\n\n#### Ist SmartLogin verfügbar\nPrüfen Sie, ob die SmartLogin-App auf dem Gerät verfügbar ist.\n\n```\nDCAL.isSmartLoginAvailable() -> Bool\n```\n\nGibt einen booleschen Wert zurück, wenn die SmartLogin-App verfügbar ist.\n\n**iOS only:  \nSie müssen das URL-Schema \"DATEVSmartLogin\" deklarieren. Fügen Sie dazu den Schlüssel LSApplicationQueriesSchemes in die Datei Info.plist Ihrer Anwendung ein. Wenn Sie diese Methode ohne das deklarierte DATEVSmartLogin-URL-Schema aufrufen, gibt diese Methode immer false zurück, unabhängig davon, ob die SmartLogin-App installiert ist oder nicht.**\n\n### Changelog\nDie DCAL-Bibliothek gibt es in verschiedenen Versionen. Die Änderungen in jeder Version sind hier aufgeführt.\n#### iOS\n\n| DCAL Version | Changes                                                       | Date       |\n| ------------ | ------------------------------------------------------------- | ---------- |\n| 2.4.4        | Aktualisierung OpenSSL, LibCURL und NGHTTP                    | 2024-04-26 |\n| 2.4.3        | Fehlerbehebung + iOS Min Target 14                            | 2024-01-31 |\n| 2.4.0        | Support new Format for Packaging Frameworks (xcframework); Upgrade OpenSSL to 1.1.1l; including bug and security fixes | 2021-11-11 |\n| 2.1.2        | Swift 5.1.3 Support                                           | 2020-15-01 |\n\n#### Android\n\n| DCAL Version | Changes                                                       | Date       |\n| ------------ | ------------------------------------------------------------- | ---------- |\n| 2.4.3        | Aktualisierung OpenSSL, LibCURL und NGHTTP                    | 2024-04-26 |\n| 2.4.3        | Fehlerbehebung                                                | 2024-01-31 |\n| 2.4.0        | Upgrade OpenSSL to 1.1.1l; including bug and security fixes   | 2021-11-11 |\n| 2.1.1        | Fixed bug where access token is not being refreshed correctly | 2019-11-21 |\n","documentId":"iuyshyaz8q21w4vmy3wkwnar","id":52,"localization":null,"sort":1,"title":"Authentifizierung Cloud Integration"},"sort":1,"title":"Authentication cloud integration"}