如何使用不同的检查对 Web 服务中的用户进行身份验证



我正在使用一个使用 Active Directory 对用户进行身份验证的 Web API。我在PHP中使用此API来登录我的WEB API密钥中的用户(密钥位于"Web.Config"文件中(。我是 c# web api 的新手,有些问题我无法解决。我需要为用户插入一些检查。第一个是如果用户不在密钥"不允许返回"中。如果用户在密钥中,但用户名或密码无效,则"返回无效的用户名或密码",如果用户输入为 true,则用户登录到系统。

public string IsAuthenticated(string user, string pass, string domain)
{
DirectoryEntry objDirEntry = new DirectoryEntry("LDAP://" + domain, user, pass);
try
{
string UserName = user.ToString();
string Password = pass.ToString();
string Domain = "Netsolpk";
DirectorySearcher search = new DirectorySearcher(objDirEntry);
SearchResult result = search.FindOne();
if (result == null)
return "You're not in the Domain";
string AdAuthentication = IsAuthenticated(UserName, Password, Domain);
string[] name = ConfigurationManager.AppSettings["name"].Split(',');
string authorized = "false";
foreach (var author in name)
{
if (AdAuthentication == "true" && author.ToLower() == user.ToLower())
{
return "true"; //login
}
else if (author.ToLower() == user.ToLower())
{
return "Invalid Password";
authorized = "true";
break;
}
}
if (AdAuthentication == "false")
{
return "Not Allowed";
}
return "false";
}
catch (Exception)
{
return "false";
}
}
<appSettings>
<add key="webpages:Version" value="3.0.0.0"/>
<add key="webpages:Enabled" value="false"/>
<add key="ClientValidationEnabled" value="true"/>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
<add key="name" value="DavidR,JohnH"/>
</appSettings>
  1. 你的问题到底在哪里?

  2. 查看 JWT 身份验证令牌。如果用户未经授权或返回令牌以登录,这是返回取消令牌的好方法。您可以使用 Postman 轻松测试 API。

这里有一个小例子:

[HttpPost]
public ActionResult Login([FromBody]LoginModel GetLoginData)
{
/// Get SAM and Passowrd
var service = new JSON();
var LoginUser = service.GetData(GetLoginData);
_logger.Log(LogLevel.Information, $"User {LoginUser.SAM} tried to Login.");
/// Checks if user is allowed to login
var db = new DB();
bool IsAllowed = db.GetUserBySAM(LoginUser);
if (IsAllowed == true)
{
/// Checks if Password is correct in LDAP
var ldap = new LDAP();
bool PasswordCorrect = ldap.IsUserPasswordCorrect(LoginUser);
if (PasswordCorrect == true)
{
/// Gets Userdata from AD
LoginUser = ldap.GetUserData(LoginUser);
var auth = new Authentication();
/// Generates a Token which expire in 5 minutes
var JwtToken = auth.CreateToken(LoginUser);
_logger.Log(LogLevel.Information, $"User {LoginUser.SAM} successfully logged in.");
return Ok(new
{
token = JwtToken,
allowed = "Authorized",
username = LoginUser.SAM,
firstname = LoginUser.FirstName,
lastname = LoginUser.LastName
});
}
else return Unauthorized();
}
_logger.Log(LogLevel.Information, $"User {LoginUser.SAM} is not allowed to login.");
return Unauthorized();
}

相关内容

  • 没有找到相关文章

最新更新