ASP.NET Core Identity Custom Register Endpoint

65 Views Asked by At

I am using Microsoft ASP.NET Core Identity, and since I need to add an additional property for my IdentityUser, I need a customer register method:

[AllowAnonymous]
[ApiController]
[Route("api/[controller]")]
public class UserController : ControllerBase
{
    private readonly UserManager<AppUser> _userManager;
    private readonly SignInManager<AppUser> _signInManager;
    private readonly IUserStore<AppUser> _userStore;

    public UserController(UserManager<AppUser> userManager, SignInManager<AppUser> signInManager, IUserStore<AppUser> userStore)
    {
        _userManager = userManager;
        _signInManager = signInManager;
        _userStore = userStore;
    }

    [HttpPost("register")]
    public async Task<ActionResult<UserDto>> Register(RegisterDto registerDto)
    {
        var user = new AppUser()
        {
            UserName = registerDto.Username,
            Email = registerDto.Email,
            Group = registerDto.Group
        };

        await _userStore.SetUserNameAsync(user, registerDto.Username, CancellationToken.None);

        var result = await _userManager.CreateAsync(user,registerDto.Password);
        
        if (result.Succeeded)
        {
            return new UserDto
            {
                Email = registerDto.Email,
                Username = registerDto.Username,
                Group = registerDto.Group
            };
        }
        return BadRequest(result.Errors);
    }
}

However, when I use the one above to register a user and try to login I get 401 unauthorized, even though I used the same payload as for registration(so I am sure that there is no typo). Whereas when I would use the default register method the login would work without problems. Please help me understand what could be the issue here.

public static class IdentityServiceExtensions
{
    public static IServiceCollection AddIdentityServices(this IServiceCollection services,IConfiguration config)
    {
        //Add authentication
        services
            .AddAuthentication()
            .AddBearerToken(IdentityConstants.BearerScheme);
        //Add authorization
        services.AddAuthorizationBuilder();
        services
            .AddIdentityCore<AppUser>(opt =>
            {
                opt.User.RequireUniqueEmail = true;
                opt.User.AllowedUserNameCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ";
            })
            .AddEntityFrameworkStores<UserDbContext>()
            .AddApiEndpoints();
        return services;
    }
}
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.Filters;
using User.DataContext;
using UserService.API.Extensions;

var builder = WebApplication.CreateBuilder(args);
var services = builder.Services;
var configuration =builder.Configuration;
// Add services to the container.
services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
services.AddEndpointsApiExplorer();
services.AddSwaggerGen(options =>
{
    options.AddSecurityDefinition("oath2", new OpenApiSecurityScheme
    {
        In = ParameterLocation.Header,
        Name = "Authorization",
        Type = SecuritySchemeType.ApiKey
    });
    options.OperationFilter<SecurityRequirementsOperationFilter>();
});

//Configure DbContext
services.AddDbContextPool<UserDbContext>(o => o.UseSqlServer(configuration.GetConnectionString("Users")));

//Configure Identity Services
services.AddIdentityServices(configuration);
var app = builder.Build();
app.MapIdentityApi<AppUser>();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseAuthentication();
app.UseAuthorization();

app.MapControllers();

app.Run();
0

There are 0 best solutions below