dotnet-starter-kit icon indicating copy to clipboard operation
dotnet-starter-kit copied to clipboard

Create New User Bug

Open kallievz opened this issue 4 years ago • 10 comments

Describe the bug Cloning/Building first time. Checked all tables were created/seeded

To Reproduce Steps to reproduce the behavior:

  1. Fire up console and use broser to open swagger url
  2. Generate JWT using Contant values
  3. Navigate and create new user, filling all fields, Execute results in error on verifying the email address. Believe the same can happen on ContactNumber

Expected behavior Create new user

Stack Trace {"Timestamp":"2022-02-15T14:37:48.8135872+02:00","Level":"Error","MessageTemplate":"Object reference not set to an instance of an object. Request failed with Status Code 500 and Error Id f06ea9df-bc30-421e-b378-d244eef61c13.","Properties":{"StackTrace":" at lambda_method923(Closure , QueryContext )\r\n at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.ExecuteAsync[TResult](Expression query, CancellationToken cancellationToken)\r\n at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryProvider.ExecuteAsync[TResult](Expression expression, CancellationToken cancellationToken)\r\n at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.ExecuteAsync[TSource,TResult](MethodInfo operatorMethodInfo, IQueryable1 source, Expression expression, CancellationToken cancellationToken)\r\n at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.ExecuteAsync[TSource,TResult](MethodInfo operatorMethodInfo, IQueryable1 source, LambdaExpression expression, CancellationToken cancellationToken)\r\n at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.SingleOrDefaultAsync[TSource](IQueryable1 source, Expression1 predicate, CancellationToken cancellationToken)\r\n at Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserStore9.FindByEmailAsync(String normalizedEmail, CancellationToken cancellationToken)\r\n at Microsoft.AspNetCore.Identity.UserManager1.FindByEmailAsync(String email)\r\n at FSH.WebApi.Infrastructure.Identity.UserService.ExistsWithEmailAsync(String email, String exceptId) in C:\Source\Private\dotnet-webapi-boilerplate-main\src\Infrastructure\Identity\UserService.cs:line 91\r\n at FSH.WebApi.Application.Identity.Users.CreateUserRequestValidator.<>c__DisplayClass0_0.<<-ctor>b__1>d.MoveNext() in C:\Source\Private\dotnet-webapi-boilerplate-main\src\Core\Application\Identity\Users\CreateUserRequestValidator.cs:line 11\r\n--- End of stack trace from previous location ---\r\n at FluentValidation.Internal.PropertyRule2.InvokePropertyValidatorAsync(ValidationContext1 context, Lazy1 accessor, String propertyName, RuleComponent2 component, CancellationToken cancellation) in /media/jskinner/Linux2/code/FluentValidation/src/FluentValidation/Internal/PropertyRule.cs:line 242\r\n at FluentValidation.Internal.PropertyRule2.Validate(ValidationContext1 context) in /media/jskinner/Linux2/code/FluentValidation/src/FluentValidation/Internal/PropertyRule.cs:line 125\r\n at FluentValidation.AbstractValidator1.Validate(ValidationContext1 context) in /media/jskinner/Linux2/code/FluentValidation/src/FluentValidation/AbstractValidator.cs:line 96\r\n at FluentValidation.AbstractValidator1.FluentValidation.IValidator.Validate(IValidationContext context) in /media/jskinner/Linux2/code/FluentValidation/src/FluentValidation/AbstractValidator.cs:line 48\r\n at FluentValidation.AspNetCore.FluentValidationModelValidator.Validate(ModelValidationContext mvContext) in /media/jskinner/Linux2/code/FluentValidation/src/FluentValidation.AspNetCore/FluentValidationModelValidatorProvider.cs:line 113\r\n at Microsoft.AspNetCore.Mvc.ModelBinding.Validation.ValidationVisitor.ValidateNode()\r\n at Microsoft.AspNetCore.Mvc.ModelBinding.Validation.ValidationVisitor.VisitComplexType(IValidationStrategy defaultStrategy)\r\n at Microsoft.AspNetCore.Mvc.ModelBinding.Validation.ValidationVisitor.VisitImplementation(ModelMetadata& metadata, String& key, Object model)\r\n at Microsoft.AspNetCore.Mvc.ModelBinding.Validation.ValidationVisitor.Visit(ModelMetadata metadata, String key, Object model)\r\n at Microsoft.AspNetCore.Mvc.ModelBinding.Validation.ValidationVisitor.Validate(ModelMetadata metadata, String key, Object model, Boolean alwaysValidateAtTopLevel, Object container)\r\n at FluentValidation.AspNetCore.FluentValidationVisitor.<>n__1(ModelMetadata metadata, String key, Object model, Boolean alwaysValidateAtTopLevel, Object container)\r\n at FluentValidation.AspNetCore.FluentValidationVisitor.<>c__DisplayClass2_0.<Validate>g__BaseValidate|0() in /media/jskinner/Linux2/code/FluentValidation/src/FluentValidation.AspNetCore/FluentValidationVisitor.cs:line 44\r\n at FluentValidation.AspNetCore.FluentValidationVisitor.ValidateInternal(ModelMetadata metadata, String key, Object model, Func1 continuation) in /media/jskinner/Linux2/code/FluentValidation/src/FluentValidation.AspNetCore/FluentValidationVisitor.cs:line 62\r\n at FluentValidation.AspNetCore.FluentValidationVisitor.Validate(ModelMetadata metadata, String key, Object model, Boolean alwaysValidateAtTopLevel, Object container) in /media/jskinner/Linux2/code/FluentValidation/src/FluentValidation.AspNetCore/FluentValidationVisitor.cs:line 46\r\n at Microsoft.AspNetCore.Mvc.ModelBinding.ObjectModelValidator.Validate(ActionContext actionContext, ValidationStateDictionary validationState, String prefix, Object model, ModelMetadata metadata, Object container)\r\n at Microsoft.AspNetCore.Mvc.ModelBinding.ParameterBinder.EnforceBindRequiredAndValidate(ObjectModelValidator baseObjectValidator, ActionContext actionContext, ParameterDescriptor parameter, ModelMetadata metadata, ModelBindingContext modelBindingContext, ModelBindingResult modelBindingResult, Object container)\r\n at Microsoft.AspNetCore.Mvc.ModelBinding.ParameterBinder.BindModelAsync(ActionContext actionContext, IModelBinder modelBinder, IValueProvider valueProvider, ParameterDescriptor parameter, ModelMetadata metadata, Object value, Object container)\r\n at Microsoft.AspNetCore.Mvc.Controllers.ControllerBinderDelegateProvider.<>c__DisplayClass0_0.<g__Bind|0>d.MoveNext()\r\n--- End of stack trace from previous location ---\r\n at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.g__Awaited|13_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)\r\n at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|20_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)\r\n at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)\r\n at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)\r\n at Microsoft.AspNetCore.Routing.EndpointMiddleware.g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)\r\n at NSwag.AspNetCore.Middlewares.SwaggerUiIndexMiddleware.Invoke(HttpContext context)\r\n at NSwag.AspNetCore.Middlewares.RedirectToIndexMiddleware.Invoke(HttpContext context)\r\n at NSwag.AspNetCore.Middlewares.OpenApiDocumentMiddleware.Invoke(HttpContext context)\r\n at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)\r\n at Finbuckle.MultiTenant.AspNetCore.MultiTenantMiddleware.Invoke(HttpContext context)\r\n at FSH.WebApi.Infrastructure.Auth.CurrentUserMiddleware.InvokeAsync(HttpContext context, RequestDelegate next) in C:\Source\Private\dotnet-webapi-boilerplate-main\src\Infrastructure\Auth\CurrentUserMiddleware.cs:line 16\r\n at Microsoft.AspNetCore.Builder.UseMiddlewareExtensions.<>c__DisplayClass6_1.<b__1>d.MoveNext()\r\n--- End of stack trace from previous location ---\r\n at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)\r\n at FSH.WebApi.Infrastructure.Middleware.ExceptionMiddleware.InvokeAsync(HttpContext context, RequestDelegate next) in C:\Source\Private\dotnet-webapi-boilerplate-main\src\Infrastructure\Middleware\ExceptionMiddleware.cs:line 31","ErrorId":"f06ea9df-bc30-421e-b378-d244eef61c13","UserEmail":"","RequestId":"4000001e-0006-fc00-b63f-84710c7967bb","RequestPath":"/api/users","MachineName":"xxxxx","ProcessId":31364,"ThreadId":22,"Application":"FSH.WebApi"}}

Screenshots If applicable, add screenshots to help explain your problem.

Desktop (please complete the following information):

  • OS: Win 11, latest
  • Browser Microsoft Edge
  • Version 98.0.1108.50 (Official build) (64-bit)

kallievz avatar Feb 15 '22 17:02 kallievz

I can't seem to repeat this... I just tried this on the latest source (dropped the database) with an invalid email address, and this is what I get back:

image

What values exactly do you send?

fretje avatar Feb 15 '22 18:02 fretje

Seems like a nullreferenceexception deep inside entityframeworkcore... You're probably using another provider than MSSQL... might be a bug with that provider?

fretje avatar Feb 15 '22 18:02 fretje

Seems like a nullreferenceexception deep inside entityframeworkcore... You're probably using another provider than MSSQL... might be a bug with that provider?

Not sure where it originates from, I am using MSSQL 2016. Did exactly that, created from fresh instance. It has seeded the root user, but when adding new user on same tenant(used valid email), it failed, never tried with invalid email.

Line 92 in UserService.cs public async Task ExistsWithEmailAsync(string email, string? exceptId = null) => await _userManager.FindByEmailAsync(email.Normalize()) is ApplicationUser user && user.Id != exceptId;

'user.Id' threw and exception of type System.NullreferenceException

kallievz avatar Feb 16 '22 07:02 kallievz

It originates from the CreateUserRequestValidator.

But that's very strange that line 92 in userservice... That would mean it found a user with that email, but that user has null as id. Can you expect what's in the database?

The callstack you posted earlier says something else btw... It's not in userservice that the nullreferenceexception happens, but rather somewhere inside FindByEmailAsync, so it probably doesn't get to the && user.Id != exceptId.

fretje avatar Feb 16 '22 09:02 fretje

CreateUserRequestValidator

Hi fretje. Actually it was a blank db, with just seeded values (root values). Creating the second user caused it to fail. Error first get triggered there. I tried overloading without passing exceptId as a second controller call to see if it solves, but no luck.

kallievz avatar Feb 16 '22 13:02 kallievz

Sorry can't repeat it... there must be something specific about your setup that makes it fail...

fretje avatar Feb 16 '22 14:02 fretje

the problem is occurring because you do not have a claims that is validated you cannot get the tenantid

frankyjquintero avatar Feb 16 '22 18:02 frankyjquintero

The user registry when anonymous must send the tenantid for the system to identify it

frankyjquintero avatar Feb 16 '22 18:02 frankyjquintero

Try putting the create user permission if you don't require anonymous registration

frankyjquintero avatar Feb 16 '22 18:02 frankyjquintero

Oh yeah, of course... It's because you don't supply the tenantId header... that's indeed necessary when allowing anonymous user registration. (my example from postman had a tenantId filled out in the headers already).

We have to put

[TenantIdHeader]

on the UsersController.CreateAsync call

Putting a permission on there won't change this behaviour... well... it probably would... but then anonymous is not possible anymore... we'll have to check inside the function if anonymous is allowed (according to appsettings) and then throw an exception if it isn't...

fretje avatar Feb 16 '22 19:02 fretje