Starts in:
2 DAYS
4 HRS
10 MIN
58 SEC
Starts in:
2 D
4 H
10 M
58 S
Open Closed

AbpValidationException response not received in JSON format on client side. #2017


User avatar
0
lalitChougule created
  • ABP Framework version: v4.3.1
  • UI type: Angular
  • DB provider: EF Core
  • Tiered (MVC) or Identity Server Separated (Angular): no / yes
  • Exception message and stack trace: N.A
  • Steps to reproduce the issue:" N.A

I have implemented override for SignInManager and have done some custom logic check in CanSignInAsync() method If my custom logic fails I thrown Exception ie. throw new AbpValidationException(...my_error_message...) On angular side I am not getting any error response in json format to handle, it's directly throwing the below error, below are the details from network tab.

Volo.Abp.Validation.AbpValidationException: Inactive user
   at SCV.Litmus.LitmusOverrides.LitmusSigInManager.CanSignInAsync(IdentityUser user) in D:\Litmus\Projects\ar-allocation\SCV.Litmus\aspnet-core\microservices\SCV.Litmus.IdentityServer\LitmusOverrides\LitmusSigInManager.cs:line 56
   at Microsoft.AspNetCore.Identity.SignInManager`1.PreSignInCheck(TUser user)
   at Microsoft.AspNetCore.Identity.SignInManager`1.CheckPasswordSignInAsync(TUser user, String password, Boolean lockoutOnFailure)

My expectation was something like this : https://docs.abp.io/en/abp/latest/Exception-Handling#validation-errors

{
  "error": {
    "code": "App:010046",
    "message": "Your request is not valid, please correct and try again!",
    "validationErrors": [{
      "message": "Username should be minimum length of 3.",
      "members": ["userName"]
    },
    {
      "message": "Password is required",
      "members": ["password"]
    }]
  }
}

How to get the above type of details by throwing error from SignInManager ?


5 Answer(s)
  • User Avatar
    0
    maliming created
    Support Team Fullstack Developer

    hi

    Are you requesting an API or a razor page?

    Can you share full error log and stack info.

  • User Avatar
    0
    kaustubh.kale@ness.com created

    HI We are requesting for API.

    For Client Side We are Using Angular 11 . For Backend Services we are using WebApi

  • User Avatar
    0
    maliming created
    Support Team Fullstack Developer

    Can you share some code of your API and full error log and stack?

  • User Avatar
    0
    kaustubh.kale@ness.com created
    public override async Task<bool> CanSignInAsync(Volo.Abp.Identity.IdentityUser user)
            {
                #region Multifactor Authentication Logic
                var authenticationCode = string.Empty;
    
                if (_contextAccessor.HttpContext.Request.Headers.TryGetValue("authenticationCode", out var authenticationCodeValue))
                {
                    authenticationCode = authenticationCodeValue;
                }
    
                if (user.TwoFactorEnabled)
                {
                    var otpResponse = await _sharedAppService.ValidatePinAtTokenCreationAsync(new ValidatePinAtTokenCreationInputDto
                    {
                        UserId = user.Id,
                        Otp = authenticationCode
                    });
    
                    if (!otpResponse)
                      **  throw new AbpAuthorizationException("Invalid authentication code");**
                }
                #endregion
    
                var status = await _appUserRepository.Where(x => x.Id == user.Id).Select(x => x.Status).FirstOrDefaultAsync();
                if (status == AbpUserStatusEnum.InActive)
                    throw new AbpAuthorizationException("Inactive user");
    
                return await base.CanSignInAsync(user);
            }
        }
    

    Log Stack Trace :

    Volo.Abp.Authorization.AbpAuthorizationException: Invalid authentication code
       at SCV.Litmus.LitmusOverrides.LitmusSigInManager.CanSignInAsync(IdentityUser user) in D:\Litmus\SCV.Litmus\aspnet-core\microservices\SCV.Litmus.IdentityServer\LitmusOverrides\LitmusSigInManager.cs:line 75
       at Microsoft.AspNetCore.Identity.SignInManager`1.PreSignInCheck(TUser user)
       at Microsoft.AspNetCore.Identity.SignInManager`1.CheckPasswordSignInAsync(TUser user, String password, Boolean lockoutOnFailure)
       at Volo.Abp.IdentityServer.AspNetIdentity.AbpResourceOwnerPasswordValidator.ValidateAsync(ResourceOwnerPasswordValidationContext context)
       at Castle.DynamicProxy.AsyncInterceptorBase.ProceedAsynchronous(IInvocation invocation, IInvocationProceedInfo proceedInfo)
       at Volo.Abp.Castle.DynamicProxy.CastleAbpMethodInvocationAdapter.ProceedAsync()
       at Volo.Abp.Uow.UnitOfWorkInterceptor.InterceptAsync(IAbpMethodInvocation invocation)
       at Volo.Abp.Castle.DynamicProxy.CastleAsyncAbpInterceptorAdapter`1.InterceptAsync(IInvocation invocation, IInvocationProceedInfo proceedInfo, Func`3 proceed)
       at IdentityServer4.Validation.TokenRequestValidator.ValidateResourceOwnerCredentialRequestAsync(NameValueCollection parameters)
       at IdentityServer4.Validation.TokenRequestValidator.RunValidationAsync(Func`2 validationFunc, NameValueCollection parameters)
       at IdentityServer4.Validation.TokenRequestValidator.ValidateRequestAsync(NameValueCollection parameters, ClientSecretValidationResult clientValidationResult)
       at IdentityServer4.Endpoints.TokenEndpoint.ProcessTokenRequestAsync(HttpContext context)
       at IdentityServer4.Endpoints.TokenEndpoint.ProcessAsync(HttpContext context)
       at IdentityServer4.Hosting.IdentityServerMiddleware.Invoke(HttpContext context, IEndpointRouter router, IUserSession session, IEventService events, IBackChannelLogoutService backChannelLogoutService)
       at IdentityServer4.Hosting.IdentityServerMiddleware.Invoke(HttpContext context, IEndpointRouter router, IUserSession session, IEventService events, IBackChannelLogoutService backChannelLogoutService)
       at IdentityServer4.Hosting.MutualTlsEndpointMiddleware.Invoke(HttpContext context, IAuthenticationSchemeProvider schemes)
       at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
       at Microsoft.AspNetCore.Cors.Infrastructure.CorsMiddleware.&lt;Invoke&gt;g__InvokeCoreAwaited|15_0(HttpContext context, Task`1 policyTask)
       at IdentityServer4.Hosting.BaseUrlMiddleware.Invoke(HttpContext context)
       at Volo.Abp.AspNetCore.MultiTenancy.MultiTenancyMiddleware.InvokeAsync(HttpContext context, RequestDelegate next)
       at Microsoft.AspNetCore.Builder.UseMiddlewareExtensions.<>c__DisplayClass6_1.<<UseMiddlewareInterface>b__1>d.MoveNext()
    --- End of stack trace from previous location ---
       at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
       at Volo.Abp.AspNetCore.Tracing.AbpCorrelationIdMiddleware.InvokeAsync(HttpContext context, RequestDelegate next)
       at Microsoft.AspNetCore.Builder.UseMiddlewareExtensions.<>c__DisplayClass6_1.<<UseMiddlewareInterface>b__1>d.MoveNext()
    --- End of stack trace from previous location ---
       at Microsoft.AspNetCore.Localization.RequestLocalizationMiddleware.Invoke(HttpContext context)
       at Microsoft.AspNetCore.RequestLocalization.AbpRequestLocalizationMiddleware.InvokeAsync(HttpContext context, RequestDelegate next)
       at Microsoft.AspNetCore.Builder.UseMiddlewareExtensions.<>c__DisplayClass6_1.<<UseMiddlewareInterface>b__1>d.MoveNext()
    --- End of stack trace from previous location ---
       at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
    

    HEADERS

    Accept: application/json, text/plain, */*
    Accept-Encoding: gzip, deflate, br
    Accept-Language: en
    Connection: keep-alive
    Content-Length: 180
    Content-Type: application/x-www-form-urlencoded
    Host: localhost:44350
    Referer: http://localhost:4200/
    User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.54 Safari/537.36
    sec-ch-ua: "Google Chrome";v="95", "Chromium";v="95", ";Not A Brand";v="99"
    sec-ch-ua-mobile: ?0
    __tenant: d1be844b-d3a2-031a-f036-39f5d4380239
    sec-ch-ua-platform: "Windows"
    Origin: http://localhost:4200
    Sec-Fetch-Site: cross-site
    Sec-Fetch-Mode: cors
    Sec-Fetch-Dest: empty
    X-Correlation-Id: c110708d3a5445769357ab22e8cd3790
    
  • User Avatar
    0
    maliming created
    Support Team Fullstack Developer

    hi

    You are request the TokenEndpoint, this is Identity Server endpoint, ABP won't wrap the exception.

    You can override this AbpResourceOwnerPasswordValidator sevice to custom the response.

    https://github.com/abpframework/abp/blob/42966c11258d8f681a2cc22b662f3ed0ea6f0dc9/modules/identityserver/src/Volo.Abp.IdentityServer.Domain/Volo/Abp/IdentityServer/AspNetIdentity/AbpResourceOwnerPasswordValidator.cs#L103

Made with ❤️ on ABP v9.1.0-preview. Updated on November 20, 2024, 13:06