Home > Software engineering >  How to create a service for user login in Identity
How to create a service for user login in Identity

Time:12-08

In order to create a token in jwt, I must first check that the received user password is correct. I want to write a service for login and create its interface and use it in the JWTAuthorizationManager class or anywhere, please correct the codes.

    public class JWTAuthorizationManager
    {

        public JwtFeilds Authenticate(string UserName, string PasswordHash)
        {

            //ایجاد تاریخ انقضای توکن
            var tokenExpireTimeStamp = DateTime.Now.AddHours(Constansts.JWT_TOKEN_EXPIRE_TIME);
            //ایجاد متغیر از کلاس مشخص شده برای ایجاد توکن و اطلاعات همراه آن
            var jwtSecurityTokenHandler = new JwtSecurityTokenHandler();
            //ایجاد آرایه ای از بایت ها به عنوان کلید توکن
            var tokenKey = Encoding.ASCII.GetBytes(Constansts.JWT_SECURITY_KEY_FOR_TOKEN);
            //از این کلاس برای نگهداری ویژگیها و اطلاعات درون توکن استفاده می شود.
            var securityTokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new List<Claim>
                {
                    new Claim("username", UserName),
                    new Claim(ClaimTypes.PrimaryGroupSid,"User Group 01")

                }),
                Expires = tokenExpireTimeStamp,
                //امضا یا اعتبارنامه یا مجوز ورود
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(tokenKey),SecurityAlgorithms.HmacSha256Signature)
            };

            var securityToken = jwtSecurityTokenHandler.CreateToken(securityTokenDescriptor);
            var token = jwtSecurityTokenHandler.WriteToken(securityToken);
     

                return new JwtFeilds
                {
                    token = token,
                    user_name = UserName,
                    expire_time = (int)tokenExpireTimeStamp.Subtract(DateTime.Now).TotalSeconds

                };

        }
       
    }
   public class loginService
    {
     
        private readonly SignInManager<User> _signInManager;

        public loginService(SignInManager<User> signInManager)
        {
            _signInManager = signInManager;
        }

    public async Task<loginService> UserLogin(string UserName, string PasswordHash)
    {

        var result = await _signInManager.PasswordSignInAsync(UserName, PasswordHash, true,
                     lockoutOnFailure: false);
        if (result.Succeeded)
        {

                return null;
        }


            return null;

        }

    }
    interface IuserLogin
    {



    }
        [HttpPost]
        public IActionResult Login([FromForm] User model)
        {
            

            var jwtAuthorizationManager = new JWTAuthorizationManager();
            var result = jwtAuthorizationManager.Authenticate(model.UserName, model.PasswordHash);
            if (result == null)
                return Unauthorized();
            else
                return Ok(result);

         
        }

The token creation is done successfully, but I want the user to be identified before creating the token

CodePudding user response:

The easiest way, you can choose to return a boolean Task:

public interface ILoginService
{
    //If your model has other attributes, pass them in together
    Task<bool> UserLogin(string UserName, string PasswordHash);
}
public class Login : ILogin
{
    private readonly SignInManager<IdentityUser> _signInManager;
    private readonly UserManager<IdentityUser> _userManager;
    public Login(SignInManager<IdentityUser> signInManager,UserManager<IdentityUser> userManager)
    {
        _signInManager = signInManager;
        _userManager = userManager;
    }

    public async Task<bool> UserLogin(string UserName, string PasswordHash) 
    {   
        var user = await _userManager.FindByEmailAsync(UserName);
        if (user != null && !user.EmailConfirmed)
        {
            return false;
        }
        if (await _userManager.CheckPasswordAsync(user, PasswordHash) == false)
        { 
            return false;
        }
        var result = await _signInManager.PasswordSignInAsync(UserName, PasswordHash, true);
            
        if (result.Succeeded)
        {
            return true;
        }
        else 
        {
            return false;
        }
    }
}

In the Login Action:

[HttpPost]
[AllowAnonymous]
public async Task<IActionResult> Login(UserLoginDto model)
{
     if (ModelState.IsValid)
     {
          //Call the ILoginService interface
          var result = _loginService.UserLogin(model.Email,model.Password);

          if (result.Result)
          {
              var jwtAuthorizationManager = new JWTAuthorizationManager();
              var result = jwtAuthorizationManager.Authenticate(model.UserName, model.PasswordHash);
              //do something    
          }
          else
          {
               ModelState.AddModelError("message", "Invalid login attempt");
               return View(model);
          }
     }
     return View(model);
}

Don't forget to sign up for the service:

builder.Services.AddTransient<ILoginService, LoginService>();

You can also return a string or other types of Task, up to you.

Hope this can help you.

  • Related