OpenID Connect
Moka.Auth provides seamless integration with OpenID Connect (OIDC) providers, enabling secure authentication through trusted identity providers.
Basic Setup
Enable OpenID Connect in your Program.cs:
builder.Services.AddMokaAuth(options =>{ options.Authentication = new AuthenticationOptions { EnableOpenId = true };
options.OpenId = new OpenIdOptions { Authority = "https://your-identity-provider", ClientId = "your-client-id", ClientSecret = "your-client-secret", Scopes = new[] { "openid", "profile", "email" } };});Or via appsettings.json:
{ "MokaAuth": { "Authentication": { "EnableOpenId": true }, "OpenId": { "Authority": "https://your-identity-provider", "ClientId": "your-client-id", "ClientSecret": "your-client-secret", "Scopes": ["openid", "profile", "email"] } }}Provider Configuration
Microsoft Azure AD
builder.Services.AddMokaAuth(options =>{ options.Authentication.EnableOpenId = true; options.OpenId = new OpenIdOptions { Authority = "https://login.microsoftonline.com/{tenant-id}/v2.0", ClientId = "your-client-id", ClientSecret = "your-client-secret", Scopes = new[] { "openid", "profile", "email", "User.Read" }, MapClaimsFromUserInfo = true, ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true };});builder.Services.AddMokaAuth(options =>{ options.Authentication.EnableOpenId = true; options.OpenId = new OpenIdOptions { Authority = "https://accounts.google.com", ClientId = "your-client-id", ClientSecret = "your-client-secret", Scopes = new[] { "openid", "profile", "email" }, MapClaimsFromUserInfo = true, ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true };});Auth0
builder.Services.AddMokaAuth(options =>{ options.Authentication.EnableOpenId = true; options.OpenId = new OpenIdOptions { Authority = "https://{your-domain}.auth0.com", ClientId = "your-client-id", ClientSecret = "your-client-secret", Scopes = new[] { "openid", "profile", "email" }, MapClaimsFromUserInfo = true, ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true };});Advanced Configuration
Token Validation
Configure token validation settings:
builder.Services.AddMokaAuth(options =>{ options.OpenId = new OpenIdOptions { // Basic settings Authority = "https://your-identity-provider", ClientId = "your-client-id", ClientSecret = "your-client-secret",
// Token validation ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, RequireHttpsMetadata = true,
// Clock skew ClockSkew = TimeSpan.FromMinutes(5),
// Token lifetimes AccessTokenLifetime = TimeSpan.FromHours(1), RefreshTokenLifetime = TimeSpan.FromDays(30) };});Claims Mapping
Configure how external claims are mapped to Moka.Auth claims:
builder.Services.AddMokaAuth(options =>{ options.OpenId = new OpenIdOptions { // Basic settings...
// Claims mapping MapClaimsFromUserInfo = true, ClaimActions = new Dictionary<string, string> { ["name"] = ClaimTypes.Name, ["email"] = ClaimTypes.Email, ["sub"] = ClaimTypes.NameIdentifier, ["given_name"] = ClaimTypes.GivenName, ["family_name"] = ClaimTypes.Surname },
// Role claim RoleClaimType = "roles",
// Additional claims to include AdditionalClaims = new[] { "picture", "locale", "updated_at" } };});Events
Handle OpenID Connect authentication events:
builder.Services.AddMokaAuth(options =>{ options.OpenId = new OpenIdOptions { // Basic settings...
Events = new OpenIdEvents { OnTokenValidated = async context => { // Access the claims principal var user = context.Principal;
// Access the tokens var accessToken = context.TokenEndpointResponse?.AccessToken; var idToken = context.TokenEndpointResponse?.IdToken;
// Custom logic here },
OnUserInformationReceived = async context => { // Access user info var claims = context.User;
// Custom logic here },
OnAuthenticationFailed = async context => { // Handle authentication failure var error = context.Exception;
// Custom error handling } } };});Integration with User Management
Auto User Creation
Configure automatic user creation for new external users:
builder.Services.AddMokaAuth(options =>{ options.OpenId = new OpenIdOptions { // Basic settings...
AutoCreateUsers = true, AutoCreateUserOptions = new AutoCreateUserOptions { DefaultRole = "User", RequireEmailVerification = false, MapExternalClaims = true, AllowedDomains = new[] { "yourdomain.com" } } };});External Login Flow
Implement external login in your controllers:
[Route("auth")]public class AuthController : Controller{ private readonly IUserService _userService; private readonly IAuthService _authService;
[HttpGet("login")] public IActionResult Login(string returnUrl = null) { var properties = new AuthenticationProperties { RedirectUri = returnUrl ?? "/" };
return Challenge(properties, OpenIdDefaults.AuthenticationScheme); }
[HttpGet("callback")] public async Task<IActionResult> ExternalLoginCallback() { var result = await _authService.HandleExternalLoginAsync();
if (result.Succeeded) { // Login successful return Redirect(result.ReturnUrl ?? "/"); }
// Handle errors return View("Error", result.Errors); }}