Может ли Azure-AD B2C использовать номер мобильного телефона в качестве имени пользователя? - PullRequest
0 голосов
/ 31 декабря 2018

У нас есть мобильное приложение и веб-сайт.Мы хотели бы использовать Azure AD-B2C для аутентификации.Мы не собираемся разрешать какую-либо стороннюю аутентификацию, а просто используем Azure AD в отдельном домене.

Мы бы предпочли использовать номер телефона пользователя.Мои исследования показывают, что эта функция запрошена , но в настоящее время не существует.

Есть ли какие-либо обходные пути для этого, или эта функция была реализована, и я пропустил ее?

Ответы [ 2 ]

0 голосов
/ 04 января 2019

Это может быть реализовано как пользовательская политика , из SocialAndLocalAccountsWithMfa стартовый пакет , где номер телефона конечного пользователя хранится как имя для входасо следующими изменениями.

1) Создать пользовательский атрибут с именем PhoneVerified типа Boolean , чтобы указать, является ли номер телефона конечного пользователя

2) В файле TrustFrameworkBase.xml добавьте следующие типы утверждений в схему утверждений:

i.Тип заявки phone для представления способа ввода номера телефона конечного пользователя. E.164 - обязательный формат этого типа претензии:

<ClaimType Id="phone">
  <DisplayName>Phone Number</DisplayName>
  <DataType>string</DataType>
  <UserInputType>TextBox</UserInputType>
  <Restriction>
    <Pattern RegularExpression="^\+[0-9]{7,15}$" HelpText="Please enter a valid phone number." />
  </Restriction>
</ClaimType>

ii. signInNames.phoneNumber тип заявления, чтобы указать, как сохраняется номер телефона конечного пользователя:

<ClaimType Id="signInNames.phoneNumber">
  <DisplayName>Phone Number</DisplayName>
  <DataType>string</DataType>
  <UserInputType>TextBox</UserInputType>
</ClaimType>

iii.Тип заявки extension_PhoneVerified , показывающий, был ли проверен номер телефона конечного пользователя:

<ClaimType Id="extension_PhoneVerified">
  <DisplayName>Phone Number Verified</DisplayName>
  <DataType>boolean</DataType>
</ClaimType>

3) В файле TrustFrameworkBase.xml добавьте LocalAccountSignUpWithLogonPhone технический профиль для локальной учетной записи поставщика утверждений и AAD-UserWriteUsingLogonPhone технического профиля для Azure Active Directory поставщика утверждений для регистрации новогоконечный пользователь с номером телефона:

<TechnicalProfile Id="LocalAccountSignUpWithLogonPhone">
  <DisplayName>Phone signup</DisplayName>
  <Protocol Name="Proprietary" Handler="Web.TPEngine.Providers.SelfAssertedAttributeProvider, Web.TPEngine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
  <Metadata>
    <Item Key="IpAddressClaimReferenceId">IpAddress</Item>
    <Item Key="ContentDefinitionReferenceId">api.localaccountsignup</Item>
    <Item Key="language.button_continue">Create</Item>
  </Metadata>
  <CryptographicKeys>
    <Key Id="issuer_secret" StorageReferenceId="B2C_1A_TokenSigningKeyContainer" />
  </CryptographicKeys>
  <OutputClaims>
    <OutputClaim ClaimTypeReferenceId="objectId" />
    <OutputClaim ClaimTypeReferenceId="phone" Required="true" />
    <OutputClaim ClaimTypeReferenceId="newPassword" Required="true" />
    <OutputClaim ClaimTypeReferenceId="reenterPassword" Required="true" />
    <OutputClaim ClaimTypeReferenceId="executed-SelfAsserted-Input" DefaultValue="true" />
    <OutputClaim ClaimTypeReferenceId="authenticationSource" />
    <OutputClaim ClaimTypeReferenceId="newUser" />
    <!-- Optional claims, to be collected from the user -->
    <OutputClaim ClaimTypeReferenceId="displayName" />
    <OutputClaim ClaimTypeReferenceId="givenName" />
    <OutputClaim ClaimTypeReferenceId="surname" />
  </OutputClaims>
  <ValidationTechnicalProfiles>
    <ValidationTechnicalProfile ReferenceId="AAD-UserWriteUsingLogonPhone" />
  </ValidationTechnicalProfiles>
  <UseTechnicalProfileForSessionManagement ReferenceId="SM-AAD" />
</TechnicalProfile>
<TechnicalProfile Id="AAD-UserWriteUsingLogonPhone">
  <Metadata>
    <Item Key="Operation">Write</Item>
    <Item Key="RaiseErrorIfClaimsPrincipalAlreadyExists">true</Item>
  </Metadata>
  <IncludeInSso>false</IncludeInSso>
  <InputClaims>
    <InputClaim ClaimTypeReferenceId="phone" PartnerClaimType="signInNames.phoneNumber" Required="true" />
  </InputClaims>
  <PersistedClaims>
    <!-- Required claims -->
    <PersistedClaim ClaimTypeReferenceId="phone" PartnerClaimType="signInNames.phoneNumber" />
    <PersistedClaim ClaimTypeReferenceId="newPassword" PartnerClaimType="password"/>
    <PersistedClaim ClaimTypeReferenceId="displayName" DefaultValue="unknown" />
    <PersistedClaim ClaimTypeReferenceId="passwordPolicies" DefaultValue="DisablePasswordExpiration" />
    <PersistedClaim ClaimTypeReferenceId="extension_PhoneVerified" DefaultValue="false" AlwaysUseDefaultValue="true" />
    <!-- Optional claims. -->
    <PersistedClaim ClaimTypeReferenceId="givenName" />
    <PersistedClaim ClaimTypeReferenceId="surname" />
  </PersistedClaims>
  <OutputClaims>
    <OutputClaim ClaimTypeReferenceId="objectId" />
    <OutputClaim ClaimTypeReferenceId="newUser" PartnerClaimType="newClaimsPrincipalCreated" />
    <OutputClaim ClaimTypeReferenceId="authenticationSource" DefaultValue="localAccountAuthentication" />
    <OutputClaim ClaimTypeReferenceId="userPrincipalName" />
    <OutputClaim ClaimTypeReferenceId="signInNames.phoneNumber" />
  </OutputClaims>
  <IncludeTechnicalProfile ReferenceId="AAD-Common" />
  <UseTechnicalProfileForSessionManagement ReferenceId="SM-AAD" />
</TechnicalProfile>

Номер телефона конечного пользователя сохраняется как имя для входа типа номер телефона и является ли телефон конечного пользователяподтверждено, что для номера установлено значение false .

4) В файле TrustFrameworkBase.xml добавьте техническую информацию SelfAsserted-LocalAccountSignin-Phone профиль для локальной учетной записи провайдера утверждений, для входа в систему существующего конечного пользователя с номером телефона:

<TechnicalProfile Id="SelfAsserted-LocalAccountSignin-Phone">
  <DisplayName>Local Account Signin</DisplayName>
  <Protocol Name="Proprietary" Handler="Web.TPEngine.Providers.SelfAssertedAttributeProvider, Web.TPEngine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
  <Metadata>
    <Item Key="SignUpTarget">SignUpWithLogonPhoneExchange</Item>
    <Item Key="setting.operatingMode">Username</Item>
    <Item Key="ContentDefinitionReferenceId">api.selfasserted</Item>
  </Metadata>
  <IncludeInSso>false</IncludeInSso>
  <InputClaims>
    <InputClaim ClaimTypeReferenceId="signInName" />
  </InputClaims>
  <OutputClaims>
    <OutputClaim ClaimTypeReferenceId="signInName" Required="true" />
    <OutputClaim ClaimTypeReferenceId="password" Required="true" />
    <OutputClaim ClaimTypeReferenceId="objectId" />
    <OutputClaim ClaimTypeReferenceId="authenticationSource" />
  </OutputClaims>
  <ValidationTechnicalProfiles>
    <ValidationTechnicalProfile ReferenceId="login-NonInteractive" />
  </ValidationTechnicalProfiles>
  <UseTechnicalProfileForSessionManagement ReferenceId="SM-AAD" />
</TechnicalProfile>

Для параметра setting.operatingMode установлено значение to Имя пользователя , чтобы поле идентификатора входа не имело требуемого формата адреса электронной почты.

5) В файле TrustFrameworkBase.xml добавьте AAD-UserReadForPhoneUsingObjectId для поставщика утверждений Azure Active Directory , для получения объекта конечного пользователя, включая профиль телефона:

<TechnicalProfile Id="AAD-UserReadForPhoneUsingObjectId">
  <Metadata>
    <Item Key="Operation">Read</Item>
    <Item Key="RaiseErrorIfClaimsPrincipalDoesNotExist">true</Item>
  </Metadata>
  <IncludeInSso>false</IncludeInSso>
  <InputClaims>
    <InputClaim ClaimTypeReferenceId="objectId" Required="true" />
  </InputClaims>
  <OutputClaims>
    <OutputClaim ClaimTypeReferenceId="signInNames.phoneNumber" />
    <OutputClaim ClaimTypeReferenceId="displayName" />
    <OutputClaim ClaimTypeReferenceId="givenName" />
    <OutputClaim ClaimTypeReferenceId="surname" />
    <OutputClaim ClaimTypeReferenceId="extension_PhoneVerified" />
  </OutputClaims>
  <IncludeTechnicalProfile ReferenceId="AAD-Common" />
</TechnicalProfile>

6) В TrustFrameworkBase.xml , добавьте технический профиль PhoneFactor-Verify к поставщику утверждений Phone Factor для проверки номера телефона конечного пользователя:

<TechnicalProfile Id="PhoneFactor-Verify">
  <DisplayName>PhoneFactor</DisplayName>
  <Protocol Name="Proprietary" Handler="Web.TPEngine.Providers.PhoneFactorProtocolProvider, Web.TPEngine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
  <Metadata>
    <Item Key="ContentDefinitionReferenceId">api.phonefactor</Item>
    <Item Key="ManualPhoneNumberEntryAllowed">false</Item>
  </Metadata>
  <CryptographicKeys>
    <Key Id="issuer_secret" StorageReferenceId="B2C_1A_TokenSigningKeyContainer" />
  </CryptographicKeys>
  <InputClaimsTransformations>
    <InputClaimsTransformation ReferenceId="CreateUserIdForMFA" />
  </InputClaimsTransformations>
  <InputClaims>
    <InputClaim ClaimTypeReferenceId="userIdForMFA" PartnerClaimType="userId" />
    <InputClaim ClaimTypeReferenceId="signInNames.phoneNumber" PartnerClaimType="strongAuthenticationPhoneNumber" />
  </InputClaims>
  <OutputClaims>
    <OutputClaim ClaimTypeReferenceId="signInNames.phoneNumber" PartnerClaimType="Verified.strongAuthenticationPhoneNumber" />
  </OutputClaims>
  <UseTechnicalProfileForSessionManagement ReferenceId="SM-MFA" />
</TechnicalProfile>

7) В файле TrustFrameworkBase.xml добавьте технический профиль UserWritePhoneVerifiedUsingObjectId к поставщику утверждений Azure Active Directory , чтобы указать, должен ли конечныйномер телефона пользователя подтвержден на true :

<TechnicalProfile Id="AAD-UserWritePhoneNumberUsingObjectId">
  <Metadata>
    <Item Key="Operation">Write</Item>
    <Item Key="RaiseErrorIfClaimsPrincipalAlreadyExists">false</Item>
    <Item Key="RaiseErrorIfClaimsPrincipalDoesNotExist">true</Item>
  </Metadata>
  <IncludeInSso>false</IncludeInSso>
  <InputClaims>
    <InputClaim ClaimTypeReferenceId="objectId" Required="true" />
  </InputClaims>
  <PersistedClaims>
    <PersistedClaim ClaimTypeReferenceId="objectId" />
    <PersistedClaim ClaimTypeReferenceId="extension_PhoneVerified" DefaultValue="true" AlwaysUseDefaultValue="true" />
  </PersistedClaims>
  <IncludeTechnicalProfile ReferenceId="AAD-Common" />
</TechnicalProfile>

Примечание: Дополнительные технические профили должны быть добавлены в TrustFrameworkBase.xml файл, позволяющий существующему конечному пользователю сбросить свой текущий пароль, используя номер телефона, но это было оставлено в качестве упражнения для читателя.

8) В TrustFrameworkBase.xml файл, добавьте SignUpOrSignInForPhone путешествие пользователя, которое позволяет либо новому конечному пользователю зарегистрироваться по номеру телефона, либо существующему конечному пользователю войти в систему с помощью номера телефона, а затем подтвердитьномер телефона конечного пользователя.

<UserJourney Id="SignUpOrSignInForPhone">
  <OrchestrationSteps>

    <!-- Display the sign-up or sign-in interaction so an existing end-user can sign in with a phone number -->      
    <OrchestrationStep Order="1" Type="CombinedSignInAndSignUp" ContentDefinitionReferenceId="api.signuporsignin">
      <ClaimsProviderSelections>
        <ClaimsProviderSelection ValidationClaimsExchangeId="LocalAccountSigninPhoneExchange" />
      </ClaimsProviderSelections>
      <ClaimsExchanges>
        <ClaimsExchange Id="LocalAccountSigninPhoneExchange" TechnicalProfileReferenceId="SelfAsserted-LocalAccountSignin-Phone" />
      </ClaimsExchanges>
    </OrchestrationStep>

    <!-- A new end-user has selected to sign up with a phone number -->
    <OrchestrationStep Order="2" Type="ClaimsExchange">
      <Preconditions>
        <Precondition Type="ClaimsExist" ExecuteActionsIf="true">
          <Value>objectId</Value>
          <Action>SkipThisOrchestrationStep</Action>
        </Precondition>
      </Preconditions>
      <ClaimsExchanges>
        <ClaimsExchange Id="SignUpWithLogonPhoneExchange" TechnicalProfileReferenceId="LocalAccountSignUpWithLogonPhone" />
      </ClaimsExchanges>
    </OrchestrationStep>

    <!-- Read the user object -->
    <OrchestrationStep Order="3" Type="ClaimsExchange">
      <ClaimsExchanges>
        <ClaimsExchange Id="AADUserReadWithObjectId" TechnicalProfileReferenceId="AAD-UserReadForPhoneUsingObjectId" />
      </ClaimsExchanges>
    </OrchestrationStep>

    <!-- If the end-user's phone number hasn't been verified, then verify it during sign-up or following the first sign-in with an unverified phone number -->
    <OrchestrationStep Order="4" Type="ClaimsExchange">
      <Preconditions>
        <Precondition Type="ClaimEquals" ExecuteActionsIf="true">
          <Value>extension_PhoneVerified</Value>
          <Value>True</Value>
          <Action>SkipThisOrchestrationStep</Action>
        </Precondition>
        <Precondition Type="ClaimsExist" ExecuteActionsIf="true">
          <Value>isActiveMFASession</Value>
          <Action>SkipThisOrchestrationStep</Action>
        </Precondition>
      </Preconditions>
      <ClaimsExchanges>
        <ClaimsExchange Id="PhoneFactor-Verify" TechnicalProfileReferenceId="PhoneFactor-Verify" />
      </ClaimsExchanges>
    </OrchestrationStep>

    <!-- Set whether the end-user's phone number has been verified to true -->
    <OrchestrationStep Order="5" Type="ClaimsExchange">
      <Preconditions>
        <Precondition Type="ClaimEquals" ExecuteActionsIf="true">
          <Value>extension_PhoneVerified</Value>
          <Value>True</Value>
          <Action>SkipThisOrchestrationStep</Action>
        </Precondition>
        <Precondition Type="ClaimsExist" ExecuteActionsIf="true">
          <Value>isActiveMFASession</Value>
          <Action>SkipThisOrchestrationStep</Action>
        </Precondition>
      </Preconditions>
      <ClaimsExchanges>
        <ClaimsExchange Id="AADUserWriteWithObjectId" TechnicalProfileReferenceId="AAD-UserWritePhoneVerifiedUsingObjectId" />
      </ClaimsExchanges>
    </OrchestrationStep>

    <OrchestrationStep Order="6" Type="SendClaims" CpimIssuerTechnicalProfileReferenceId="JwtIssuer" />

  </OrchestrationSteps>
</UserJourney>

9) Создайте файл проверяющей стороны с именем SignUpOrSignInForPhone.xml (или аналогичный) и укажите ссылку SignUpOrSignInForPhone путешествие пользователя:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<TrustFrameworkPolicy
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema"
    xmlns="http://schemas.microsoft.com/online/cpim/schemas/2013/06"
    PolicySchemaVersion="0.3.0.0"
    TenantId="yourtenant.onmicrosoft.com"
    PolicyId="B2C_1A_signup_signin_phone"
    PublicPolicyUri="http://yourtenant.onmicrosoft.com/B2C_1A_signup_signin_phone">
  <BasePolicy>
    <TenantId>yourtenant.onmicrosoft.com</TenantId>
    <PolicyId>B2C_1A_TrustFrameworkExtensions</PolicyId>
  </BasePolicy>
  <RelyingParty>
    <DefaultUserJourney ReferenceId="SignUpOrSignInForPhone" />
    <TechnicalProfile Id="PolicyProfile">
      <DisplayName>PolicyProfile</DisplayName>
      <Protocol Name="OpenIdConnect" />
      <OutputClaims>
        <OutputClaim ClaimTypeReferenceId="objectId" PartnerClaimType="sub" />
        <OutputClaim ClaimTypeReferenceId="displayName" />
        <OutputClaim ClaimTypeReferenceId="givenName" />
        <OutputClaim ClaimTypeReferenceId="surname" />
        <OutputClaim ClaimTypeReferenceId="signInNames.phoneNumber" PartnerClaimType="phone_number" />
        <OutputClaim ClaimTypeReferenceId="extension_PhoneNumber" PartnerClaimType="phone_number_verified" />
      </OutputClaims>
      <SubjectNamingInfo ClaimType="sub" />
    </TechnicalProfile>
  </RelyingParty>
</TrustFrameworkPolicy>

Заявки на токены, которые выводятся проверяющей стороне, включают:

i.Заявка phone_number , представляющая номер телефона конечного пользователя.

ii. phone_number_verified утверждает, что указывает, был ли проверен номер телефона конечного пользователя.

0 голосов
/ 02 января 2019

Я мог бы использовать номер мобильного телефона, чтобы зарегистрироваться в качестве имени пользователя для локального пользователя во встроенной политике входа или регистрации.Процесс, подобный следующему:

enter image description here

И результат:

enter image description here

Или вы также можете использовать собственную политику, чтобы сделать это, как сказал Крис Паджетт.

...