dhis2_debug_authentication
Identify and resolve DHIS2 authentication issues such as login failures, session timeouts, cookie problems, and token errors by analyzing instance configurations, error details, and browser settings.
Instructions
Debug authentication issues including login failures, session management, and cookie problems
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| authMethod | Yes | Authentication method being used | |
| browserSettings | No | ||
| dhis2Instance | Yes | DHIS2 instance URL | |
| errorDetails | No | ||
| issueType | Yes | Type of authentication issue |
Implementation Reference
- src/debugging-helpers.ts:310-512 (handler)Main handler function for the 'dhis2_debug_authentication' tool. Analyzes authentication issues and generates a comprehensive debugging report with diagnosis, solutions, and testing commands.export function debugAuthentication(args: any): string { const { issueType, dhis2Instance, authMethod, errorDetails = {}, browserSettings = {} } = args; const diagnosis = []; const solutions = []; // Analyze authentication issue type switch (issueType) { case 'login_failure': diagnosis.push('Authentication credentials may be invalid or endpoint unreachable'); solutions.push('Verify username and password are correct'); solutions.push('Test credentials directly in DHIS2 web interface'); solutions.push('Check if account is locked or disabled'); break; case 'session_timeout': diagnosis.push('User session has expired or is not being maintained'); solutions.push('Implement session refresh mechanism'); solutions.push('Check session timeout settings in DHIS2'); solutions.push('Ensure cookies are being sent with requests'); break; case 'cookie_issues': diagnosis.push('Browser cookie handling issues affecting authentication'); solutions.push('Check SameSite cookie attributes'); solutions.push('Ensure cookies are enabled in browser'); solutions.push('Verify domain/path settings for cookies'); break; case 'token_problems': diagnosis.push('Authentication token is invalid, expired, or malformed'); solutions.push('Check token format and expiration'); solutions.push('Implement token refresh logic'); solutions.push('Verify token is included in Authorization header'); break; case 'proxy_auth': diagnosis.push('Proxy server authentication issues'); solutions.push('Check proxy credentials and configuration'); solutions.push('Verify proxy target URL is correct'); solutions.push('Ensure proxy is handling auth headers properly'); break; } // Analyze HTTP status codes if (errorDetails.httpStatus) { switch (errorDetails.httpStatus) { case 401: diagnosis.push('HTTP 401: Unauthorized - Invalid credentials'); solutions.push('Double-check username and password'); solutions.push('Ensure Authorization header is properly formatted'); break; case 403: diagnosis.push('HTTP 403: Forbidden - Valid credentials but insufficient permissions'); solutions.push('Check user authorities/permissions in DHIS2'); solutions.push('Verify user is assigned to appropriate user groups'); break; case 302: diagnosis.push('HTTP 302: Redirect - Authentication endpoint is redirecting'); solutions.push('Follow redirect chain to find final login endpoint'); solutions.push('Use direct API authentication instead of login forms'); break; case 404: diagnosis.push('HTTP 404: Not Found - Authentication endpoint does not exist'); solutions.push('Verify DHIS2 instance URL is correct'); solutions.push('Check if DHIS2 version supports the authentication method'); break; case 500: diagnosis.push('HTTP 500: Server Error - DHIS2 server experiencing issues'); solutions.push('Check DHIS2 server logs for detailed error information'); solutions.push('Verify database connectivity and server health'); break; } } return `# Authentication Debug Report ## Issue Details - **Issue Type**: ${issueType.replace(/_/g, ' ').toUpperCase()} - **DHIS2 Instance**: ${dhis2Instance} - **Auth Method**: ${authMethod.toUpperCase()} - **HTTP Status**: ${errorDetails.httpStatus || 'Not provided'} - **Error Message**: ${errorDetails.errorMessage || 'Not provided'} ## Diagnosis ${diagnosis.map(d => `- ${d}`).join('\n')} ## Recommended Solutions ${solutions.map((s, i) => `${i + 1}. ${s}`).join('\n')} ## Authentication Method Testing ${generateAuthMethodTests(authMethod, dhis2Instance)} ## Browser Settings Analysis ${browserSettings.cookiesEnabled !== undefined ? `- **Cookies Enabled**: ${browserSettings.cookiesEnabled ? 'Yes' : 'No'}` : ''} ${browserSettings.thirdPartyCookies !== undefined ? `- **Third-party Cookies**: ${browserSettings.thirdPartyCookies ? 'Enabled' : 'Disabled'}` : ''} ${browserSettings.sameSiteSettings ? `- **SameSite Settings**: ${browserSettings.sameSiteSettings}` : ''} ## Debug Commands ### Test Authentication Endpoint \`\`\`bash # Test basic authentication curl -X POST \\ -H "Content-Type: application/json" \\ -d '{"username":"your-username","password":"your-password"}' \\ ${dhis2Instance}/api/auth/login # Test current user endpoint curl -H "Authorization: Basic $(echo -n 'username:password' | base64)" \\ ${dhis2Instance}/api/me \`\`\` ### Network Analysis \`\`\`javascript // Browser console - check authentication headers fetch('${dhis2Instance}/api/me', { method: 'GET', headers: { 'Authorization': 'Basic ' + btoa('username:password') }, credentials: 'include' }).then(response => { console.log('Status:', response.status); console.log('Headers:', [...response.headers.entries()]); return response.json(); }).then(data => console.log('User data:', data)) .catch(err => console.error('Error:', err)); \`\`\` ## Browser Dev Tools Checklist 1. **Network Tab**: - [ ] Authentication request sent - [ ] Correct Authorization header present - [ ] Response status code - [ ] Set-Cookie headers in response 2. **Application Tab**: - [ ] Cookies stored correctly - [ ] Local/Session storage items - [ ] Cookie domain and path settings 3. **Console**: - [ ] No CORS errors - [ ] No cookie warnings - [ ] No security policy violations ## Common Authentication Patterns ### Basic Authentication \`\`\`javascript const credentials = btoa(\`\${username}:\${password}\`); fetch('/api/me', { headers: { 'Authorization': \`Basic \${credentials}\` } }); \`\`\` ### Cookie-based Authentication \`\`\`javascript // Login fetch('/dhis-web-commons-security/login.action', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: \`j_username=\${username}&j_password=\${password}\`, credentials: 'include' }); // Subsequent requests fetch('/api/me', { credentials: 'include' }); \`\`\` ## Environment-Specific Issues ### Development Environment - CORS configuration - Proxy authentication - Self-signed certificates - Local network restrictions ### Production Environment - Load balancer configuration - SSL/TLS certificate issues - Firewall restrictions - Session persistence ## Session Management Best Practices 1. **Session Timeout**: Configure appropriate timeout values 2. **Session Refresh**: Implement automatic session renewal 3. **Secure Storage**: Store credentials/tokens securely 4. **Logout Cleanup**: Clear all auth data on logout ## Security Considerations ⚠️ **Never log credentials in production** ⚠️ **Use HTTPS for authentication in production** ⚠️ **Implement proper session management** ⚠️ **Regular security audits of authentication flow** `; }
- src/index.ts:1164-1175 (registration)Tool registration and dispatch handler in the main MCP server. Calls the debugAuthentication function from debugging-helpers.ts with user arguments.case 'dhis2_debug_authentication': const authDebugArgs = args as any; const authAnalysis = debugAuthentication(authDebugArgs); return { content: [ { type: 'text', text: authAnalysis, }, ], };
- src/permission-system.ts:147-147 (registration)Permission registration mapping the tool to 'canDebugApplications' permission.['dhis2_debug_authentication', 'canDebugApplications'],
- src/debugging-helpers.ts:514-569 (helper)Helper function generateAuthMethodTests used by the handler to generate authentication testing commands for different auth methods.function generateAuthMethodTests(authMethod: string, dhis2Instance: string): string { switch (authMethod) { case 'basic': return `### Basic Authentication Test \`\`\`bash # Test basic auth credentials curl -v -u username:password ${dhis2Instance}/api/me # Check response headers curl -I -u username:password ${dhis2Instance}/api/me \`\`\``; case 'oauth2': return `### OAuth2 Authentication Test \`\`\`bash # Step 1: Get authorization code open "${dhis2Instance}/uaa/oauth/authorize?response_type=code&client_id=YOUR_CLIENT_ID&redirect_uri=YOUR_REDIRECT_URI" # Step 2: Exchange code for token curl -X POST \\ -H "Content-Type: application/x-www-form-urlencoded" \\ -d "grant_type=authorization_code&code=AUTH_CODE&redirect_uri=YOUR_REDIRECT_URI" \\ -u "CLIENT_ID:CLIENT_SECRET" \\ ${dhis2Instance}/uaa/oauth/token \`\`\``; case 'cookie': return `### Cookie-based Authentication Test \`\`\`bash # Test cookie authentication curl -c cookies.txt -b cookies.txt \\ -d "j_username=username&j_password=password" \\ -X POST \\ ${dhis2Instance}/dhis-web-commons-security/login.action # Test with saved cookies curl -b cookies.txt ${dhis2Instance}/api/me \`\`\``; case 'token': return `### Token-based Authentication Test \`\`\`bash # Get token TOKEN=$(curl -s -X POST \\ -H "Content-Type: application/json" \\ -d '{"username":"your-username","password":"your-password"}' \\ ${dhis2Instance}/api/auth/token | jq -r '.token') # Use token curl -H "Authorization: Bearer $TOKEN" ${dhis2Instance}/api/me \`\`\``; default: return '### Custom Authentication Test\n```bash\n# Add your authentication test commands here\n```'; } }