Overview
SuperUaePass is a professional .NET library for integrating UAE Pass authentication into your applications. It provides a clean, secure, and easy-to-use interface for OAuth 2.0 authentication with UAE Pass.
Pre-requisites
Before integrating SuperUaePass into your application, ensure you have the following requirements:
UAE Pass Developer Account
- Staging Environment Account: Developer/Tester should have a user account created on the UAE Pass staging environment
- UAE Pass Mobile App: Staging mobile app should be installed on the developer's device for testing purposes
- Emirates ID: Valid Emirates ID for testing authentication flow
UAE Pass Application Registration
- Client ID and Secret: Valid credentials from UAE Pass service provider registration
- Redirect URI: Properly configured callback URL that matches your UAE Pass application settings
- Application Assessment: Complete UAE Pass application assessment for production access
Technical Requirements
- .NET 6.0+: Minimum .NET version required
- HTTPS: Required for production environments
- Session Support: For state parameter validation and CSRF protection
- HTTP Client: For making API calls to UAE Pass endpoints
Network Requirements
- Internet Access: Required to connect to UAE Pass APIs
- Proxy Configuration: If behind corporate firewall (optional)
- DNS Resolution: Ability to resolve UAE Pass domain names
Development Environment
- Visual Studio 2022 or VS Code: For development
- UAE Pass Staging Environment: For testing and development
- Valid Test Data: Emirates ID and user credentials for testing
Installation
Install SuperUaePass using your preferred package manager:
Install-Package SuperUaePass
dotnet add package SuperUaePass
Quick Start
Method 1: Configuration-Based Setup (Recommended)
1. Configure Services with appsettings.json
using SuperUaePass.Extensions;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews();
// Add session support (REQUIRED for state parameter validation)
builder.Services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromMinutes(30);
options.Cookie.HttpOnly = true;
options.Cookie.IsEssential = true;
});
// Configure SuperUaePass services using configuration
builder.Services.AddSuperUaePass(builder.Configuration);
var app = builder.Build();
// Configure the HTTP request pipeline.
app.UseSession();
app.MapControllers();
app.Run();
2. Add Configuration to appsettings.json
{
"SuperUaePass": {
"BaseUrl": "https://stg-id.uaepass.ae",
"ClientId": "your_client_id",
"ClientSecret": "your_client_secret",
"RedirectUri": "https://your-domain.com/callback",
"Scope": "urn:uae:digitalid:profile:general",
"Environment": "Staging",
"ResponseType": "code",
"EnableLogging": true,
"TimeoutSeconds": 30,
"UseProxy": false
}
}
Method 2: Hardcoded Configuration
Configure Services with Options
using SuperUaePass.Extensions;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews();
// Add session support (REQUIRED for state parameter validation)
builder.Services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromMinutes(30);
options.Cookie.HttpOnly = true;
options.Cookie.IsEssential = true;
});
// Configure SuperUaePass services with hardcoded options
builder.Services.AddSuperUaePass(options =>
{
// UAE Pass Environment URLs
options.BaseUrl = "https://stg-id.uaepass.ae"; // Staging environment
// options.BaseUrl = "https://id.uaepass.ae"; // Production environment
// Your UAE Pass credentials (provided during onboarding)
options.ClientId = "your-client-id";
options.ClientSecret = "your-client-secret";
options.RedirectUri = "https://your-app.com/callback";
options.Scope = "urn:uae:digitalid:profile:general";
// Environment configuration
options.Environment = UaePassEnvironment.Staging;
options.ResponseType = "code";
options.EnableLogging = true;
options.TimeoutSeconds = 30;
// Optional: Configure proxy for enterprise environments
options.UseProxy = true;
options.ProxyUrl = "http://your-proxy:8080";
options.ProxyUsername = "proxy-user";
options.ProxyPassword = "proxy-password";
});
var app = builder.Build();
// Configure the HTTP request pipeline.
app.UseSession();
app.MapControllers();
app.Run();
Method 3: Custom Configuration Section
Configure Services with Custom Section
using SuperUaePass.Extensions;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews();
// Add session support (REQUIRED for state parameter validation)
builder.Services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromMinutes(30);
options.Cookie.HttpOnly = true;
options.Cookie.IsEssential = true;
});
// Configure SuperUaePass services using custom configuration section
builder.Services.AddSuperUaePass(builder.Configuration, "CustomUaePassSection");
var app = builder.Build();
// Configure the HTTP request pipeline.
app.UseSession();
app.MapControllers();
app.Run();
Custom Configuration in appsettings.json
{
"CustomUaePassSection": {
"BaseUrl": "https://stg-id.uaepass.ae",
"ClientId": "your_client_id",
"ClientSecret": "your_client_secret",
"RedirectUri": "https://your-domain.com/callback",
"Scope": "urn:uae:digitalid:profile:general",
"Environment": "Staging",
"ResponseType": "code",
"EnableLogging": true
}
}
4. Use in Controller
public class HomeController : Controller
{
private readonly ISuperUaePassService _uaePassService;
private readonly ILogger _logger;
public HomeController(ISuperUaePassService uaePassService, ILogger logger)
{
_uaePassService = uaePassService;
_logger = logger;
}
public IActionResult Login()
{
var state = Guid.NewGuid().ToString();
// Store state in session for validation
HttpContext.Session.SetString("UaePassState", state);
var authUrl = _uaePassService.GenerateAuthorizationUrl(state);
return Redirect(authUrl);
}
public async Task Callback(string code, string state)
{
try
{
// Validate state parameter to prevent CSRF attacks
var storedState = HttpContext.Session.GetString("UaePassState");
if (string.IsNullOrEmpty(storedState) || storedState != state)
{
return BadRequest("Invalid state parameter");
}
// Clear the state from session after validation
HttpContext.Session.Remove("UaePassState");
var tokenResponse = await _uaePassService.ExchangeCodeForTokenAsync(code, state);
var userProfile = await _uaePassService.GetUserProfileAsync(tokenResponse.AccessToken);
// Store user information in session
HttpContext.Session.SetString("IsAuthenticated", "true");
HttpContext.Session.SetString("UserProfile", JsonSerializer.Serialize(userProfile));
return RedirectToAction("Profile");
}
catch (Exception ex)
{
_logger.LogError(ex, "UAE Pass authentication failed");
return RedirectToAction("Error", new { error = "Authentication failed" });
}
}
}
Configuration
Configure SuperUaePass using the following options in your appsettings.json
:
Property | Type | Default | Description |
---|---|---|---|
BaseUrl |
string | https://stg-id.uaepass.ae |
UAE Pass base URL |
ClientId |
string | - | Your UAE Pass client ID |
ClientSecret |
string | - | Your UAE Pass client secret |
RedirectUri |
string | - | Your application's callback URL |
Scope |
string | urn:uae:digitalid:profile:general |
OAuth 2.0 scope |
Environment |
UaePassEnvironment | Staging |
UAE Pass environment |
ResponseType |
string | code |
OAuth 2.0 response type |
EnableLogging |
bool | false |
Enable detailed logging |
Authentication Flow
The UAE Pass integration follows the standard OAuth 2.0 authorization code flow:
Authorization Request
Redirect user to UAE Pass authorization endpoint
User Authentication
User authenticates with Emirates ID
Authorization Code
UAE Pass returns authorization code to your callback
Token Exchange
Exchange authorization code for access token
User Profile
Retrieve user information using access token
Browser-Based Authentication
For browser-based authentication, the client secret is typically skipped, and the authorization endpoint includes specific parameters:
https://stg-id.uaepass.ae/idshub/authorize?
response_type=code&
client_id=sandbox_stage&
scope=urn:uae:digitalid:profile:general&
state=HnlHOJTkTb66Y5H&
redirect_uri=https://stg-selfcare.uaepass.ae&
acr_values=urn:safelayer:tws:policies:authentication:level:low
acr_values
parameter is required for authentication level- Parameters should NOT be URL-encoded
nonce
parameter is optional
Security Considerations
State Parameter
Always use a state parameter to prevent CSRF attacks:
var state = Guid.NewGuid().ToString();
HttpContext.Session.SetString("UaePassState", state);
var authUrl = _uaePassService.GenerateAuthorizationUrl(state);
User Type Validation
Validate user types to ensure only authorized users can access your application:
var supportedTypes = new[] { "SOP1", "SOP2", "SOP3" };
if (!_uaePassService.IsUserTypeSupported(userProfile.UserType, supportedTypes))
{
return BadRequest("User type not supported");
}
Error Handling
Implement proper error handling with correlation IDs:
try
{
var tokenResponse = await _uaePassService.ExchangeCodeForTokenAsync(code);
var userProfile = await _uaePassService.GetUserProfileAsync(tokenResponse.AccessToken);
}
catch (Exception ex)
{
_logger.LogError(ex, "UAE Pass authentication failed");
return RedirectToAction("Error", new { error = "Authentication failed" });
}
ISuperUaePassService
GenerateAuthorizationUrl
string GenerateAuthorizationUrl(string state, string? nonce = null, string? prompt = null, string? uiLocales = null)
Generates the UAE Pass authorization URL with the specified parameters.
ExchangeCodeForTokenAsync
Task<UaePassTokenResponse> ExchangeCodeForTokenAsync(string code)
Exchanges the authorization code for an access token.
GetUserProfileAsync
Task<UaePassUserProfile> GetUserProfileAsync(string accessToken)
Retrieves the user profile using the access token.
GenerateLogoutUrl
string GenerateLogoutUrl(string? redirectUri = null)
Generates the UAE Pass logout URL.
UaePassUserProfile
The user profile contains the following properties from the UAE Pass response:
public class UaePassUserProfile
{
public string? Sub { get; set; }
public string? Uuid { get; set; }
public string? UserType { get; set; }
public string? ProfileType { get; set; }
public string? Idn { get; set; }
public string? UnifiedID { get; set; }
public string? IdType { get; set; }
public string? Spuuid { get; set; }
public string? FirstnameEN { get; set; }
public string? LastnameEN { get; set; }
public string? FullnameEN { get; set; }
public string? FirstnameAR { get; set; }
public string? LastnameAR { get; set; }
public string? FullnameAR { get; set; }
public string? TitleEN { get; set; }
public string? TitleAR { get; set; }
public string? Email { get; set; }
public string? Mobile { get; set; }
public string? Gender { get; set; }
public string? NationalityEN { get; set; }
public string? NationalityAR { get; set; }
public string? Acr { get; set; }
public string? Amr { get; set; }
// Convenience properties
public string? EmiratesId => Idn;
public string? FirstName => FirstnameEN;
public string? LastName => LastnameEN;
public string? FullName => FullnameEN;
public string? PhoneNumber => Mobile;
}
UaePassTokenResponse
The token response contains the OAuth 2.0 tokens returned by UAE Pass:
public class UaePassTokenResponse
{
public string? AccessToken { get; set; }
public string? TokenType { get; set; }
public int? ExpiresIn { get; set; }
public string? RefreshToken { get; set; }
public string? Scope { get; set; }
public string? IdToken { get; set; }
}
Configuration Options
Detailed configuration options for the SuperUaePass library:
Property | Type | Required | Description |
---|---|---|---|
BaseUrl |
string | Yes | UAE Pass base URL (staging or production) |
ClientId |
string | Yes | Your UAE Pass client ID |
ClientSecret |
string | Yes | Your UAE Pass client secret |
RedirectUri |
string | Yes | Your application's callback URL |
Scope |
string | No | OAuth 2.0 scope (default: urn:uae:digitalid:profile:general) |
Environment |
UaePassEnvironment | No | UAE Pass environment (default: Staging) |
ResponseType |
string | No | OAuth 2.0 response type (default: code) |
EnableLogging |
bool | No | Enable detailed logging (default: false) |
Basic Integration
A complete example of integrating UAE Pass authentication in an ASP.NET Core application:
// Program.cs
using SuperUaePass;
var builder = WebApplication.CreateBuilder(args);
// Add UAE Pass services
builder.Services.AddSuperUaePass(builder.Configuration);
// Add session support
builder.Services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromMinutes(30);
options.Cookie.HttpOnly = true;
options.Cookie.IsEssential = true;
});
var app = builder.Build();
app.UseSession();
app.MapControllers();
app.Run();
// AuthController.cs
public class AuthController : Controller
{
private readonly ISuperUaePassService _uaePassService;
private readonly ILogger _logger;
public AuthController(ISuperUaePassService uaePassService, ILogger logger)
{
_uaePassService = uaePassService;
_logger = logger;
}
public IActionResult Login()
{
var state = Guid.NewGuid().ToString();
HttpContext.Session.SetString("UaePassState", state);
var authUrl = _uaePassService.GenerateAuthorizationUrl(state);
return Redirect(authUrl);
}
public async Task Callback(string code, string state)
{
try
{
// Validate state parameter
var storedState = HttpContext.Session.GetString("UaePassState");
if (string.IsNullOrEmpty(storedState) || storedState != state)
{
return BadRequest("Invalid state parameter");
}
// Exchange code for token
var tokenResponse = await _uaePassService.ExchangeCodeForTokenAsync(code);
// Get user profile
var userProfile = await _uaePassService.GetUserProfileAsync(tokenResponse.AccessToken);
// Store user information in session
HttpContext.Session.SetString("IsAuthenticated", "true");
HttpContext.Session.SetString("UserProfile", JsonSerializer.Serialize(userProfile));
return RedirectToAction("Profile", "Home");
}
catch (Exception ex)
{
_logger.LogError(ex, "UAE Pass authentication failed");
return RedirectToAction("Error", "Home", new { error = "Authentication failed" });
}
}
public IActionResult Logout()
{
HttpContext.Session.Clear();
var logoutUrl = _uaePassService.GenerateLogoutUrl();
return Redirect(logoutUrl);
}
}
Advanced Usage
Advanced features and best practices for UAE Pass integration:
Custom Authorization Parameters
// Generate authorization URL with custom parameters
var state = Guid.NewGuid().ToString();
var nonce = Guid.NewGuid().ToString();
var authUrl = _uaePassService.GenerateAuthorizationUrl(
state: state,
nonce: nonce,
prompt: "login",
uiLocales: "en"
);
// Store nonce for validation
HttpContext.Session.SetString("UaePassNonce", nonce);
User Type Validation
// Validate user type after authentication
var supportedUserTypes = new[] { "SOP1", "SOP2", "SOP3" };
if (!supportedUserTypes.Contains(userProfile.UserType))
{
_logger.LogWarning("Unsupported user type: {UserType}", userProfile.UserType);
return BadRequest("User type not supported");
}
// Check authentication level
if (userProfile.Acr != "urn:safelayer:tws:policies:authentication:level:low")
{
_logger.LogWarning("Insufficient authentication level: {Acr}", userProfile.Acr);
return BadRequest("Insufficient authentication level");
}
Troubleshooting
Common issues and solutions when integrating UAE Pass:
Common Issues
1. Invalid Redirect URI
Problem: UAE Pass returns "invalid_redirect_uri" error.
Solution: Ensure the redirect URI in your configuration matches exactly what's registered with UAE Pass, including protocol, domain, port, and path.
// Correct format
"RedirectUri": "https://your-domain.com/callback"
// Common mistakes
"RedirectUri": "http://your-domain.com/callback" // Wrong protocol
"RedirectUri": "https://your-domain.com/callback/" // Extra slash
"RedirectUri": "https://your-domain.com/Callback" // Wrong case
2. State Parameter Mismatch
Problem: "Invalid state parameter" error.
Solution: Verify session is properly configured and state parameter is stored/retrieved correctly.
// Ensure session is configured
builder.Services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromMinutes(30);
options.Cookie.HttpOnly = true;
options.Cookie.IsEssential = true;
});
// Use session middleware in correct order
app.UseSession(); // Must be after routing, before authorization
3. Network Issues
Problem: Unable to connect to UAE Pass endpoints.
Solution: Check proxy configuration and network connectivity to UAE Pass endpoints.
// Configure proxy if behind corporate firewall
options.UseProxy = true;
options.ProxyUrl = "http://your-proxy:8080";
options.ProxyUsername = "proxy-user";
options.ProxyPassword = "proxy-password";
4. Invalid Credentials
Problem: "invalid_client" or "unauthorized_client" error.
Solution: Verify client ID and secret are correct for the environment you're using.
// Staging environment
"BaseUrl": "https://stg-id.uaepass.ae"
"ClientId": "staging_client_id"
"ClientSecret": "staging_client_secret"
// Production environment
"BaseUrl": "https://id.uaepass.ae"
"ClientId": "production_client_id"
"ClientSecret": "production_client_secret"
5. Session Not Working
Problem: Session data is not persisting between requests.
Solution: Ensure session middleware is configured and used in the correct order.
// Correct middleware order
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseSession(); // Must be after routing, before authorization
app.UseAuthorization();
Debug Mode
Enable logging to troubleshoot issues:
{
"SuperUaePass": {
"EnableLogging": true
},
"Logging": {
"LogLevel": {
"SuperUaePass": "Debug",
"Default": "Information"
}
}
}