'Allow user to sign in by Azure AD username and password

In my controller I hard-coded a username and password. Now I want to allow the user to login with his/her Azure AD username and password.

        public IActionResult Login([FromBody] LoginModel user)
        {
            if (user == null)
            {
                return BadRequest("Invalid client request");
            }
            if (user.UserName == "johndoe" && user.Password == "def@MKK")
            {
                var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("justAsecretKey"));
                var signinCredentials = new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha256);

                var claims = new List<Claim>
                {
                    new Claim(ClaimTypes.Name, user.UserName)
                };
                
                var token = new JwtSecurityToken(
                    audience: "http://api.azurewebsites.net",
                    issuer: "http://api.azurewebsites.net",
                    claims: claims,
                    expires: DateTime.Now.AddMinutes(60),
                    signingCredentials: signinCredentials
                );

                var results = new
                {
                    token = new JwtSecurityTokenHandler().WriteToken(token),
                    expiration = token.ValidTo
                };
                return Ok(results);
            }
            else
            {
                return Unauthorized();
            }
        }


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source