Pass user detail after Login Is successful From identity asp.net core 3.1

Hatpe123 :

I was wondering how to pass user detail when the user sign response is 200. I'm using Asp.net core identity, here is my code for httpPost controller for authentication : It only sends username when user login with response 200.

namespace Test.Controllers
{
    [Route("/api/authentication/")]
    [ApiController]
    public class AuthenticationController : ControllerBase
    {
        private readonly UserManager<User> userManager;
        private readonly SignInManager<User> signInManager;
        public AuthenticationController(UserManager<User> userManager, SignInManager<User> signInManager)
        {
            this.userManager = userManager;
            this.signInManager = signInManager;
        }
        [HttpPost("login")]
        public async Task<ActionResult<UserDTO>> Login(LoginDTO dto)
        {

            var user = await userManager.FindByNameAsync(dto.UserName);



            if (user == null)
            {
                return BadRequest();
            }
            var password = await signInManager.CheckPasswordSignInAsync(user, dto.Password, true);
            if (!password.Succeeded)
            {
                return BadRequest();
            }
            await signInManager.SignInAsync(user, false, "Password");


            return Ok(new UserDTO { UserName = user.UserName });
        }
        [HttpPost("logout")]
        public async Task<ActionResult> logout()
        {
            await signInManager.SignOutAsync();
            return Ok();
        }


    }
}

I want to get all the user information not only userName that is in UserDTO.cs when user signIn with response 200.

namespace Test.Features.Users
{
    public class UserDTO
    {
        public string UserName { get; set; }
        public string Email { get; set; }
        public string PhoneNumber { get; set; }
        public string Password { get; set; }
        public string Role { get; set; }
    }
}

Here is my create account controller

namespace Test.Controllers
{
    [Route("api/createaccount")]
    [ApiController]
    public class CreateAccountController : ControllerBase
    {
        private readonly DataContext dataContext;
        private readonly SignInManager<User> signInManager;
        private readonly UserManager<User> userManager;
        public CreateAccountController(DataContext dataContext, SignInManager<User> signInManager, UserManager<User> userManager)
        {
            this.dataContext = dataContext;
            this.signInManager = signInManager;
            this.userManager = userManager;
        }

        [HttpPost]
        public async Task<ActionResult<UserDTO>> CreateUser(CreateAccountDTO dto)
        {   
            var newuser = new User
            {
                UserName = dto.UserName,
                Email = dto.Email,
                PhoneNumber = dto.PhoneNumber, 

            };

            using (var transaction = await dataContext.Database.BeginTransactionAsync())
            {
                var identityresults = await userManager.CreateAsync(newuser, dto.Password);

                if (!identityresults.Succeeded) 
                {
                    return BadRequest();
                }

                var roleresults = await userManager.AddToRoleAsync(newuser, Roles.Customer);


                if (!roleresults.Succeeded)
                {
                    return BadRequest();
                }

                transaction.Commit();

                await signInManager.SignInAsync(newuser, isPersistent: false);

                var user = await userManager.FindByEmailAsync(newuser.Email);


                var rolesList = await userManager.GetRolesAsync(user);

                var getRole = rolesList[0];

                Console.WriteLine(getRole);

                return Created(string.Empty, new UserDTO
                {
                    UserName = newuser.UserName,
                    Email = newuser.Email,
                    PhoneNumber = newuser.PhoneNumber,
                    Password = newuser.PasswordHash,
                    Role = getRole
                }) ;
            }
        }
    }
}

for role i have role.cs and roles.cs

namespace Test.Features.Roles
{
    public class Roles
    {
        public const string Admin = nameof(Admin);
        public const string Customer = nameof(Customer);

        private static bool HasAnyRole(ClaimsPrincipal user, string target)
        {
            foreach(var role in target.Split(","))
            {
                if (user.IsInRole(role))
                {
                    return true;
                }

            }
            return false;
        }


    }
}

namespace Test.Features.Roles
{
    public class Role:IdentityRole<int>
    {
        public virtual ICollection<UserRole> Users { get; set; } = new List<UserRole>();
    }
}

thank you!

Daniaal :

So you need to use the UserManager for this. If you look at what i am returning, this is what you want. I have tested this and it works my end. Any questions let me know.

For the roles, a user can have multiple roles and the method below returns a list of roles.

var roles = await _userManager.GetRolesAsync( test );

So your UserDTO will look like the below:

 public class UserDTO
{
    public string UserName { get; set; }
    public string Email { get; set; }
    public string PhoneNumber { get; set; }
    public string Password { get; set; }
    public List<string> Role { get; set; }
}

And your controller method will look like the below:

[Route("/api/authentication/")]
[ApiController]
public class AuthenticationController : ControllerBase
{
    private readonly UserManager<User> userManager;
    private readonly SignInManager<User> signInManager;
    public AuthenticationController(UserManager<User> userManager, SignInManager<User> signInManager)
    {
        this.userManager = userManager;
        this.signInManager = signInManager;
    }
    [HttpPost("login")]
    public async Task<ActionResult<UserDTO>> Login(LoginDTO dto)
    {

        var user = await userManager.FindByNameAsync(dto.UserName);
        var roles = await _userManager.GetRolesAsync( user );
        if (user == null)
        {
            return BadRequest();
        }
        var password = await signInManager.CheckPasswordSignInAsync(user, dto.Password, true);
        if (!password.Succeeded)
        {
            return BadRequest();
        }
        await signInManager.SignInAsync(user, false, "Password");


        return Ok(new UserDTO { UserName = user.UserName, Email = user.Email, PhoneNumber = user.PhoneNumber, Password = user.PasswordHash, Role = roles.ToList() });
    }

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

ASP.Net Core Identity login status lost after deploy

Link ASP.NET Identity users to user detail table

User.Identity.GetUserId() returns null after successful login

Register and Login by Phone Number in Asp.net Core Identity

ASP.NET Core 2.0 Identity: SignInManager.IsSignedIn(User) returns false after signing in

Asp Core Identity, How to get userId after login?

Asp.net core Identity successful login redirecting back to login page

How to get user claims after signin through SignInManager in ASP .NET CORE Identity?

ASP.NET Identity user null after login

How to disable account if user login fails continuously in Asp.Net Core identity

Using Asp.Net Core Identity in MVC, Authorize attribute is rebouncing to login page after succesfull login

Adding Redirection immediately after Login in ASP.Net Core 2.1 using Identity Core

ASP.NET Core Identity - LoginPartial broken after scaffolding identity

Not able to get user group claims when using Azure AD as external login alongside Identity Core(ASP.NET Core 2.1)

ASP.NET Core 3: Cannot resolve scoped service 'Microsoft.AspNetCore.Identity.UserManager`1[Alpha.Models.Identity.User]' from root provider

Application Insights User ID from ASP.NET Core identity

After updating the identity server 4 4.0.0 from 3.1.4 Scope is invalid asp.net core 3 with Mongo DB

Asp.net/JQuery: Set session after successful login

ASP.Net Core - How do I wait for User Identity to be available immediately after signing in?

Cannot login on ASP.NET Identity 2 site after programmatic user creation

ASP.NET Identity - Maintain login after updating user record

Add a Custom property to ASP.NET MVC Identity after user login

ASP.NET Core 2.0 Identity update user roles only after re-authorization

How do I get the user details straight after login using Identity on ASP.NET Core?

ASP.NET Identity, how to change the view after successful authorization

ASP.NET Core Identity user groups

ASP.net Core Identity Sign in as another user from Administrator

User.Identity.IsAuthenticated is false in a non-auth methods after successful login in asp.net core

UserIdentity is null after successful login and redirection to another razor view, ASP.NET Core MVC web application