如何在Azure AD B2C自定义策略中取消密码首尾空格自动修剪?
Absolutely! You can disable Azure AD B2C's automatic password trimming behavior using custom policies, and it's straightforward to implement. Here's how to meet your client's requirement:
Step 1: Disable Trimming for the Password Claim
By default, Azure AD B2C trims leading/trailing whitespace for all string claims—including passwords. To override this, redefine the password ClaimType in your policy's ClaimsSchema section with the Trim="false" attribute:
<ClaimsSchema> <ClaimType Id="password"> <DisplayName>Password</DisplayName> <DataType>string</DataType> <AdminHelpText>Enter your account password</AdminHelpText> <UserHelpText>Enter your account password</UserHelpText> <UserInputType>Password</UserInputType> <Trim>false</Trim> <!-- Critical: Disables automatic whitespace trimming --> </ClaimType> </ClaimsSchema>
This ensures the raw password input (including any leading/trailing spaces) is preserved when passed to the authentication step.
Step 2: Update the Login Technical Profile
Next, confirm the self-asserted technical profile that collects the password (typically SelfAsserted-LocalAccountSignin-Email) references this untrimmed claim. You don’t need major changes here—just ensure the profile uses the password claim without any trimming transformations.
Step 3: Validate the Untrimmed Password
With trimming disabled, the raw password input will be sent directly to the authentication validation technical profile (like login-NonInteractive). If a user enters a password with leading/trailing spaces that doesn’t match their stored password (which lacks those spaces), Azure AD B2C will return the standard "Invalid username or password" error—exactly what your client wants.
Optional: Add a Custom Error for Whitespace
If your client wants explicit feedback instead of the generic error message, you can add a claims transformation to detect leading/trailing spaces and throw a custom error before authentication:
- Add the transformation to detect whitespace:
<ClaimsTransformations> <ClaimsTransformation Id="BlockPasswordWhitespace" TransformationMethod="AssertStringDoesNotMatchRegex"> <InputClaims> <InputClaim ClaimTypeReferenceId="password" TransformationClaimType="inputClaim" /> </InputClaims> <InputParameters> <InputParameter Id="regex" DataType="string" Value="^\s+|\s+$" /> <InputParameter Id="message" DataType="string" Value="Password cannot contain leading or trailing spaces." /> </InputParameters> </ClaimsTransformation> </ClaimsTransformations>
- Attach it to the self-asserted login profile:
<TechnicalProfile Id="SelfAsserted-LocalAccountSignin-Email"> <OutputClaimsTransformations> <OutputClaimsTransformation ReferenceId="BlockPasswordWhitespace" /> </OutputClaimsTransformations> </TechnicalProfile>
This will immediately show a clear error if the user enters a password with leading/trailing spaces, instead of proceeding to the authentication check.
内容的提问来源于stack exchange,提问作者Zahra Saniepour

