### Load Application Credential and Get Signed JWT (C#) Source: https://github.com/smartive/zitadel-net/blob/main/src/Zitadel/README.md Demonstrates how to load application credentials from a JSON string and obtain a signed JWT token. This is typically used for authenticating applications acting as relying parties. ```csharp var application = Application.LoadFromJsonString( @"{ \"type\": \"application\", \"keyId\": \"keyid\", \"key\": \"RSA KEY\", \"appId\": \"appid\", \"clientId\": \"client id\" }"); var jwt = await application.GetSignedJwtAsync("issuer"); ``` -------------------------------- ### Web API with Multiple Authentication Schemes in C# Source: https://context7.com/smartive/zitadel-net/llms.txt A production-ready .NET Web API example demonstrating how to combine multiple authentication methods (Zitadel JWT and Basic introspection) and protect endpoints. Includes authorization policies and controller implementations. ```csharp using System.Security.Claims; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Zitadel.Authentication; using Zitadel.Credentials; using Zitadel.Extensions; var builder = WebApplication.CreateBuilder(args); builder.Services.AddControllers(); builder.Services .AddAuthorization(options => { options.AddZitadelOrganizationRolePolicy("AdminPolicy", "org-123", "Admin"); }) .AddAuthentication() .AddZitadelIntrospection("ZITADEL_JWT", o => { o.Authority = "https://my-instance.zitadel.cloud"; o.JwtProfile = Application.LoadFromJsonFile("app-credentials.json"); }) .AddZitadelIntrospection("ZITADEL_BASIC", o => { o.Authority = "https://my-instance.zitadel.cloud/"; o.ClientId = "client-id@project"; o.ClientSecret = "client-secret"; }); var app = builder.Build(); app.UseAuthentication(); app.UseAuthorization(); app.MapControllers(); await app.RunAsync(); // Controller implementation [ApiController] [Route("api")] public class ApiController : ControllerBase { [HttpGet("public")] public IActionResult PublicEndpoint() => Ok(new { Message = "Public data" }); [HttpGet("protected")] [Authorize(AuthenticationSchemes = "ZITADEL_JWT,ZITADEL_BASIC")] public IActionResult ProtectedEndpoint() { return Ok( new { UserId = User.FindFirst(OidcClaimTypes.Subject)?.Value, AuthType = User.Identity?.AuthenticationType, Claims = User.Claims.Select(c => new { c.Type, c.Value }) }); } [HttpGet("admin")] [Authorize(AuthenticationSchemes = "ZITADEL_JWT", Policy = "AdminPolicy")] public IActionResult AdminEndpoint() { if (!User.IsInRole("org-123", "Admin")) return Forbid(); return Ok(new { Message = "Admin access granted" }); } } ``` -------------------------------- ### Configure Static and Service Account Token Providers for gRPC Clients Source: https://context7.com/smartive/zitadel-net/llms.txt Demonstrates how to create and use ITokenProvider implementations for gRPC clients. Supports static tokens for simplicity and service account tokens for automatic refresh, requiring the Zitadel.Api and Zitadel.Credentials namespaces. ```csharp using Zitadel.Api; using Zitadel.Credentials; // Static token provider - uses the same token for all requests ITokenProvider staticProvider = ITokenProvider.Static("your-access-token"); // Service account provider - automatically refreshes tokens when expired var serviceAccount = ServiceAccount.LoadFromJsonFile("service-account.json"); ITokenProvider serviceAccountProvider = ITokenProvider.ServiceAccount( "https://my-instance.zitadel.cloud", serviceAccount, new ServiceAccount.AuthOptions { ApiAccess = true }); // Use with any gRPC client var client = Clients.UserService(new Clients.Options( "https://my-instance.zitadel.cloud", serviceAccountProvider)); var userResult = await client.GetUserByIDAsync(new() { UserId = "user-id-123" }); Console.WriteLine($"Found user: {userResult.User.Human.Profile.DisplayName}"); ``` -------------------------------- ### Create gRPC API Clients with Token Handling - C# Source: https://context7.com/smartive/zitadel-net/llms.txt Factory for creating pre-configured gRPC clients for ZITADEL's management APIs. Supports authentication via personal access tokens or service accounts with JWT profiles, and allows setting a default organization context. ```csharp using Zitadel.Api; using Zitadel.Credentials; const string apiUrl = "https://my-instance.zitadel.cloud"; // Option 1: Using a personal access token var authClient = Clients.AuthService(new Clients.Options( apiUrl, ITokenProvider.Static("ge85fvmgTX4XAhjpF0XGpelB2vn9LZanJaq..."))); var user = await authClient.GetMyUserAsync(new()); Console.WriteLine($"User ID: {user.User.Id}, Name: {user.User.Human.Profile.DisplayName}"); // Option 2: Using a service account with JWT profile var serviceAccount = ServiceAccount.LoadFromJsonFile("service-account.json"); var managementClient = Clients.ManagementService(new Clients.Options( apiUrl, ITokenProvider.ServiceAccount(apiUrl, serviceAccount, new() { ApiAccess = true })) { Organization = "org-id-123" // Set default organization context }); // List users in the organization var users = await managementClient.ListUsersAsync(new()); foreach (var u in users.Result) { Console.WriteLine($"- {u.Human?.Profile?.DisplayName ?? u.Machine?.Name}"); } // Available clients: AuthService, AdminService, ManagementService, // UserService, SessionService, OrganizationService, SettingsService, // OidcService, SystemService ``` -------------------------------- ### Load Service Account Credential and Authenticate (C#) Source: https://github.com/smartive/zitadel-net/blob/main/src/Zitadel/README.md Shows how to load service account credentials from a JSON string and authenticate with ZITADEL to retrieve an access token. This is useful for server-to-server communication. ```csharp var serviceAccount = ServiceAccount.LoadFromJsonString( @"{ \"type\": \"serviceaccount\", \"keyId\": \"key id\", \"key\": \"RSA KEY\", \"userId\": \"user id\" }"); var token = await serviceAccount.AuthenticateAsync(); ``` -------------------------------- ### Access ZITADEL Auth Service with Personal Access Token (C#) Source: https://github.com/smartive/zitadel-net/blob/main/src/Zitadel/README.md Illustrates how to create an AuthClient for the ZITADEL API using a personal access token. This method is suitable for scenarios where a static token is available. ```csharp const string apiUrl = "https://zitadel-libraries-l8boqa.zitadel.cloud"; const string personalAccessToken = "TOKEN"; var client = Clients.AuthService(new(apiUrl, ITokenProvider.Static(personalAccessToken))); var result = await client.GetMyUserAsync(new()); Console.WriteLine($"User: {result.User}"); ``` -------------------------------- ### Configure ASP.NET Core OpenID Connect Authentication with ZITADEL Source: https://context7.com/smartive/zitadel-net/llms.txt Sets up ASP.NET Core web applications for authentication via ZITADEL using OpenID Connect. This configuration enables session management and requires the Microsoft.AspNetCore.Identity, Zitadel.Authentication, and Zitadel.Extensions namespaces. ```csharp using Microsoft.AspNetCore.Identity; using Zitadel.Authentication; using Zitadel.Extensions; var builder = WebApplication.CreateBuilder(args); builder.Services .AddAuthorization() .AddAuthentication(ZitadelDefaults.AuthenticationScheme) .AddZitadel(options => { options.Authority = "https://my-instance.zitadel.cloud/"; options.ClientId = "170088295403946241@library"; options.SignInScheme = IdentityConstants.ExternalScheme; options.SaveTokens = true; options.Scope.Add("openid"); options.Scope.Add("profile"); options.Scope.Add("email"); }) .AddExternalCookie() .Configure(cookieOptions => { cookieOptions.Cookie.HttpOnly = true; cookieOptions.Cookie.IsEssential = true; cookieOptions.Cookie.SameSite = SameSiteMode.None; cookieOptions.Cookie.SecurePolicy = CookieSecurePolicy.Always; }); var app = builder.Build(); app.UseAuthentication(); app.UseAuthorization(); app.MapRazorPages(); await app.RunAsync(); // In a Razor Page or Controller: // User.FindFirst(ClaimTypes.NameIdentifier)?.Value // ZITADEL user ID // User.FindFirst(ClaimTypes.Email)?.Value // User's email // User.IsInRole("Admin") // Check role membership ``` -------------------------------- ### Create ZITADEL AuthServiceClient Manually (C#) Source: https://github.com/smartive/zitadel-net/blob/main/src/Zitadel/README.md Explains how to manually create an AuthServiceClient by providing a gRPC channel and an access token in the metadata. This offers more control over the gRPC client configuration. ```csharp var accessToken = "fetch it somehow"; var channel = GrpcChannel.ForAddress("https://my-zitadel-api.com"); var client = new AuthService.AuthServiceClient(channel); var result = await client.GetMyUserAsync( new(), new Metadata { { "Authorization", $"Bearer {accessToken}" } }); Console.WriteLine($"User: {result.User}"); ``` -------------------------------- ### Mock Authentication with AddZitadelFake Source: https://context7.com/smartive/zitadel-net/llms.txt Enables local development and testing without a real ZITADEL instance by mocking authentication. It allows customization of fake user ID, roles, and additional claims. Authentication can be overridden per-request using specific headers. ```csharp using System.Security.Claims; using Zitadel.Extensions; var builder = WebApplication.CreateBuilder(args); builder.Services .AddAuthorization() .AddAuthentication() .AddZitadelFake(options => { options.FakeZitadelId = "test-user-123"; options.Roles = new[] { "Admin", "User" }; options.AdditionalClaims = new List { new Claim(ClaimTypes.Email, "test@example.com"), new Claim(ClaimTypes.Name, "Test User"), new Claim("custom_claim", "custom_value") }; }); var app = builder.Build(); app.UseAuthentication(); app.UseAuthorization(); app.MapControllers(); await app.RunAsync(); // Override authentication per-request using headers: // x-zitadel-fake-auth: false -> Request will be unauthenticated // x-zitadel-fake-user-id: user123 -> Override the fake user ID ``` -------------------------------- ### Zitadel Authentication Scheme Defaults in C# Source: https://context7.com/smartive/zitadel-net/llms.txt Access default configuration values for Zitadel authentication schemes, including scheme names, display names, OIDC paths, and organization context headers. Demonstrates custom authentication scheme registration. ```csharp using Zitadel.Authentication; // Default authentication scheme names string defaultScheme = ZitadelDefaults.AuthenticationScheme; // "ZITADEL" string fakeScheme = ZitadelDefaults.FakeAuthenticationScheme; // "ZITADEL-Fake" // Display names string displayName = ZitadelDefaults.DisplayName; // "ZITADEL" string fakeDisplayName = ZitadelDefaults.FakeDisplayName; // "ZITADEL-Fake" // OIDC paths and endpoints string callbackPath = ZitadelDefaults.CallbackPath; // "/signin-zitadel" string discoveryPath = ZitadelDefaults.DiscoveryEndpointPath; // "/.well-known/openid-configuration" // HTTP header for organization context string orgHeader = ZitadelDefaults.ZitadelOrgIdHeader; // "x-zitadel-orgid" // Example: Custom authentication scheme registration builder.Services .AddAuthentication(ZitadelDefaults.AuthenticationScheme) .AddZitadel(ZitadelDefaults.AuthenticationScheme, ZitadelDefaults.DisplayName, options => { options.Authority = "https://my-instance.zitadel.cloud/"; options.ClientId = "my-client-id"; options.CallbackPath = ZitadelDefaults.CallbackPath; }); ``` -------------------------------- ### Configure ZITADEL Authentication in ASP.NET Core (C#) Source: https://github.com/smartive/zitadel-net/blob/main/src/Zitadel/README.md Shows the configuration of ZITADEL authentication for ASP.NET Core web applications using the `AddZitadel` extension method. It requires an application on ZITADEL and its client ID. ```csharp // -- snip -- builder.Services .AddAuthorization() .AddAuthentication(ZitadelDefaults.AuthenticationScheme) .AddZitadel( o => { o.Authority = "https://zitadel-libraries-l8boqa.zitadel.cloud/"; o.ClientId = "170088295403946241@library"; o.SignInScheme = IdentityConstants.ExternalScheme; }) .AddExternalCookie() .Configure( o => { o.Cookie.HttpOnly = true; o.Cookie.IsEssential = true; o.Cookie.SameSite = SameSiteMode.None; o.Cookie.SecurePolicy = CookieSecurePolicy.Always; }); // -- snip -- ``` -------------------------------- ### Generate HTTP Basic Credentials - C# Source: https://context7.com/smartive/zitadel-net/llms.txt Creates URL-encoded HTTP Basic authentication credentials using a client ID and client secret. It provides the `HttpCredentials` property which can be directly used in the Authorization header. ```csharp using Zitadel.Credentials; var basicAuth = new BasicAuthentication( ClientId: "170102032621961473@library", ClientSecret: "KNkKW8nx3rlEKOeHNUcPx80tZTP1uZTjJESfdA3kMEK7urhX3ChFukTMQrtjvG70" ); // Get the HTTP Authorization header value Console.WriteLine(basicAuth.HttpCredentials); // Output: Basic MTcwMTAyMDMyNjIxOTYxNDczJTQwbGlicmFyeTpLTmtLVzhueD..." ``` -------------------------------- ### Enable Faked/Mocked Local Authentication for ZITADEL Source: https://github.com/smartive/zitadel-net/blob/main/src/Zitadel/README.md Enables a mocked authentication mechanism for local development and testing without a live ZITADEL instance. This adds provided claims to the identity and allows calls to pass as authenticated. It supports overriding user ID via headers. ```csharp builder.Services .AddAuthorization() .AddAuthentication() .AddZitadelFake(o => { o.FakeZitadelId = "1337"; }); ``` -------------------------------- ### Access ZITADEL Auth Service with Service Account JWT (C#) Source: https://github.com/smartive/zitadel-net/blob/main/src/Zitadel/README.md Demonstrates accessing the ZITADEL Auth Service using a service account's JWT profile. This provides a secure way to authenticate machine-to-machine interactions. ```csharp const string apiProject = "PROJECT ID"; var serviceAccount = ServiceAccount.LoadFromJsonString( @"{ \"type\": \"serviceaccount\", \"keyId\": \"key id\", \"key\": \"RSA KEY\", \"userId\": \"user id\" }"); client = Clients.AuthService( new( apiUrl, ITokenProvider.ServiceAccount( apiUrl, serviceAccount, new(){ ApiAccess = true }))) result = await client.GetMyUserAsync(new()); Console.WriteLine($"User: {result.User}"); ``` -------------------------------- ### Authenticate as Service Account with JWT Profile - C# Source: https://context7.com/smartive/zitadel-net/llms.txt Authenticates a service account using RSA key pairs loaded from a JSON file or string. It obtains access tokens for making API calls, supporting options like API access, required roles, and project audiences. ```csharp using Zitadel.Credentials; // Load service account from JSON file var serviceAccount = await ServiceAccount.LoadFromJsonFileAsync("path/to/service-account.json"); // Or load from JSON string var serviceAccount = ServiceAccount.LoadFromJsonString( @"{ \"type\": \"serviceaccount\", \"keyId\": \"170084658355110145\", \"key\": \"-----BEGIN RSA PRIVATE KEY-----\n...\n-----END RSA PRIVATE KEY-----\n\", \"userId\": \"170079991923474689\" }"); // Authenticate and get access token var token = await serviceAccount.AuthenticateAsync( "https://my-instance.zitadel.cloud", new ServiceAccount.AuthOptions { ApiAccess = true, // Include ZITADEL API in audience RequiredRoles = new List { "Admin" }, ProjectAudiences = new List { "project-id-123" } }); Console.WriteLine($"Access Token: {token}"); // Output: Access Token: eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9..." ``` -------------------------------- ### Role Checking Utilities with ClaimsPrincipalExtensions Source: https://context7.com/smartive/zitadel-net/llms.txt Provides extension methods for `ClaimsPrincipal` to easily check user roles, including organization-scoped role verification. These methods simplify the process of determining if a user has the necessary permissions to access specific resources or perform certain actions. ```csharp using System.Security.Claims; using Zitadel.Extensions; // In a controller or middleware public IActionResult CheckAccess() { // Check if user has any of the specified roles bool isAdminOrManager = User.IsInRole("Admin", "Manager"); // Check role within a specific organization bool isOrgAdmin = User.IsInRole( organizationId: "170079991923474689", role: "Admin"); // Check multiple roles within an organization bool hasOrgAccess = User.IsInRole( organizationId: "170079991923474689", roles: "Admin", "Manager", "User"); return Ok(new { IsAdminOrManager = isAdminOrManager, IsOrgAdmin = isOrgAdmin, HasOrgAccess = hasOrgAccess }); } ``` -------------------------------- ### Standard Claim Type Constants with ZitadelClaimTypes Source: https://context7.com/smartive/zitadel-net/llms.txt Offers constants for standard ZITADEL claim types, simplifying the process of parsing and validating user claims. It includes constants for roles, primary domain, and provides a method to generate organization-specific role claim types. ```csharp using Zitadel.Authentication; using System.Security.Claims; // Standard claim types string roleClaim = ZitadelClaimTypes.Role; // Value: "urn:zitadel:iam:org:project:roles" string primaryDomainClaim = ZitadelClaimTypes.PrimaryDomain; // Value: "urn:zitadel:iam:org:domain:primary" // Organization-specific role claim string orgRoleClaim = ZitadelClaimTypes.OrganizationRole("170079991923474689"); // Value: "urn:zitadel:iam:org:170079991923474689:project:roles" // Usage in a controller public IActionResult GetUserInfo() { var userId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value; var primaryDomain = User.FindFirst(ZitadelClaimTypes.PrimaryDomain)?.Value; var roles = User.FindAll(ZitadelClaimTypes.Role).Select(c => c.Value); return Ok(new { UserId = userId, PrimaryDomain = primaryDomain, Roles = roles }); } ``` -------------------------------- ### Authenticate Web API with Application JWT Profile - C# Source: https://context7.com/smartive/zitadel-net/llms.txt Authenticates Web APIs against ZITADEL's introspection endpoint using signed JWTs derived from application credentials. Credentials can be loaded from a JSON string, and a signed JWT is generated for a specified duration. ```csharp using Zitadel.Credentials; // Load application credentials from JSON var application = Application.LoadFromJsonString( @"{ \"type\": \"application\", \"keyId\": \"170104948032274689\", \"key\": \"-----BEGIN RSA PRIVATE KEY-----\n...\n-----END RSA PRIVATE KEY-----\n\", \"appId\": \"170101999168127233\", \"clientId\": \"170101999168192769@library\" }"); // Generate signed JWT for authentication var jwt = await application.GetSignedJwtAsync( "https://my-instance.zitadel.cloud", TimeSpan.FromMinutes(30)); Console.WriteLine($"Signed JWT: {jwt}"); // Output: Signed JWT: eyJhbGciOiJSUzI1NiIsImtpZCI6IjE3MDEwNDk0ODAzMjI3NDY4OSJ9..." ``` -------------------------------- ### Configure ASP.NET Core OAuth2 Token Introspection with ZITADEL Source: https://context7.com/smartive/zitadel-net/llms.txt Configures ASP.NET Core Web APIs to validate access tokens using ZITADEL's introspection endpoint. Supports JWT Profile authentication with private key details or Basic authentication with client credentials, utilizing the Zitadel.Credentials and Zitadel.Extensions namespaces. ```csharp using Zitadel.Credentials; using Zitadel.Extensions; var builder = WebApplication.CreateBuilder(args); builder.Services .AddAuthorization() .AddAuthentication() // Option 1: JWT Profile authentication (recommended) .AddZitadelIntrospection("ZITADEL_JWT", options => { options.Authority = "https://my-instance.zitadel.cloud"; options.JwtProfile = Application.LoadFromJsonString(@"{ \"type\": \"application\", \"keyId\": \"key-id\", \"key\": \"-----BEGIN RSA PRIVATE KEY-----\n...\n-----END RSA PRIVATE KEY-----\n\", \"appId\": \"app-id\", \"clientId\": \"client-id@project\" }"); }) // Option 2: Basic authentication .AddZitadelIntrospection("ZITADEL_BASIC", options => { options.Authority = "https://my-instance.zitadel.cloud/"; options.ClientId = "170102032621961473@library"; options.ClientSecret = "KNkKW8nx3rlEKOeHNUcPx80tZTP1uZTjJESfdA3kMEK7urhX3ChFukTMQrtjvG70"; options.EnableCaching = true; options.CacheDuration = TimeSpan.FromMinutes(5); }); var app = builder.Build(); app.UseAuthentication(); app.UseAuthorization(); app.MapControllers(); await app.RunAsync(); // In a Controller: [ApiController] [Route("api/[controller]")] public class ProtectedController : ControllerBase { [HttpGet] [Authorize(AuthenticationSchemes = "ZITADEL_JWT")] public IActionResult Get() { var userId = User.FindFirst("sub")?.Value; var roles = User.Claims.Where(c => c.Type == ClaimTypes.Role).Select(c => c.Value); return Ok(new { UserId = userId, Roles = roles }); } } ``` -------------------------------- ### Configure ZITADEL Basic Authentication for Web APIs Source: https://github.com/smartive/zitadel-net/blob/main/src/Zitadel/README.md Configures ZITADEL introspection with Basic Authentication for a web API. This method requires a client ID and client secret to authenticate against ZITADEL. Ensure your ZITADEL application is set up for basic authentication. ```csharp builder.Services .AddAuthorization() .AddAuthentication() .AddZitadelIntrospection( o => { o.Authority = "https://zitadel-libraries-l8boqa.zitadel.cloud/"; o.ClientId = "170102032621961473@library"; o.ClientSecret = "KNkKW8nx3rlEKOeHNUcPx80tZTP1uZTjJESfdA3kMEK7urhX3ChFukTMQrtjvG70"; }); ``` -------------------------------- ### Configure ZITADEL JWT Profile Authentication for Web APIs Source: https://github.com/smartive/zitadel-net/blob/main/src/Zitadel/README.md Configures ZITADEL introspection using the JWT Profile (application credential) for a web API. This is the recommended method and does not require a client ID. The JWT profile must be loaded from a JSON string. ```csharp builder.Services .AddAuthorization() .AddAuthentication() .AddZitadelIntrospection( o => { o.Authority = "https://zitadel-libraries-l8boqa.zitadel.cloud"; o.JwtProfile = Application.LoadFromJsonString("YOUR APPLICATION JSON"); }); ``` -------------------------------- ### Organization-Scoped Role Policies with AddZitadelOrganizationRolePolicy Source: https://context7.com/smartive/zitadel-net/llms.txt Creates authorization policies that require specific roles within a ZITADEL organization context. This is useful for enforcing access control based on roles assigned within a particular organization. Policies can be defined to require one or multiple roles. ```csharp using Zitadel.Extensions; var builder = WebApplication.CreateBuilder(args); builder.Services.AddAuthorization(options => { // Require "Admin" or "Manager" role in a specific organization options.AddZitadelOrganizationRolePolicy( policyName: "OrgAdmin", organizationId: "170079991923474689", roles: "Admin", "Manager"); // Require "Reader" role in the organization options.AddZitadelOrganizationRolePolicy( policyName: "OrgReader", organizationId: "170079991923474689", roles: "Reader"); }); var app = builder.Build(); // Use in controllers: [Authorize(Policy = "OrgAdmin")] [HttpPost("admin-action")] public IActionResult AdminAction() => Ok("Admin action performed"); [Authorize(Policy = "OrgReader")] [HttpGet("read-data")] public IActionResult ReadData() => Ok("Data retrieved"); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.