I'm developing a web API using .NET 5. I have an endpoint in that gets the current user
[Authorize]
[HttpGet]
public async Task<ActionResult<UserDto>> GetCurrentUser()
{
ApplicationUser user = await userManager.FindByEmailAsync(User.FindFirstValue(ClaimTypes.Email));
return CreateUserObject(user);
}
Now, if I add the dependency like below, this method works fine.
services.AddIdentityCore<ApplicationUser>(opt =>
{
//options go here
opt.User.RequireUniqueEmail = true;
})
However, if I use AddIdentity()
instead of AddIdentityCore()
this method fails
// AddIdentity registers the same services as AddIdentityCore, with a few extras:
// https://stackoverflow.com/questions/55361533/addidentity-vs-addidentitycore
services.AddIdentity<ApplicationUser, IdentityRole>(opt =>
//services.AddIdentityCore<ApplicationUser>(opt =>
{
//options go here
opt.User.RequireUniqueEmail = true;
})
.AddEntityFrameworkStores<DataContext>()
.AddSignInManager<SignInManager<ApplicationUser>>();
SymmetricSecurityKey key = new(Encoding.UTF8.GetBytes(config["TokenKey"]));
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = key,
ValidateIssuer = false,
ValidateAudience = false,
};
});
services.AddScoped<TokenService>();
"statusCode": 500, "message": "Value cannot be null. (Parameter 'email')", "details": " at Microsoft.AspNetCore.Identity.UserManager
1.FindByEmailAsync(String email)\r\n at Spacestation.API.Controllers.AccountController.GetCurrentUser() in F:\\Projects\\Spacestation\\Spacestation.API\\Controllers\\AccountController.cs:line 86\r\n at lambda_method18(Closure , Object )\r\n at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.AwaitableObjectResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)\r\n at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeActionMethodAsync>g__Awaited|12_0(ControllerActionInvoker invoker, ValueTask
1 actionResultValueTask)\r\n at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)\r\n at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)\r\n at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)\r\n at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()\r\n--- End of stack trace from previous location ---\r\n at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|19_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.Routing.EndpointMiddleware.g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)\r\n at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)\r\n at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)\r\n at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext)\r\n at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider)\r\n at Spacestation.API.Middleware.ExceptionMiddleware.InvokeAsync(HttpContext context) in F:\Projects\Spacestation\Spacestation.API\Middleware\ExceptionMiddleware.cs:line 28"
Edit #2 - The token services
public string CreateToken(ApplicationUser user)
{
List<Claim> claims = new()
{
new Claim(ClaimTypes.Name, user.UserName),
new Claim(ClaimTypes.NameIdentifier, user.Id),
new Claim(ClaimTypes.Email, user.Email),
};
SymmetricSecurityKey key = new(Encoding.UTF8.GetBytes(config["TokenKey"]));
SigningCredentials creds = new(key, SecurityAlgorithms.HmacSha512Signature);
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(claims),
Expires = DateTime.Now.AddDays(7),
SigningCredentials = creds
};
var tokenHandler = new JwtSecurityTokenHandler();
var token = tokenHandler.CreateToken(tokenDescriptor);
return tokenHandler.WriteToken(token);
}