Guest User

Guest User

  • Tech Writer
  • 611
  • 128k

Face Error in code.

Jan 27 2021 4:49 AM
I have make a login api with JWT token but i have face a issue.Please review this code.
[HttpPost]
[Route("Login")]
public IActionResult Login(string email, string password)
{
Login login = new Login();
login.Email = email;
login.Password = password;
IActionResult response = Unauthorized();
var user = AuthenticateUser(login);
if (user != null)
{
var tokenStr = GenerateJSONWebToken(user);
response = Ok(new
{
token = tokenStr
});
}
return response;
}
private Login AuthenticateUser(Login login_user)
{
Logindata obj_data = new Logindata();
LoginResult obj_result = new LoginResult();
var user = _context.UserMasters.Where(x => x.UserEmail == login_user.Email && x.Password == login_user.Password).FirstOrDefault();
if (user != null)
{
user.UserEmail = login_user.Email;
user.Password = login_user.Password;
obj_result.Response = 1;
obj_result.ErrorMessage = "No Error Found";
obj_result.data = obj_data;
}
else
{
obj_result.Response = 2;
obj_result.ErrorMessage = "Wrong Credentials";
}
return obj_result; -- Here I have face this issue Cannot implicitly convert type 'JWTAPITest.ViewModel.LoginResult' to 'JWTAPITest.ViewModel.Login' 
}
private string GenerateJSONWebToken(Login user_loginInfo)
{
var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]));
var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
var claims = new[]
{
new Claim(System.IdentityModel.Tokens.Jwt.JwtRegisteredClaimNames.Sub,user_loginInfo.Password),
new Claim(System.IdentityModel.Tokens.Jwt.JwtRegisteredClaimNames.Email,user_loginInfo.Email),
new Claim(System.IdentityModel.Tokens.Jwt.JwtRegisteredClaimNames.Jti,Guid.NewGuid().ToString())
};
var token = new JwtSecurityToken(
issuer: _config["Jwt:Issuer"],
audience: _config["Jwt:Issuer"],
claims,
expires: DateTime.Now.AddMinutes(120),
signingCredentials: credentials);
var encodetoken = new JwtSecurityTokenHandler().WriteToken(token);
return encodetoken;
}
}
 

Answers (2)