Сообщения об ошибках при вызове REST API не отображаются в настраиваемой политике B2C

У меня есть самопровозглашенный технический профиль в моей настраиваемой политике, у него есть технический профиль проверки, который является вызовом REST API (функция Azure). Я не вызываю функцию azure напрямую из политики, из политики вызовет azure APIM, а APIM передаст запрос в функцию azure.

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

return new OkObjectResult(new ResponseContentModel
      {
       userMessage = "Sorry, Please provide valid information ",
       status = 409,
       retryCounter = data.RetryCounter
     });

Мой технический профиль следующий:

<TechnicalProfile Id="Registration">
          <DisplayName>Email 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">Activate Account</Item>
            <!-- Sample: Remove sign-up email verification -->
            <Item Key="EnforceEmailVerification">False</Item>
            <Item Key="setting.retryLimit">5</Item>
          </Metadata>
          <InputClaimsTransformations>
            <!--Sample: Copy the email to ReadOnlyEamil claim type-->  
            <InputClaimsTransformation ReferenceId="CreateReadOnlyEmailAddress" />
          </InputClaimsTransformations>
          <InputClaims>
            <InputClaim ClaimTypeReferenceId="email" />
            <InputClaim ClaimTypeReferenceId="givenName" />
            <InputClaim ClaimTypeReferenceId="surname" />
          </InputClaims>
          <OutputClaims>
            <OutputClaim ClaimTypeReferenceId="objectId" DefaultValue="123" />
            <OutputClaim ClaimTypeReferenceId="newPassword" Required="true" />
            <OutputClaim ClaimTypeReferenceId="reenterPassword" Required="true" />
            <OutputClaim ClaimTypeReferenceId="tncCheckbox" Required="true" />

            <OutputClaim ClaimTypeReferenceId="retryCounter" DefaultValue="0" />
            <OutputClaim ClaimTypeReferenceId="isFound" DefaultValue="false" />
            <OutputClaim ClaimTypeReferenceId="executed-SelfAsserted-Input" DefaultValue="true" />
            <OutputClaim ClaimTypeReferenceId="authenticationSource" DefaultValue="localAccountAuthentication"/>
            <OutputClaim ClaimTypeReferenceId="newUser" DefaultValue="true" />
          </OutputClaims>
          <ValidationTechnicalProfiles>
            <ValidationTechnicalProfile ReferenceId="API-Validate-UserInfo" />
            <ValidationTechnicalProfile ReferenceId="AAD-UserWriteUsingLogonEmail" />
          </ValidationTechnicalProfiles>
          <UseTechnicalProfileForSessionManagement ReferenceId="SM-Noop" />
        </TechnicalProfile>

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

<TechnicalProfile Id="API-Validate-UserInfo">
                <DisplayName>User OTP Notifications</DisplayName>    
                <Protocol Name="Proprietary" Handler="Web.TPEngine.Providers.RestfulProvider, Web.TPEngine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
                <Metadata>
                  <Item Key="ServiceUrl">https://myapimurl</Item>
                  <Item Key="SendClaimsIn">Body</Item>                        
                  <Item Key="AuthenticationType">ClientCertificate</Item>
                </Metadata>
                <CryptographicKeys>
                    <Key Id="ClientCertificate" StorageReferenceId="B2C_1A_APIMClientCertificate" />
                </CryptographicKeys>
                <InputClaims>
                    <InputClaim ClaimTypeReferenceId="givenName" PartnerClaimType="GivenName" />
                    <InputClaim ClaimTypeReferenceId="surname" PartnerClaimType="SurName"/>
                    <InputClaim ClaimTypeReferenceId="email" PartnerClaimType="Email"/>
                    <InputClaim ClaimTypeReferenceId="retryCounter" PartnerClaimType="RetryCounter"/>
                </InputClaims>
                <OutputClaims>
                  <OutputClaim ClaimTypeReferenceId="retryCounter" />
                  <OutputClaim ClaimTypeReferenceId="isFound" />
                </OutputClaims>
                <UseTechnicalProfileForSessionManagement ReferenceId="SM-Noop" />
            </TechnicalProfile>

В пользовательском интерфейсе отображается сообщение об ошибке:

Обмен утверждений API-Validate-UserInfo, указанный на шаге 5, вернул HTTP-ответ об ошибке с кодом BadRequest и причиной «Плохой запрос».

Что касается функции, я использую .net core 3.1, а версия выполнения функции - ~ 3.


person Alex    schedule 20.05.2020    source источник
comment
Подозреваю, потому что то, что отправляет B2C, на самом деле возвращает неверный запрос HTTP 400, а не ваш собственный ответ HTTP 409. Работает ли это при хорошем сценарии?   -  person Jas Suri - MSFT    schedule 20.05.2020
comment
@JasSuri Да, он работает правильно при возврате OkObjectResult   -  person Alex    schedule 20.05.2020
comment
@JasSuri Я попытался изменить тип результата возврата на ConflictObjectResult, теперь отображается сообщение об ошибке. Обмен утверждениями «API-Validate-UserInfo», указанный на шаге «5», вернул ответ об ошибке HTTP с кодом «Конфликт» и причиной «Конфликт».   -  person Alex    schedule 20.05.2020
comment
У меня возникла проблема, я проверил документ docs.microsoft.com/en-us/azure/active-directory-b2c/. Я должен включить атрибут версии в ответное сообщение. Теперь все работает нормально. Спасибо   -  person Alex    schedule 20.05.2020


Ответы (2)


Обнаружена проблема, указанная в этой статье. Необходимо указать версию в ответном сообщении. Версия, статус и userMessage - обязательные поля для сообщения об ошибке.

{
  version = "1.0.0",
  userMessage = "Sorry, Something happened unexpectedly. Please try after sometime.",
  status = 409,
 }
person Alex    schedule 20.05.2020

В соответствии с этой документацией это необходимая структура ошибки:

Возврат проверки сообщение об ошибке

Более того, убедитесь, что в ответе должен быть код ошибки http, соответствующий коду ошибки содержимого:

return StatusCode(409, new ResponseContent { userMessage = ex.Message });

где ResponseContent имеет следующую структуру:

        public class ResponseContent : IResult
    {
        public string version { get; set; }
        public int status { get; set; }
        public string code { get; set; }
        public string userMessage { get; set; }
        public string developerMessage { get; set; }
        public string requestId { get; set; }
        public string moreInfo { get; set; }

        public ResponseContent()
        {
            version = "1.0.0";
            status = 409;
            code = "API12345";
            requestId = "50f0bd91-2ff4-4b8f-828f-00f170519ddb";
            userMessage = "Message for the user";
            developerMessage = "Verbose description of problem and how to fix it.";
            moreInfo = "https://docs.microsoft.com/en-us/azure/active-directory-b2c/restful-technical-profile#returning-validation-error-message";
        }
    }
person EladTal    schedule 17.11.2020