# Automating Microsoft Entra ID PIM Role Activation with PowerShell and Microsoft Graph

Managing Microsoft Entra ID roles through Privileged Identity Management (PIM) can be repetitive and time-consuming, especially for administrators who frequently activate roles. To streamline this process while maintaining robust security, I developed a PowerShell script that automates role activation using Microsoft Graph with full Multi-Factor Authentication (MFA) support.

**Version 2.0 Update**: After receiving feedback and conducting a thorough security review, I've significantly enhanced the script with security hardening, input validation, audit logging, and adherence to the principle of least privilege.

---

## 🔧 Key Features

### Core Functionality
- **🔐 Secure Connection**: Establishes connection to Microsoft Graph with minimal required permissions (only 3 scopes instead of 5)
- **👤 User Context Retrieval**: Automatically fetches the current user context to identify eligible roles
- **⚡ Automated Activation**: Streamlines the role activation process with intelligent prompts
- **📋 Interactive Selection**: Clear, numbered menu when multiple roles are available
- **⏱️ Configurable Duration**: Set activation duration from 1-8 hours (default: 4 hours)
- **✅ Explicit Confirmation**: Type "ACTIVATE" to confirm and prevent accidental activations

### Security Enhancements (New in v2.0)
- **🛡️ Least Privilege**: Reduced Microsoft Graph scopes by 40% - uses only what's essential
- **✅ Input Validation**: Comprehensive validation with 20-500 character requirement for justifications
- **🧹 Input Sanitization**: Automatic cleaning of potentially dangerous characters
- **📝 Audit Logging**: Persistent JSON logs for compliance and security monitoring
- **🔒 Data Protection**: Sensitive information (like Request IDs) never displayed to console
- **🎯 Error Handling**: Sanitized error messages with helpful troubleshooting guidance

---

## 💻 How It Works

The script follows a secure, step-by-step process:

1. **Clean State**: Disconnects any existing Microsoft Graph sessions to ensure a fresh start
2. **Secure Authentication**: Connects with only 3 essential scopes (reduced from 5):
   - `RoleAssignmentSchedule.ReadWrite.Directory` - For self-activation
   - `Directory.Read.All` - For reading role information  
   - `User.Read` - For user profile access
3. **User Verification**: Validates the current user and retrieves their context
4. **Role Discovery**: Fetches all eligible PIM roles for the authenticated user
5. **Interactive Selection**: If multiple roles exist, displays a clear numbered menu
6. **Duration Configuration**: Prompts for activation duration (1-8 hours, default 4)
7. **Justification Input**: Requires meaningful justification (minimum 20 characters) with automatic sanitization
8. **Confirmation Summary**: Shows all details and requires typing "ACTIVATE" to proceed
9. **Secure Activation**: Submits the activation request with MFA support
10. **Verification**: Confirms the role is active and displays expiration time
11. **Audit Trail**: Logs the entire transaction to local audit file for compliance

All actions are logged to `%LOCALAPPDATA%\PIMActivation\audit.log` in JSON format for easy parsing and compliance reporting.

---

## 🔒 Security Improvements - What Changed

### Before (v1.0)
❌ 5 Microsoft Graph scopes (over-privileged)  
❌ No input validation  
❌ No audit logging  
❌ Sensitive data exposed in console  
❌ Generic justifications accepted  
❌ No explicit confirmation

### After (v2.0)
✅ 3 Microsoft Graph scopes (least privilege)  
✅ Comprehensive input validation  
✅ Full audit logging with JSON format  
✅ Sensitive data protected  
✅ Enforced 20-character minimum justifications  
✅ Explicit "ACTIVATE" confirmation required

---

## 📊 Real-World Example

Here's what the improved experience looks like:
```powershell
===================================================================
  PIM Role Activation Script - Secured Version 2.0
===================================================================

Connecting to Microsoft Graph...
✓ Successfully connected to Microsoft Graph
✓ Connected as: admin@contoso.com
✓ Found 3 eligible role(s)

===================================================================
  Available Roles for Activation
===================================================================
1. Global Reader
2. Security Administrator
3. User Administrator

Enter the number of the role to activate (1-3): 1

Selected role: Global Reader

-------------------------------------------------------------------
Duration Configuration
-------------------------------------------------------------------
Enter activation duration in hours (1-8, default: 4): 4
✓ Duration set to: 4 hour(s)

-------------------------------------------------------------------
Justification (minimum 20 characters)
-------------------------------------------------------------------
Enter justification for role activation: Monthly security review and compliance audit
✓ Justification validated

===================================================================
  Activation Summary
===================================================================
Role:          Global Reader
Duration:      4 hour(s)
Justification: Monthly security review and compliance audit...
User:          admin@contoso.com
===================================================================

⚠️  This will activate privileged access. Ensure you have authorization.

Type 'ACTIVATE' to confirm (case-sensitive): ACTIVATE

✅ Role activation successful!

Currently Active Roles:
  ✓ Global Reader (Expires: 2025-11-02 18:30:00 UTC)

✓ Script completed successfully
===================================================================
  Audit log: C:\Users\Admin\AppData\Local\PIMActivation\audit.log
===================================================================
```

---

## 📂 Access the Script

You can find the updated script on my GitHub repository: [Activate-EntraIDPIMRole.ps1](https://github.com/bitnash/m365-powershell-scripts/tree/main/entra-pim-select/)

**What's Included:**
- ✅ Complete PowerShell script (v2.0)
- ✅ Comprehensive README with security details
- ✅ Usage examples and troubleshooting guide
- ✅ Audit log format documentation

Feel free to clone the repository, test the script in your environment, and customize it to fit your organization's security policies and compliance requirements.

---

## 🛡️ Security Considerations

When using this script in production:

1. **Review Audit Logs Regularly**: Check `%LOCALAPPDATA%\PIMActivation\audit.log` for unusual patterns
2. **Use Minimum Duration**: Only activate roles for as long as needed
3. **Provide Clear Justifications**: Always document why you're activating privileged access
4. **Test First**: Run in a non-production environment before deploying
5. **Follow Policies**: Ensure compliance with your organization's security policies
6. **Monitor Failed Attempts**: Investigate repeated activation failures

---

## 📣 Feedback and Contributions

The security improvements in v2.0 came directly from community feedback and security reviews. I'm always open to more suggestions!

**How to Contribute:**
- 🐛 Found a bug? [Open an issue](https://github.com/bitnash/m365-powershell-scripts/issues)
- 💡 Have an enhancement idea? Submit a pull request
- 🔒 Identified a security concern? Please report it responsibly
- 📖 Want to improve documentation? Contributions welcome!

---

## 🎯 What's Next?

I'm considering these enhancements for future versions:

- 🔔 **Notification System**: Alerts when roles are about to expire
- 📊 **Reporting Dashboard**: Visual analytics from audit logs
- 🤖 **Scheduled Activations**: Pre-approved activation windows
- 🔗 **Integration with Ticketing Systems**: Link to ITSM tickets

Let me know in the comments which features would be most valuable for your environment!

---

## 📚 Related Resources

- [Microsoft Entra PIM Documentation](https://learn.microsoft.com/entra/id-governance/privileged-identity-management/)
- [Microsoft Graph PowerShell SDK](https://learn.microsoft.com/powershell/microsoftgraph/)
- [PIM Best Practices Guide](https://learn.microsoft.com/entra/id-governance/privileged-identity-management/pim-deployment-plan)

---

**Update History:**
- **v2.0** (Nov 2025): Security hardening, audit logging, input validation
- **v1.0** (Initial): Basic PIM role activation automation

---

*Have you implemented PIM automation in your environment? What security considerations were most important to you? Share your experience in the comments below!*
