简体   繁体   English

如何验证 Azure AD 中的用户名和密码?

[英]How do I validate a username and password in Azure AD?

I want an example code to allow users to login with their username and password in Azure AD.我想要一个示例代码,允许用户在 Azure AD 中使用他们的用户名和密码登录。 After successfully logging in, I want to get an Access Token登录成功后,我想获取一个Access Token

At the moment I have no connection with Azure AD, I hard-coded a user.目前我与 Azure AD 没有任何联系,我硬编码了一个用户。

        // 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();
            }
        }
    }

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 .没有与 Azure AD 连接,您无法验证用户,我认为没有必要这样做,如果您使用AcquireTokenByUsernamePassword方法获取令牌,它本质上使用Azure AD ROPC 流程,它会自动为您验证用户如果用户无效,它将给出错误Error validating credentials due to invalid username or password

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM