### Install ActiveLogin BankID NuGet Package Source: https://github.com/activelogin/activelogin.authentication/blob/main/docs/articles/bankid.md Install the ASP.NET Core BankID authentication package using the .NET CLI. ```console dotnet add package ActiveLogin.Authentication.BankId.AspNetCore ``` -------------------------------- ### Payment Controller Example Source: https://github.com/activelogin/activelogin.authentication/blob/main/docs/articles/bankid.md A sample controller demonstrating how to use IBankIdPaymentConfigurationProvider and IBankIdPaymentService to initiate and handle payment flows. ```csharp [AllowAnonymous] public class PaymentController : Controller { private readonly IBankIdPaymentConfigurationProvider _bankIdPaymentConfigurationProvider; private readonly IBankIdPaymentService _bankIdPaymentService; public PaymentController(IBankIdPaymentConfigurationProvider bankIdPaymentConfigurationProvider, IBankIdPaymentService bankIdPaymentService) { _bankIdPaymentConfigurationProvider = bankIdPaymentConfigurationProvider; _bankIdPaymentService = bankIdPaymentService; } public async Task Index() { var configurations = await _bankIdPaymentConfigurationProvider.GetAllConfigurationsAsync(); var providers = configurations .Where(x => x.DisplayName != null) .Select(x => new ExternalProvider(x.DisplayName ?? x.Key, x.Key)); var viewModel = new BankIdViewModel(providers, $"{Url.Action(nameof(Index))}"); return View(viewModel); } [AllowAnonymous] [HttpPost("Payment")] public IActionResult Payment([FromQuery] string provider, [FromForm] PaymentRequestModel model) { ArgumentNullException.ThrowIfNull(model, nameof(model)); var recipientName = "Demo Merchant Name"; var amount = "100,00"; var currency = "SEK"; var props = new BankIdPaymentProperties(TransactionType.card, recipientName) { Money = new(amount, currency), UserVisibleData = "Demo of Payment with Active Login.", Items = { {"scheme", provider}, {"transactionType", nameof(TransactionType.card)}, {"recipientName", recipientName}, {"amount", amount}, {"currency", currency} }, }; var returnPath = $"{Url.Action(nameof(Callback))}?provider={provider}"; return this.BankIdInitiatePayment(props, returnPath, provider); } [AllowAnonymous] [HttpPost] public async Task Callback(string provider) { var result = await _bankIdPaymentService.GetPaymentResultAsync(provider); if (result?.Succeeded != true || result.BankIdCompletionData == null) { throw new Exception("Payment error"); } return View("Result", new PaymentResultViewModel( result.BankIdCompletionData.User.PersonalIdentityNumber, result.BankIdCompletionData.User.Name, result.BankIdCompletionData.Device.IpAddress, result.Properties.Items["transactionType"] ?? string.Empty, result.Properties.Items["recipientName"] ?? string.Empty, result.Properties.Items["amount"] ?? null, result.Properties.Items["currency"] ?? null ) ); } } ``` -------------------------------- ### Basic BankID Setup in .NET Source: https://github.com/activelogin/activelogin.authentication/blob/main/README.md This snippet shows the minimal configuration for adding BankID authentication and signing capabilities to a .NET application. It includes common setup, authentication, and signing configurations. ```csharp // Common services .AddBankId(bankId => { bankId.UseTestEnvironment(); }); // Auth services .AddAuthentication() .AddBankIdAuth(bankId => { bankId.AddSameDevice(); }); // Sign services .AddBankIdSign(bankId => { bankId.AddSameDevice(); }); ``` -------------------------------- ### Build All Projects Source: https://github.com/activelogin/activelogin.authentication/blob/main/README.md Use this command to build all projects within the Active Login solution. Ensure you have the .NET SDK and runtime installed. ```console dotnet build ``` -------------------------------- ### Run Standalone MVC Sample Source: https://github.com/activelogin/activelogin.authentication/blob/main/README.md Navigate to the Standalone.MvcSample directory and run this command to start the sample application. It's configured for the test environment by default. ```console dotnet run ``` -------------------------------- ### BankID Verify API Controller Example Source: https://github.com/activelogin/activelogin.authentication/blob/main/docs/articles/bankid.md An example MVC Controller demonstrating how to use the BankID Verify API to process QR code content and retrieve user verification details, specifically the personal identity number. ```csharp public class VerifyRequestModel { public string QrCodeContent { get; set; } = string.Empty; } public class VerifyController : Controller { private readonly IBankIdVerifyApiClient _bankIdVerifyApiClient; public VerifyController(IBankIdVerifyApiClient bankIdVerifyApiClient) { _bankIdVerifyApiClient = bankIdVerifyApiClient; } [HttpPost("/verify/api")] public async Task> Verify([FromBody] VerifyRequestModel model) { // Minimalistic sample implementation ArgumentNullException.ThrowIfNull(model, nameof(model)); if (string.IsNullOrEmpty(model.QrCodeContent)) { throw new ArgumentNullException(nameof(model.QrCodeContent)); } var verifyResult = await _bankIdVerifyApiClient.VerifyAsync(model.QrCodeContent); return verifyResult.User.PersonalIdentityNumber; } ``` -------------------------------- ### BankID Sign Controller Example Source: https://github.com/activelogin/activelogin.authentication/blob/main/docs/articles/bankid.md A minimal controller demonstrating how to use IBankIdSignConfigurationProvider to list configurations and IBankIdSignService to initiate and resolve sign flows. This sample includes methods for displaying available providers, initiating a sign request with custom properties, and handling the callback. ```csharp [AllowAnonymous] public class SignController : Controller { private readonly IBankIdSignConfigurationProvider _bankIdSignConfigurationProvider; private readonly IBankIdSignService _bankIdSignService; public SignController(IBankIdSignConfigurationProvider bankIdSignConfigurationProvider, IBankIdSignService bankIdSignService) { _bankIdSignConfigurationProvider = bankIdSignConfigurationProvider; _bankIdSignService = bankIdSignService; } public async Task Index() { var configurations = await _bankIdSignConfigurationProvider.GetAllConfigurationsAsync(); var providers = configurations .Where(x => x.DisplayName != null) .Select(x => new ExternalProvider(x.DisplayName ?? x.Key, x.Key)); var viewModel = new BankIdViewModel(providers, "~/"); return View(viewModel); } public IActionResult Sign(string provider) { var props = new BankIdSignProperties("The info displayed for the user") // The user visible data { UserNonVisibleData = new byte[1024], // Whatever data you want to sign UserVisibleDataFormat = BankIdUserVisibleDataFormats.SimpleMarkdownV1, // The format of the user visible data, use empty or the markdown constant Items = { {"returnUrl", "~"}, {"scheme", provider} } RequirePinCode = true, RequireMrtd = true RequiredPersonalIdentityNumber = new PersonalIdentityNumber(1999, 8, 7, 239, 1) }; var returnPath = $"{Url.Action(nameof(Callback))}?provider={provider}"; return this.BankIdInitiateSign(props, returnPath, provider); } [HttpPost] public async Task Callback(string provider) { var result = await _bankIdSignService.GetSignResultAsync(provider); if (result?.Succeeded != true) { throw new Exception("Sign error"); } // Parse these to store the signed values var ocspResponse = result.BankIdCompletionData?.OcspResponse; var signature = result.BankIdCompletionData?.Signature; return Redirect(result.Properties?.Items["returnUrl"] ?? "~/"); } } ``` -------------------------------- ### Registering BankID Authentication with Custom Claims Transformer Source: https://github.com/activelogin/activelogin.authentication/blob/main/docs/articles/bankid.md Example of registering BankID authentication services and adding a custom claims transformer. ```csharp services .AddAuthentication() .AddBankIdAuth(bankId => { bankId.AddSameDevice(); bankId.AddClaimsTransformer(); }); ``` -------------------------------- ### Configure BankID for Production Environment Source: https://github.com/activelogin/activelogin.authentication/blob/main/docs/articles/bankid.md Configure ActiveLogin for production use, including event listeners, client certificates from Azure Key Vault, and device detection methods. This example also shows how to add support for same-device and other-device authentications. ```csharp services .AddBankId(bankId => { bankId .AddApplicationInsightsEventListener(options => { options.LogUserPersonalIdentityNumberHints = true; }) .UseProductionEnvironment() .UseClientCertificateFromAzureKeyVault(configuration.GetSection("ActiveLogin:BankId:ClientCertificate")) .AddSameDevice() .AddOtherDevice() .UseQrCoderQrCodeGenerator() .UseUaParserDeviceDetection(); }); services .AddAuthentication() .AddBankIdAuth(bankId => { bankId .UseProductionEnvironment(); }); ``` -------------------------------- ### Register BankID Services with Test Environment Source: https://github.com/activelogin/activelogin.authentication/blob/main/docs/articles/bankid.md Configure BankID services for testing, including adding a debug event listener and selecting the test environment. This setup is required before using BankID APIs. ```csharp services .AddBankId(bankId => { bankId .AddDebugEventListener() .UseTestEnvironment(); }); ``` -------------------------------- ### Full Production BankID Configuration with Azure KeyVault Source: https://github.com/activelogin/activelogin.authentication/blob/main/docs/articles/bankid.md A comprehensive example of configuring BankID for production, including fetching client certificates from Azure KeyVault, using a QR code generator, and device detection. ```csharp services .AddBankId(bankId => { .UseProductionEnvironment() .UseClientCertificateFromAzureKeyVault(configuration.GetSection("ActiveLogin:BankId:ClientCertificate")) .UseQrCoderQrCodeGenerator() .UseUaParserDeviceDetection(); }); services .AddAuthentication() .AddBankIdAuth(bankId => { bankId .AddSameDevice() .AddOtherDevice(); }); ``` -------------------------------- ### BankID Configuration in JSON Source: https://github.com/activelogin/activelogin.authentication/blob/main/docs/articles/bankid.md Example JSON configuration for BankID client certificate settings, specifying Azure Key Vault URI and secret name. ```json { "ActiveLogin:BankId:ClientCertificate": { "AzureKeyVaultUri": "TODO-ADD-YOUR-VALUE", "AzureKeyVaultSecretName": "TODO-ADD-YOUR-VALUE" } } ``` -------------------------------- ### Register BankID and Sign Services Source: https://github.com/activelogin/activelogin.authentication/blob/main/docs/articles/bankid.md Register the common BankID logic and the sign-specific configuration, including environment, certificates, and devices. This setup is required before using the sign services. ```csharp services .AddBankId(bankId => { bankId.AddDebugEventListener(); bankId.UseQrCoderQrCodeGenerator(); bankId.UseUaParserDeviceDetection(); bankId.UseSimulatedEnvironment(); }); services .AddBankIdSign(bankId => { bankId.AddSameDevice(BankIdSignDefaults.SameDeviceConfigKey, "BankID (SameDevice)", options => { }); bankId.AddOtherDevice(BankIdSignDefaults.OtherDeviceConfigKey, "BankID (OtherDevice)", options => { }); }); ``` -------------------------------- ### Configure BankID with QRCoder Generator Source: https://github.com/activelogin/activelogin.authentication/blob/main/src/ActiveLogin.Authentication.BankId.QRCoder/README.md Use this extension method to configure BankID authentication within your service collection, specifying QRCoder as the QR code generator. Ensure the QRCoder library is installed. ```csharp services .AddBankId(bankId => { bankId.UseQrCoderQrCodeGenerator(); }); ``` -------------------------------- ### Query All Active Login BankId Info Source: https://github.com/activelogin/activelogin.authentication/blob/main/docs/articles/monitor.md Retrieves comprehensive details for all events starting with 'ActiveLogin_BankId_'. Useful for a broad overview of login activities. ```kql customEvents | where name startswith "ActiveLogin_BankId_" | project timestamp, client_City, client_CountryOrRegion, Event_Name = name, Event_TypeId = tostring(customDimensions.AL_Event_TypeId), Event_Severity = tostring(customDimensions.AL_Event_Severity), Error_ErrorReason = tostring(customDimensions.AL_Error_ErrorReason), BankId_BankId_Options_LaunchType = tostring(customDimensions.AL_BankId_Options_LaunchType), BankId_Options_UseQrCode = tostring(customDimensions.AL_BankId_Options_UseQrCode), BankId_ErrorCode = tostring(customDimensions.AL_BankId_ErrorCode), BankId_ErrorDetails = tostring(customDimensions.AL_BankId_ErrorDetails), BankId_OrderRef = tostring(customDimensions.AL_BankId_OrderRef), BankId_CollectHintCode = tostring(customDimensions.AL_BankId_CollectHintCode), BankId_User_CertNotBefore = tostring(customDimensions.AL_BankId_User_CertNotBefore), BankId_User_CertNotAfter = tostring(customDimensions.AL_BankId_User_CertNotAfter), BankId_User_DeviceIpAddress = tostring(customDimensions.AL_BankId_User_DeviceIpAddress), User_Device_Browser = tostring(customDimensions.AL_User_Device_Browser), User_Device_Os = tostring(customDimensions.AL_User_Device_Os), User_Device_Type = tostring(customDimensions.AL_User_Device_Type), User_Device_OsVersion = tostring(customDimensions.AL_User_Device_OsVersion), User_Name = tostring(customDimensions.AL_User_Name), User_GivenName = tostring(customDimensions.AL_User_GivenName), User_Surname = tostring(customDimensions.AL_User_Surname), User_SwedishPersonalIdentityNumber = tostring(customDimensions.AL_User_SwedishPersonalIdentityNumber), User_DateOfBirthHint = tostring(customDimensions.AL_User_DateOfBirthHint), User_AgeHint = tostring(customDimensions.AL_User_AgeHint), User_GenderHint = tostring(customDimensions.AL_User_GenderHint), ProductName = tostring(customDimensions.AL_ProductName), ProductVersion = tostring(customDimensions.AL_ProductVersion), BankId_ApiEnvironment = tostring(customDimensions.AL_BankId_ApiEnvironment), BankId_ApiVersion = tostring(customDimensions.AL_BankId_ApiVersion) | order by timestamp desc | render table ``` -------------------------------- ### Configure Simulated BankID Environment (No Config) Source: https://github.com/activelogin/activelogin.authentication/blob/main/docs/articles/bankid.md Sets up the simulated BankID environment without any specific configuration for user details. ```csharp services .AddBankId(bankId => { bankId.UseSimulatedEnvironment(); }); ``` -------------------------------- ### Add Custom Browser via Implementation Source: https://github.com/activelogin/activelogin.authentication/blob/main/docs/articles/bankid.md Integrate custom browser configurations by implementing the IBankIdLauncherCustomAppCallback interface for advanced scenarios. ```csharp services .AddBankId(bankId => { // ... bankId.AddCustomBrowser(); // ... }); ``` -------------------------------- ### Run All Tests Source: https://github.com/activelogin/activelogin.authentication/blob/main/README.md Execute this command in the root directory to run all unit tests for the Active Login solution. This helps verify the integrity of the codebase. ```console dotnet test ``` -------------------------------- ### Configure BankID for Production Environment Source: https://github.com/activelogin/activelogin.authentication/blob/main/docs/articles/bankid.md Enables the BankID service to use the production environment. Requires client certificates to be prepared beforehand. ```csharp services .AddBankId(bankId => { bankId.UseProductionEnvironment(); }); ``` -------------------------------- ### Device OS and Browser Distribution Source: https://github.com/activelogin/activelogin.authentication/blob/main/docs/articles/monitor.md Summarizes the distribution of device operating systems and browsers for specific events. Use this to understand user device landscape. ```kql customEvents | where name == "ActiveLogin_BankId_AspNetChallengeSuccess" | project DeviceOs = tostring(customDimensions.AL_User_Device_Os), DeviceBrowser = tostring(customDimensions.AL_User_Device_Browser) | project DeviceOsAndDeviceBrowser = strcat(DeviceOs, ' - ', DeviceBrowser) | summarize count() by DeviceOsAndDeviceBrowser | render piechart ``` -------------------------------- ### Configure BankID with Azure Key Vault Client Certificate Source: https://github.com/activelogin/activelogin.authentication/blob/main/src/ActiveLogin.Authentication.BankId.AzureKeyVault/README.md Use the extension method to configure BankID authentication with client certificates from Azure Key Vault. This snippet shows the basic setup within a .NET service collection. ```csharp services .AddBankId(bankId => { bankId.UseClientCertificateFromAzureKeyVault(Configuration.GetSection("ActiveLogin:BankId:ClientCertificate")); }); ``` -------------------------------- ### Count BankId Launch Types Source: https://github.com/activelogin/activelogin.authentication/blob/main/docs/articles/monitor.md Summarizes the count of 'SameDevice' vs 'OtherDevice' launch types for successful BankId challenges. Helps understand user interaction patterns. ```kql customEvents | where name == "ActiveLogin_BankId_AspNetChallengeSuccess" | project LaunchType = tostring(customDimensions.AL_BankId_Options_LaunchType) | summarize count() by LaunchType | render piechart ``` -------------------------------- ### Configure Application Insights Event Listener Options Source: https://github.com/activelogin/activelogin.authentication/blob/main/docs/articles/bankid.md Configures the Application Insights event listener with custom options to control which user and device data is logged. For example, you can disable logging of personal identity numbers or enable logging of hardware IDs. ```csharp services .AddBankId(bankId => { bankId.AddApplicationInsightsEventListener(options => { options.LogUserPersonalIdentityNumber = false; options.LogUserPersonalIdentityNumberHints = true; options.LogUserNames = false; options.LogDeviceIpAddress = false; options.LogDeviceUniqueHardwareId = true; options.LogUserBankIdIssueDate = true; // And more... }); }); ``` -------------------------------- ### Use Client Certificate from Custom Source Source: https://github.com/activelogin/activelogin.authentication/blob/main/docs/articles/bankid.md Configure BankID authentication to use a client certificate loaded from a custom source, such as a file. ```csharp services.AddBankId(bankId => { bankId .UseProductionEnvironment() .UseClientCertificate(() => new X509Certificate2( ... )) ... }); ``` -------------------------------- ### Configure BankID for Development (Simulated Environment) Source: https://github.com/activelogin/activelogin.authentication/blob/main/docs/articles/bankid.md Configure ActiveLogin to use a simulated BankID environment for development and testing. This includes adding a debug event listener. ```csharp services .AddBankId(bankId => { bankId .AddDebugEventListener() .UseSimulatedEnvironment(); }); services .AddAuthentication() .AddBankIdAuth(bankId => { bankId .AddSameDevice(); }); ``` -------------------------------- ### Count BankId Device Type and Device OS Combinations Source: https://github.com/activelogin/activelogin.authentication/blob/main/docs/articles/monitor.md Examines the combinations of device types and operating systems used during successful BankId challenges. Helps identify common platform usage. ```kql customEvents | where name == "ActiveLogin_BankId_AspNetChallengeSuccess" | project DeviceType = tostring(customDimensions.AL_User_Device_Type), DeviceOs = tostring(customDimensions.AL_User_Device_Os) | project DeviceAndDeviceOs = strcat(DeviceType, ' - ', DeviceOs) | summarize count() by DeviceAndDeviceOs | render piechart ``` -------------------------------- ### Sample BankID Event Listener Implementation Source: https://github.com/activelogin/activelogin.authentication/blob/main/docs/articles/bankid.md A sample implementation of the IBankIdEventListener interface to handle BankID events. This listener logs the event type and severity to the console. ```csharp public class BankIdSampleEventListener : IBankIdEventListener { public Task HandleAsync(BankIdEvent bankIdEvent) { Console.WriteLine($"{bankIdEvent.EventTypeName}: {bankIdEvent.EventSeverity}"); return Task.CompletedTask; } } ``` -------------------------------- ### Configure BankID for Development Source: https://github.com/activelogin/activelogin.authentication/blob/main/src/ActiveLogin.Authentication.BankId.AspNetCore/README.md Use this snippet to configure BankID services and authentication handlers for a development environment, enabling the simulated environment. ```csharp services .AddBankId(bankId => { bankId.UseSimulatedEnvironment(); }); services .AddAuthentication() .AddBankIdAuth(bankId => { bankId.AddSameDevice(); }); ``` -------------------------------- ### Import Namespaces for BankId Extension Methods Source: https://github.com/activelogin/activelogin.authentication/blob/main/BREAKINGCHANGES.md After namespace changes, you may need to add these using statements in your Program.cs file to access BankId extension methods. ```csharp using ActiveLogin.Authentication.BankId.AspNetCore.Auth; using ActiveLogin.Authentication.BankId.AspNetCore.Sign; using ActiveLogin.Authentication.BankId.AzureKeyVault; using ActiveLogin.Authentication.BankId.AzureMonitor; using ActiveLogin.Authentication.BankId.Core; using ActiveLogin.Authentication.BankId.QrCoder; using ActiveLogin.Authentication.BankId.UaParser; ``` -------------------------------- ### Configure BankID for Production Source: https://github.com/activelogin/activelogin.authentication/blob/main/src/ActiveLogin.Authentication.BankId.AspNetCore/README.md This snippet shows how to configure BankID for a production environment, including Application Insights logging, Azure Key Vault client certificates, and QR code generation. ```csharp services .AddBankId(bankId => { bankId .AddApplicationInsightsEventListener(options => { options.LogUserPersonalIdentityNumberHints = true; options.LogCertificateDates = true; }) .UseProductionEnvironment() .UseClientCertificateFromAzureKeyVault(Configuration.GetSection("ActiveLogin:BankId:ClientCertificate")) .UseQrCoderQrCodeGenerator(); }); services .AddAuthentication() .AddBankIdAuth(bankId => { bankId .AddSameDevice() .AddOtherDevice(); }); ``` -------------------------------- ### Register Client Certificates for Multi-Tenant Scenarios Source: https://github.com/activelogin/activelogin.authentication/blob/main/BREAKINGCHANGES.md When registering multiple client certificates for multi-tenant applications, use the AddClientCertificate methods. The UseClientCertificate method will overwrite previously registered certificates. ```csharp .AddClientCertificate() .AddClientCertificateFromAzureKeyVault() ``` -------------------------------- ### Registering BankID with QR Code and Device Detection Source: https://github.com/activelogin/activelogin.authentication/blob/main/BREAKINGCHANGES.md This snippet shows how to register BankID authentication services, including configuration for QR code generation and device detection. Ensure common configuration is registered before authentication-specific configuration. ```csharp services .AddBankId(bankId => { bankId.UseQrCoderQrCodeGenerator(); bankId.UseUaParserDeviceDetection(); ... }); services.AddAuthentication() .AddCookie() .AddBankIdAuth(bankId => { bankId.AddSameDevice(); bankId.AddOtherDevice(); }); ``` -------------------------------- ### Count BankId Launch Type and Device Type Combinations Source: https://github.com/activelogin/activelogin.authentication/blob/main/docs/articles/monitor.md Analyzes the combined usage of launch types (SameDevice/OtherDevice) and device types for successful BankId challenges. Useful for detailed user behavior analysis. ```kql customEvents | where name == "ActiveLogin_BankId_AspNetChallengeSuccess" | project DeviceType = tostring(customDimensions.AL_User_Device_Type), LaunchType = tostring(customDimensions.AL_BankId_Options_LaunchType) | project DeviceTypeAndLaunchType = strcat(DeviceType, ' - ', LaunchType) | summarize count() by DeviceTypeAndLaunchType | render piechart ``` -------------------------------- ### Register BankID and Payment Services Source: https://github.com/activelogin/activelogin.authentication/blob/main/docs/articles/bankid.md Configure BankID and BankID Payment services, including debug listeners, QR code generation, device detection, and simulated environments. ```csharp services .AddBankId(bankId => { bankId.AddDebugEventListener(); bankId.UseQrCoderQrCodeGenerator(); bankId.UseUaParserDeviceDetection(); bankId.UseSimulatedEnvironment(); }); services.AddBankIdPayment(bankId => { bankId.AddSameDevice(BankIdPaymentDefaults.SameDeviceConfigKey, "BankID (SameDevice)", options => { }); bankId.AddOtherDevice(BankIdPaymentDefaults.OtherDeviceConfigKey, "BankID (OtherDevice)", options => { }); }); ``` -------------------------------- ### Enable Static File Support Source: https://github.com/activelogin/activelogin.authentication/blob/main/BREAKINGCHANGES.md To serve the client-side stylesheet and JavaScript files, ensure static file support is enabled in your application pipeline. ```csharp app.UseStaticFiles(); ``` -------------------------------- ### Configure Simulated BankID Environment (Custom Person Info) Source: https://github.com/activelogin/activelogin.authentication/blob/main/docs/articles/bankid.md Configures the simulated BankID environment with custom faked name and personal identity number. ```csharp services .AddBankId(bankId => { bankId.UseSimulatedEnvironment("Alice", "Smith", "199908072391") }); ``` -------------------------------- ### Configure BankID with Azure Key Vault Certificate Source: https://github.com/activelogin/activelogin.authentication/blob/main/docs/articles/bankid.md Set up BankID to use a production environment and load a client certificate from Azure Key Vault. ```csharp services.AddBankId(bankId => { bankId .UseProductionEnvironment() .UseClientCertificateFromAzureKeyVault(configuration.GetSection("ActiveLogin:BankId:ClientCertificate")) ... ``` -------------------------------- ### Configure BankID with UAParser Device Detection Source: https://github.com/activelogin/activelogin.authentication/blob/main/src/ActiveLogin.Authentication.BankId.UAParser/README.md Use this extension method to enable device detection for BankID authentication via the ua_parser C# Library. Ensure `Microsoft.Extensions.DependencyInjection` is available. ```csharp services .AddAuthentication() .AddBankId(bankId => { bankId.UseUaParserDeviceDetection(); }); ``` -------------------------------- ### Add BankID Authentication Schemas Source: https://github.com/activelogin/activelogin.authentication/blob/main/docs/articles/bankid.md Adds both 'Same Device' and 'Other Device' authentication schemas for BankID. ```csharp services .AddAuthentication() .AddBankIdAuth(bankId => { bankId .AddSameDevice() .AddOtherDevice(); }); ``` -------------------------------- ### Default Device Data Configuration for Web Source: https://github.com/activelogin/activelogin.authentication/blob/main/docs/articles/bankid.md Configures BankID to use default web device data resolution when no custom implementation is provided. Sets the device type to Web and uses default resolvers. ```csharp services .AddBankId(bankId => { bankId.UseDeviceData(config => { // Set the device type for the request config.DeviceType = BankIdEndUserDeviceType.Web; // Use the default resolver factory config.UseResolverFactory(); // Add the default resolver for Web config.UseDeviceResolver(); }); }); ``` -------------------------------- ### Configure BankID Options to Enable Risk Level Return Source: https://github.com/activelogin/activelogin.authentication/blob/main/BREAKINGCHANGES.md Use this snippet to configure BankID options to enable `BankIdReturnRisk`. This allows your application to handle the risk level returned by BankID, as direct blocking is no longer supported. ```csharp services.Configure(options => { options.BankIdReturnRisk = true; }); ``` -------------------------------- ### Configure BankID for Test Environment Source: https://github.com/activelogin/activelogin.authentication/blob/main/docs/articles/bankid.md Enables the BankID service to use the test environment. This is the default behavior and automatically registers root and client certificates. ```csharp services .AddBankId(bankId => { bankId.UseTestEnvironment(); }); ``` -------------------------------- ### Use Client Certificate from Custom Service Source: https://github.com/activelogin/activelogin.authentication/blob/main/docs/articles/bankid.md Configure BankID authentication to use a client certificate retrieved from a custom certificate service within the service provider. ```csharp services.AddBankId(bankId => { bankId .UseProductionEnvironment() .UseClientCertificate(sp => sp.GetRequiredService().GetCertificate()) ... }); ``` -------------------------------- ### Custom Device Data Configuration for Web Source: https://github.com/activelogin/activelogin.authentication/blob/main/docs/articles/bankid.md Configures BankID with custom device data resolution for web requests. Allows specifying custom resolver factories and resolvers. ```csharp services .AddBankId(bankId => { bankId.UseDeviceData(config => { // Set the device type for the request config.DeviceType = BankIdEndUserDeviceType.Web; // Use a custom resolver factory // that implements IBankIdEndUserDeviceDataResolverFactory config.UseResolverFactory(); // Add a custom resolver for the device type Web // that implements IBankIdEndUserDeviceDataResolver config.UseDeviceResolver(); }); }); ``` -------------------------------- ### BankId Signing Flow Diagram Source: https://github.com/activelogin/activelogin.authentication/blob/main/docs/articles/bankid-architechture.md Visualizes the steps and interactions within the BankID signing process, from initiating a sign request to completing the callback. ```mermaid graph TD App-->A A[SignController.Index] -->B B[SignController.Sign] -->|IBankIdSignService.InitiateSignAsync|C C[BankIdUiSignController.Init] --> D D([BankIdUiSign/Init.cshtml]) E[BankIdUiSignApiController.Initialize] F[BankIdUiSignApiController.QrCode]-->D G[BankIdUiSignApiController.Status]-->D D-->E D-->F D-->G D-->H H[SignController.Callback] -->|IBankIdSignService.GetSignResultAsync|App ``` -------------------------------- ### Add Custom Browser with Reload Behavior Source: https://github.com/activelogin/activelogin.authentication/blob/main/docs/articles/bankid.md Specify custom browser configurations, including the reload behavior when returning from the BankID app, for specific user agents. ```csharp services .AddBankId(bankId => { // ... bankId.AddCustomBrowserByUserAgent(userAgent => userAgent.Contains("Instagram"), new BankIdLauncherUserAgentCustomBrowser("instagram://", BrowserReloadBehaviourOnReturnFromBankIdApp.Never)); // ... }); ``` -------------------------------- ### Configure Global BankID Options Source: https://github.com/activelogin/activelogin.authentication/blob/main/docs/articles/bankid.md Apply common BankID options globally to all BankID schemes using the Configure method. ```csharp .Configure(options => { options.BankIdRequireMrtd = true; options.BankIdReturnRisk = true; }); ``` -------------------------------- ### Enable Azure Monitor Event Listener for BankID Source: https://github.com/activelogin/activelogin.authentication/blob/main/src/ActiveLogin.Authentication.BankId.AzureMonitor/README.md Call `AddApplicationInsightsEventListener()` to enable logging of BankID authentication events to Azure Monitor. Options can be provided to log sensitive metadata like personal identity number, age, and IP address. ```csharp services .AddBankId(bankId => { bankId.AddApplicationInsightsEventListener(); }); ``` -------------------------------- ### Average User Age Hint Source: https://github.com/activelogin/activelogin.authentication/blob/main/docs/articles/monitor.md Calculates the average age hint for users completing a BankId collection. Useful for demographic analysis. ```kql customEvents | where name == "ActiveLogin_BankId_CollectCompleted" | project UserAgeHint = toint(customMeasurements.AL_User_AgeHint) | summarize AverageUserAge = avg(UserAgeHint) ``` -------------------------------- ### Register Custom QR Code Generator for BankID Source: https://github.com/activelogin/activelogin.authentication/blob/main/docs/articles/bankid.md Register a custom implementation of IBankIdQrCodeGenerator as a service to provide your own QR code generation logic for BankID. ```csharp services.AddTransient(); ``` -------------------------------- ### Specify Client Certificate Format for Test Environment Source: https://github.com/activelogin/activelogin.authentication/blob/main/docs/articles/bankid.md Sets the format of the client certificate used in the BankID test environment. Supports P12, PEM, and legacy PFX formats. ```csharp services .AddBankId(bankId => { bankId.UseTestEnvironment(clientCertificateFormat: TestCertificateFormat.P12); }); ``` -------------------------------- ### Register Custom BankID Launcher Source: https://github.com/activelogin/activelogin.authentication/blob/main/docs/articles/bankid.md Register a custom implementation of IBankIdLauncher as a service to customize how the BankID app is launched on different devices. ```csharp services.AddTransient(); ``` -------------------------------- ### Count Active Login Versions Source: https://github.com/activelogin/activelogin.authentication/blob/main/docs/articles/monitor.md Counts the occurrences of each Active Login product version for successful BankId challenges. Useful for tracking deployed versions. ```kql customEvents | where name == "ActiveLogin_BankId_AspNetChallengeSuccess" | project ActiveLogin_ProductVersion = tostring(customDimensions.AL_ProductVersion) | summarize count() by ActiveLogin_ProductVersion | render piechart ``` -------------------------------- ### Configure BankID with Azure Key Vault Certificate and Ephemeral Key Set Source: https://github.com/activelogin/activelogin.authentication/blob/main/docs/articles/bankid.md Configure BankID to use a production environment and load a client certificate from Azure Key Vault, specifying EphemeralKeySet for certificate handling. ```csharp services.AddBankId(bankId => { bankId .UseProductionEnvironment() .UseClientCertificateFromAzureKeyVault(configuration.GetSection("ActiveLogin:BankId:ClientCertificate"), X509KeyStorageFlags.EphemeralKeySet) ... ``` -------------------------------- ### Daily Successful Logins Chart Source: https://github.com/activelogin/activelogin.authentication/blob/main/docs/articles/monitor.md Renders a column chart showing the count of successful BankId logins per day. Use this to visualize daily login activity. ```kql customEvents | where name == "ActiveLogin_BankId_AspNetAuthenticateSuccess" | project timestamp | summarize Logins = count() by bin(timestamp, 1d) | render columnchart ``` -------------------------------- ### BankID Multi-Tenant Configuration with Custom Certificate Resolver Source: https://github.com/activelogin/activelogin.authentication/blob/main/docs/articles/bankid.md This extension method allows configuring the HTTP client handler to disable connection pooling and set a custom certificate selection callback for multi-tenant scenarios. Use this when multiple BankID certificates need to be managed per tenant. ```csharp internal static class BankIdBuilderExtensions { public static IBankIdBuilder UseClientCertificateResolver(this IBankIdBuilder builder, Func configureClientCertificateResolver) { builder.ConfigureHttpClientHandler((serviceProvider, httpClientHandler) => { httpClientHandler.PooledConnectionLifetime = TimeSpan.Zero; httpClientHandler.SslOptions.LocalCertificateSelectionCallback = (sender, host, certificates, certificate, issuers) => configureClientCertificateResolver(serviceProvider, certificates, host); }); return builder; } } ``` ```csharp public class Startup { public void ConfigureServices(IServiceCollection services) { // ... services .AddBankId(bankId => { bankId .AddClientCertificateFromAzureKeyVault(configuration.GetSection("ActiveLogin:BankId:ClientCertificate1")) .AddClientCertificateFromAzureKeyVault(configuration.GetSection("ActiveLogin:BankId:ClientCertificate2")) .AddClientCertificateFromAzureKeyVault(configuration.GetSection("ActiveLogin:BankId:ClientCertificate3")) .UseClientCertificateResolver((serviceCollection, certificates, hostname) => { // Apply logic here to select the correct certificate return certificates[0]; }); // ... } } } ``` -------------------------------- ### Monthly Successful Logins Table Source: https://github.com/activelogin/activelogin.authentication/blob/main/docs/articles/monitor.md Generates a table showing successful BankId logins aggregated by year and month. Use this for monthly trend monitoring. ```kql let MonthNames = dynamic(["", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]); customEvents | where name == "ActiveLogin_BankId_AspNetAuthenticateSuccess" | project timestamp, Year = datetime_part("Year", timestamp), Month = datetime_part("Month", timestamp) | extend YearAndMonth = strcat(Year, ' ' , tostring(MonthNames[Month])) | order by Year, Month | summarize Logins = count() by YearAndMonth | render table ``` -------------------------------- ### BankId Authentication Flow Diagram Source: https://github.com/activelogin/activelogin.authentication/blob/main/docs/articles/bankid-architechture.md Illustrates the sequence of calls and components involved in the BankID authentication process, from the initial login request to the final authentication callback. ```mermaid graph TD App-->A A[AccountController.Login] -->B B[AccountController.ExternalLogin] -->|Challange|C C[BankIdUiAuthController.Init] --> D D([BankIdUiAuth/Init.cshtml]) E[BankIdUiAuthApiController.Initialize] F[BankIdUiAuthApiController.QrCode]-->D G[BankIdUiAuthApiController.Status]-->D D-->E D-->F D-->G D-->H H[AccountController.ExternalLoginCallback] -->|HttpContext.AuthenticateAsync|App ``` -------------------------------- ### Add Custom Browser by User Agent Source: https://github.com/activelogin/activelogin.authentication/blob/main/docs/articles/bankid.md Configure BankID to use custom return URLs for specific user agents, such as Instagram and Facebook, overriding default behavior. ```csharp services .AddBankId(bankId => { // ... bankId.AddCustomBrowserByUserAgent(userAgent => userAgent.Contains("Instagram"), "instagram://"); bankId.AddCustomBrowserByUserAgent(userAgent => userAgent.Contains("FBAN") || userAgent.Contains("FBAV"), "fb://"); // ... }); ``` -------------------------------- ### BankIdAppApiClient Methods Source: https://github.com/activelogin/activelogin.authentication/blob/main/src/ActiveLogin.Authentication.BankId.Api/README.md Lists the public methods available in the BankIdAppApiClient for handling BankID authentication and signing operations via the App API. ```csharp public class BankIdAppApiClient : IBankIdAppApiClient { public Task AuthAsync(AuthRequest request) { ... } public Task SignAsync(SignRequest request) { ... } public Task PhoneAuthAsync(PhoneAuthRequest request) { ... } public Task PhoneSignAsync(PhoneSignRequest request) { ... } public Task CollectAsync(CollectRequest request) { ... } public Task CancelAsync(CancelRequest request) { ... } } ``` -------------------------------- ### Enable BankID Risk Indication Source: https://github.com/activelogin/activelogin.authentication/blob/main/docs/articles/bankid.md Configure BankID authentication options to enable the retrieval of risk indications from BankID. ```csharp services.Configure(options => { options.BankIdReturnRisk = true; }); ``` -------------------------------- ### Override X509KeyStorageFlags for Test Environment Source: https://github.com/activelogin/activelogin.authentication/blob/main/docs/articles/bankid.md Allows overriding the default X509KeyStorageFlags when loading the embedded client certificate for the test environment. Useful for specific hosting or security requirements. ```csharp services .AddBankId(bankId => { bankId.UseTestEnvironment( keyStorageFlags: X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable ); }); ``` -------------------------------- ### Set Formatted User Visible Data for BankID Auth Source: https://github.com/activelogin/activelogin.authentication/blob/main/docs/articles/bankid.md Configure static user visible data with formatting for BankID authentication requests. Supports SimpleMarkdownV1 for rich text display. ```csharp bankId.UseAuthRequestUserData(authUserData => { var message = new StringBuilder(); message.AppendLine("# Active Login"); message.AppendLine(); message.AppendLine("Welcome to the *Active Login* demo."); authUserData.UserVisibleData = message.ToString(); authUserData.UserVisibleDataFormat = BankIdUserVisibleDataFormats.SimpleMarkdownV1; }); ``` -------------------------------- ### Custom Device Data Configuration for Mobile App Source: https://github.com/activelogin/activelogin.authentication/blob/main/docs/articles/bankid.md Configures BankID with custom device data resolution for mobile app requests. Requires manual configuration of app-specific details. ```csharp services .AddBankId(bankId => { bankId.UseDeviceData(config => { // Set the device type starting the request config.DeviceType = BankIdEndUserDeviceType.App; // Use the default resolver factory to find what device data resolvers to use config.UseResolverFactory(); // Use the default data resolver for the device type app // On app devices (e.g. MAUI, Xamarin, etc.) we need to set the // device data manually at start config.UseDeviceResolver(_ => new BankIdAppDeviceDataResolver() { // App ID or package name AppIdentifier = "com.example.app", // Device operating system DeviceOs = "iOS 16.7.7", // Device model DeviceModelName = "Apple iPhone14,3", // Unique hardware ID DeviceIdentifier = "1234567890" }); }); }); ``` -------------------------------- ### Register Custom BankID Device Detector Source: https://github.com/activelogin/activelogin.authentication/blob/main/docs/articles/bankid.md Register a custom implementation of IBankIdSupportedDeviceDetector as a service to override the default device detection logic used by the BankID launcher. ```csharp services.AddTransient(); ``` -------------------------------- ### Implement Dynamic User Data Resolver for BankID Source: https://github.com/activelogin/activelogin.authentication/blob/main/docs/articles/bankid.md Implement the IBankIdAuthRequestUserDataResolver interface to dynamically generate user data for BankID authentication. This allows for real-time information like timestamps. ```csharp public class BankIdAuthRequestDynamicUserDataResolver : IBankIdAuthRequestUserDataResolver { public Task GetUserDataAsync(BankIdAuthRequestContext authRequestContext, HttpContext httpContext) { return Task.FromResult(new BankIdAuthUserData() { UserVisibleData = "*Time:* " + DateTime.Now.ToLongTimeString(), UserVisibleDataFormat = BankIdUserVisibleDataFormats.SimpleMarkdownV1 }); } } ``` ```csharp services.AddTransient(); ``` -------------------------------- ### Detailed Success Event Log Source: https://github.com/activelogin/activelogin.authentication/blob/main/docs/articles/monitor.md Retrieves detailed information for all successful BankId events. Use this for in-depth troubleshooting of specific successful transactions. ```kql customEvents | where name startswith "ActiveLogin_BankId_" | project timestamp, Event_ShortName = substring(name, 19), Event_TypeId = tostring(customDimensions.AL_Event_TypeId), Event_Severity = tostring(customDimensions.AL_Event_Severity), BankId_Options_LaunchType = tostring(customDimensions.AL_BankId_Options_LaunchType), BankId_Options_UseQrCode = tostring(customDimensions.AL_BankId_Options_UseQrCode), BankId_OrderRef = tostring(customDimensions.AL_BankId_OrderRef), BankId_CollectHintCode = tostring(customDimensions.AL_BankId_CollectHintCode), BankId_User_CertNotBefore = tostring(customDimensions.AL_BankId_User_CertNotBefore), BankId_User_CertNotAfter = tostring(customDimensions.AL_BankId_User_CertNotAfter), BankId_User_DeviceIpAddress = tostring(customDimensions.AL_BankId_User_DeviceIpAddress), User_Device_Browser = tostring(customDimensions.AL_User_Device_Browser), User_Device_Os = tostring(customDimensions.AL_User_Device_Os), User_Device_Type = tostring(customDimensions.AL_User_Device_Type), User_Device_OsVersion = tostring(customDimensions.AL_User_Device_OsVersion), User_Name = tostring(customDimensions.AL_User_Name), User_GivenName = tostring(customDimensions.AL_User_GivenName), User_Surname = tostring(customDimensions.AL_User_Surname), User_SwedishPersonalIdentityNumber = tostring(customDimensions.AL_User_SwedishPersonalIdentityNumber), User_DateOfBirthHint = tostring(customDimensions.AL_User_DateOfBirthHint), User_AgeHint = tostring(customDimensions.AL_User_AgeHint), User_GenderHint = tostring(customDimensions.AL_User_GenderHint), ProductName = tostring(customDimensions.AL_ProductName), ProductVersion = tostring(customDimensions.AL_ProductVersion), BankId_ApiEnvironment = tostring(customDimensions.AL_BankId_ApiEnvironment), BankId_ApiVersion = tostring(customDimensions.AL_BankId_ApiVersion) | where Event_Severity == "Success" | order by timestamp desc | render table ``` -------------------------------- ### ActiveLogin BankId Events by Severity Over Time Source: https://github.com/activelogin/activelogin.authentication/blob/main/docs/articles/monitor.md This query tracks the count of ActiveLogin BankId events, categorized by severity, on a daily basis. It uses binning on the timestamp to group events and renders the trend as a column chart. ```kql customEvents | where name startswith "ActiveLogin_BankId_" | project timestamp, Severity = tostring(customDimensions.AL_Event_Severity) | summarize count() by bin(timestamp, 1d), Severity | render columnchart ``` -------------------------------- ### Weekly Successful Logins Table Source: https://github.com/activelogin/activelogin.authentication/blob/main/docs/articles/monitor.md Displays a table of successful BankId logins aggregated by year and week. Useful for weekly trend analysis. ```kql customEvents | where name == "ActiveLogin_BankId_AspNetAuthenticateSuccess" | project timestamp, Year = datetime_part("Year", timestamp), Week = week_of_year(timestamp) | extend YearAndWeek = strcat(Year, ' ' , Week) | order by Year, Week | summarize Logins = count() by YearAndWeek | render table ``` -------------------------------- ### Custom BankID Facebook App Browser Configuration Source: https://github.com/activelogin/activelogin.authentication/blob/main/docs/articles/bankid.md Implementation of IBankIdLauncherCustomAppCallback to handle custom return URLs and reload behavior for Facebook apps. ```csharp public class BankIdFacebookAppBrowserConfig : IBankIdLauncherCustomAppCallback { private readonly IHttpContextAccessor _httpContextAccessor; public BankIdFacebookAppCallback(IHttpContextAccessor httpContextAccessor) { _httpContextAccessor = httpContextAccessor; } public Task IsApplicable(BankIdLauncherCustomAppCallbackContext context) { var userAgent = _httpContextAccessor.HttpContext?.Request.Headers.UserAgent.FirstOrDefault(); if (string.IsNullOrWhiteSpace(userAgent)) { return Task.FromResult(false); } var isFacebook = userAgent.Contains("FBAN") || userAgent.Contains("FBAV"); return Task.FromResult(isFacebook); } public Task GetCustomAppReturnUrl(BankIdLauncherCustomAppCallbackContext context) { return Task.FromResult( new BankIdLauncherCustomAppCallbackResult("fb://", BrowserReloadBehaviourOnReturnFromBankIdApp.Never, BrowserMightRequireUserInteractionToLaunch.Default) ); } } ``` -------------------------------- ### Register Custom BankId Result Store Source: https://github.com/activelogin/activelogin.authentication/blob/main/docs/articles/bankid.md Registers a custom implementation of IBankIdResultStore to handle completion data after a BankId login flow. The sample implementation logs completion data to the trace log. ```csharp public class BankIdResultSampleLoggerStore : IBankIdResultStore { private readonly EventId _eventId = new EventId(101, "StoreCollectCompletedCompletionData"); private readonly ILogger _logger; public BankIdResultSampleLoggerStore(ILogger logger) { _logger = logger; } public Task StoreCollectCompletedCompletionData(string orderRef, CompletionData completionData) { _logger.LogTrace(_eventId, "Storing completion data for OrderRef '{OrderRef}' (UserPersonalIdentityNumber: '{UserPersonalIdentityNumber}')", orderRef, completionData.User.PersonalIdentityNumber); return Task.CompletedTask; } } ``` ```csharp services .AddBankId(bankId => { bankId.AddResultStore(); }); ```