Web 应用程序受所有客户端的单一密码保护
Web app protected by single password for all clients
我想知道是否有一种标准方法可以仅使用一个密码来保护 ASP.Net Web 应用程序?换句话说,不需要用户名,所有客户端都使用相同的密码进行身份验证。
或者有人有自己的解决方案吗?
您可以简单地使用 Identity 框架来针对此建议。实际上,您不需要任何用户或密码来进行身份验证。
[HttpPost]
public ActionResult Login(string password)
{
if (password=="MyVerySecretPassword")
{
var ident = new ClaimsIdentity(
new[] {
// adding following 2 claim just for supporting default antiforgery provider
new Claim(ClaimTypes.NameIdentifier, "JustAnuniqueName"),
new Claim("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider", "ASP.NET Identity", "http://www.w3.org/2001/XMLSchema#string"),
new Claim(ClaimTypes.Name,"JustAnuniqueName"),
},
DefaultAuthenticationTypes.ApplicationCookie);
HttpContext.GetOwinContext().Authentication.SignIn(
new AuthenticationProperties { IsPersistent = false }, ident);
return RedirectToAction("MyAction"); // auth succeed
}
// invalid password
ModelState.AddModelError("", "invalid username or password");
return View();
}
但是如果您散列密码并检查散列密码而不是上面简单的 if
语句会更好。为此,您可以使用 PasswordHasher
class 来散列和验证密码。
首先散列您想要的密码并将其保存在首选存储中(数据库、文件、硬编码代码或其他任何地方):
string hashedPassword = new PasswordHasher().HashPassword("MyVerySecretPassword");
既然你有了散列的。您可以使用VerifyHashedPassword()
方法来验证它。
if(new PasswordHasher()
.VerifyHashedPassword("myHashedPassword",password)==PasswordVerificationResult.Success)
{
// the password is correct do whatever you want
}
你也可以看到我制作的simple working example来演示它。
我想知道是否有一种标准方法可以仅使用一个密码来保护 ASP.Net Web 应用程序?换句话说,不需要用户名,所有客户端都使用相同的密码进行身份验证。 或者有人有自己的解决方案吗?
您可以简单地使用 Identity 框架来针对此建议。实际上,您不需要任何用户或密码来进行身份验证。
[HttpPost]
public ActionResult Login(string password)
{
if (password=="MyVerySecretPassword")
{
var ident = new ClaimsIdentity(
new[] {
// adding following 2 claim just for supporting default antiforgery provider
new Claim(ClaimTypes.NameIdentifier, "JustAnuniqueName"),
new Claim("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider", "ASP.NET Identity", "http://www.w3.org/2001/XMLSchema#string"),
new Claim(ClaimTypes.Name,"JustAnuniqueName"),
},
DefaultAuthenticationTypes.ApplicationCookie);
HttpContext.GetOwinContext().Authentication.SignIn(
new AuthenticationProperties { IsPersistent = false }, ident);
return RedirectToAction("MyAction"); // auth succeed
}
// invalid password
ModelState.AddModelError("", "invalid username or password");
return View();
}
但是如果您散列密码并检查散列密码而不是上面简单的 if
语句会更好。为此,您可以使用 PasswordHasher
class 来散列和验证密码。
首先散列您想要的密码并将其保存在首选存储中(数据库、文件、硬编码代码或其他任何地方):
string hashedPassword = new PasswordHasher().HashPassword("MyVerySecretPassword");
既然你有了散列的。您可以使用VerifyHashedPassword()
方法来验证它。
if(new PasswordHasher()
.VerifyHashedPassword("myHashedPassword",password)==PasswordVerificationResult.Success)
{
// the password is correct do whatever you want
}
你也可以看到我制作的simple working example来演示它。