Reputation: 10345
I want an example code to allow users to login with their username and password in Azure AD. After successfully logging in, I want to get an Access Token
At the moment I have no connection with Azure AD, I hard-coded a user.
// POST api/values
[HttpPost, Route("login")]
public IActionResult Login([FromBody] LoginModel user)
{
if (user == null)
{
return BadRequest("Invalid client request");
}
if (user.UserName == "JO3434" && user.Password == "defDDMKJM")
{
var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("superSMKLJMKey@345"));
var signinCredentials = new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha256);
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name, user.UserName)
};
var token = new JwtSecurityToken(
audience: "http://site.azurewebsites.net",
issuer: "http://site.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();
}
}
}
Upvotes: 0
Views: 1723
Reputation: 42043
Without connection with Azure AD, you could not validate the user, also I think it is unnecessary to do that, if you get the token with AcquireTokenByUsernamePassword
methond, it essentially uses the Azure AD ROPC flow, it will validate the user automatically for you, if the user is invalidated, it will give an error Error validating credentials due to invalid username or password
.
Upvotes: 2