Búsqueda de sitios web

[PowerShell] Habilite MFA para usuarios de Office 365


Si no tiene una licencia Premium de Azure AD, solo tiene dos opciones para habilitar MFA para sus usuarios de Office 365: actívelo para todos los usuarios con los valores predeterminados de seguridad o manualmente para cada usuario en el Centro de administración > Usuarios activos > Múltiples. -autenticación de factor.

Habilitar MFA para cada usuario manualmente puede ser una tarea espantosa y es algo que tendrás que hacer cada vez que crees un nuevo usuario. Con PowerShell, podemos seleccionar fácilmente un grupo de usuarios y habilitar MFA para ellos.

Si incluso lo combina con el script para buscar usuarios sin MFA habilitado, puede automatizar todo el proceso.

Habilite la autenticación multifactor para usuarios de Office 365 con PowerShell

Antes de comenzar a habilitar MFA en Office 365 con PowerShell, debemos conectarnos al servicio en línea de Microsoft:

Connect-MsolService

Para habilitar MFA con PowerShell, primero debemos crear un objeto StrongAuthenticationRequirement con los parámetros requeridos. A continuación, podemos configurar este objeto en cada usuario para el que queramos habilitar MFA.

# Create the StrongAuthenticationRequirement Object
$sa = New-Object -TypeName Microsoft.Online.Administration.StrongAuthenticationRequirement
$sa.RelyingParty = "*"
$sa.State = "Enabled"
$sar = @($sa)

# Enable MFA for the user
Set-MsolUser -UserPrincipalName $user -StrongAuthenticationRequirements $sar

He incluido esto en una función para que podamos canalizarlo fácilmente detrás de otro cmdlet (para seleccionar los usuarios o en función de un archivo CSV). La función intentará habilitar MFA para cada usuario y generará un objeto con los usuarios y el estado de MFA.

Function Set-MFAforUser {
<#
  .Synopsis
    Enables MFA for an Office 365 User

  .DESCRIPTION
    Enable MFA for a user, you can turn it on for a single user or input a list of users

  .NOTES
    Name: Set-MFAforUser
    Author: R. Mens - LazyAdmin.nl
    Version: 1.0
    DateCreated: jan 2021
    Purpose/Change: Initial script development

  .LINK
    https://lazyadmin.nl

  .EXAMPLE
    Set-MFAforUser -UserPrincipalName johndoe@contoso.com

    Enable MFA for the user John Doe

  .EXAMPLE
	  Import-Csv -Delimiter ";" -Path ("path\to\file\users-to-enable.csv") | Foreach-Object { Set-MFAforUser $_.UserPrincipalName }

    Enable MFA for all users in a CSV file
#>
 [CmdletBinding(DefaultParameterSetName="Default")]
  param(
    [Parameter(
      Mandatory = $true,
      ValueFromPipeline = $true,
      ValueFromPipelineByPropertyName = $true,
      ParameterSetName  = "UserPrincipalName",
      Position = 0
      )]
    # Enter a single UserPrincipalName or a comma separted list of UserPrincipalNames
    [string[]]$UserPrincipalName
	)

Begin {}

Process {
	if ($PSBoundParameters.ContainsKey('UserPrincipalName')) {
		foreach ($user in $UserPrincipalName) {
			try {
		    # Src: https://docs.microsoft.com/en-us/azure/active-directory/authentication/howto-mfa-userstates
		    $sa = New-Object -TypeName Microsoft.Online.Administration.StrongAuthenticationRequirement
		    $sa.RelyingParty = "*"
		    $sa.State = "Enabled"
		    $sar = @($sa)

		    # Change the following UserPrincipalName to the user you wish to change state
		    Set-MsolUser -UserPrincipalName $user -StrongAuthenticationRequirements $sar -ErrorAction Stop

		    [PSCustomObject]@{
			    UserPrincipalName = $user
			    MFAEnabled        = $true
		    }
	    }
	    catch {
		    [PSCustomObject]@{
			    UserPrincipalName = $user
			    MFAEnabled        = $false
		    }
	    }
	 }
	}else{
		Write-Verbose "No UserPrincipalName given"
	}
  }
}

También puedes encontrar el script completo aquí en mi GitHub.

Excluyendo usuarios

Si necesita excluir usuarios o cuentas del script, puede agregarle la siguiente parte:

# Create a list of excluded accounts
$exclusions = @("archive@lazyadmin.nl",
                "info@lazyadmin.onmicrosoft.com")

# Replace the following line (160 in the complete script above)
$MsolUsers = Get-MsolUser -EnabledFilter EnabledOnly -MaxResults $MaxResults | Where-Object {$_.IsLicensed -eq $isLicensed} | Sort-Object UserPrincipalName

# With this
$MsolUsers = Get-MsolUser -EnabledFilter EnabledOnly -MaxResults $MaxResults | 
            Where-Object {$_.IsLicensed -eq $true -and $_.UserPrincipalName -notin $exclusions -and !$_.StrongAuthenticationMethods -and !$_.StrongAuthenticationRequirements} | 
            Sort-Object UserPrincipalName

Concluyendo

Activar MFA es realmente importante cuando se trata de proteger su entorno. Los valores predeterminados de seguridad son una excelente solución para inquilinos más pequeños, pero no funcionan cuando tienes cuentas del sistema, por ejemplo. Al usar PowerShell y una tarea programada, aún puedes automatizar MFA en Office 365, manteniendo tus cuentas seguras.

Si tiene alguna pregunta, simplemente deje un comentario a continuación.

Artículos relacionados