[英]C#.NET Using isAuthenticated
我使用MVC格式來創建一個網站。 現在它所做的只是從SQL服務器管理用戶。 我現在要做的是讓用戶登錄然后能夠管理用戶。 從登錄頁面,它應該轉到帳戶的索引,但我只希望經過身份驗證的用戶可以查看此頁面。 如果我:它工作正常:
1)將控制器中的函數設置為[AllowAnonymous](這不是我想要的)
2)允許Windows身份驗證(這不是我想要的,因為一旦我部署,它將在網絡上)
它實際上歸結為我如何驗證用戶身份,然后保持該身份驗證。
這是登錄頁面:
@model myWebsite.Models.LoginModel
@{
ViewBag.Title = "Login";
ViewBag.ReturnUrl = "Index";
}
<h2>Login</h2>
@using (Html.BeginForm("Login", "Login", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Login</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger"})
<div class="form-group">
@Html.LabelFor(Model => Model.UserName, new { @class = "control-label col-md-2"})
<div class="col-md-10">
@Html.TextBoxFor(Model => Model.UserName, new { @class = "col-md-2 control-label"})
@Html.ValidationMessageFor(Model => Model.UserName, "" , new { @class = "text-danger"})
</div>
</div>
<div class="form-group">
@Html.LabelFor(Model => Model.Password, new { @class = "control-label col-md-2"})
<div class="col-md-10">
@Html.TextBoxFor(Model => Model.Password, new { @class = "col-md-2 control-label"})
@Html.ValidationMessageFor(Model => Model.Password, "" , new { @class = "text-danger"})
</div>
</div>
<div class="form-group">
<input type="submit" value="Log In" class="btn btn-default" />
</div>
</div>
}
這是每個頁面的部分部分
@using Microsoft.AspNet.Identity;
@if (Request.IsAuthenticated)
{
using (Html.BeginForm("LogOff", "Account", FormMethod.Post, new { id = "logoutForm", @class = "navbar-right" }))
{
@Html.AntiForgeryToken()
<ul class="nav navbar-nav navbar-right">
<li>@Html.ActionLink("Hello " + User.Identity.GetUserName() + "!", "Index" , "Manage", routeValues: null, htmlAttributes: new { title = "Manage" } )</li>
</ul>
}
}
else
{
<ul class="nav navbar-nav navbar-right">
<li>@Html.ActionLink("Register", "Create", "Login", routeValues: null, htmlAttributes: new { id = "registerLink" })</li>
<li>@Html.ActionLink("Log in", "Login", "Login", routeValues: null, htmlAttributes: new { id = "loginLink" })</li>
</ul>
}
這是控制器
[AllowAnonymous]
// GET: Login
public ActionResult Login()
{
return View();
}
[AllowAnonymous]
// GET: Login
public ActionResult Login()
{
return View();
}
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginModel model, string retunUrl)
{
/*
if (!ModelState.IsValid)
{
Console.WriteLine("IS NOT VALID");
return View(model);
}
*/
String UserName = model.UserName;
String Password = model.Password;
LoginContext LC = new LoginContext();
LoginModel ValidUser = LC.UserList.Single(Person => Person.UserName == UserName && Person.Password == Password);
if (ValidUser != null)
{
return Redirect("Index");
}
return View(model);
}
// GET: Login Index of users
[AllowAnonymous]
public ActionResult Index()
{
return View(db.UserList.ToList());
}
如果您只關心用戶為您提供有效憑據的事實,那么您最簡單的選項可能是FormsAuthentication:
FormsAuthentication.SetAuthCookie(model.UserName, false);
和
FormsAuthentication.SignOut();
這些要求FormsAuthentication模塊處於活動狀態,因此您可以在web.config中查找這樣的行:
<remove name="FormsAuthentication" />
並刪除它,並添加或更新身份驗證部分:
<authentication mode="Forms">
<forms loginUrl="~/account/login" timeout="2880" defaultUrl="~/" protection="All" />
</authentication>
通過這些設置,ASP.NET知道從FormsAuthentication.SetAuthCookie
生成的cookie構建Identity和Principle。
話雖這么說,FormsAuthentication在這一點上不是推薦的路徑,因為它依賴於System.Web,而且它不是聲明感知的事實。
您可以使用確實產生聲明感知身份的OWIN來完成最小設置。 如果您使用較新的ASP.NET項目模板,那么您應該在App_Start文件夾中有一個Startup.Auth.cs文件,或者您可以添加一個。 使用OWIN進行基於cookie的身份驗證的最小代碼是:
using Microsoft.AspNet.Identity;
using Microsoft.Owin;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Cookies;
using Owin;
public partial class Startup
{
public void ConfigureAuth(IAppBuilder app)
{
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
LoginPath = new PathString("/account/login"),
LogoutPath = new PathString("/account/logout"),
CookieName = ".YOUR_COOKIE_NAME_HERE",
SlidingExpiration = true,
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
AuthenticationMode = AuthenticationMode.Active
});
}
}
然后,當您對用戶進行身份驗證時,您會執行以下操作:
var claims = new List<Claim>();
claims.Add(new Claim(ClaimTypes.Name, model.UserName));
var identity = new ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie);
HttpContext.Current.Request.GetOwinContext().Authentication.SignIn(identity);
並退出:
HttpContext.Current.Request.GetOwinContext().Authentication.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
您還需要在Global.asax文件中設置以下值:
using System.Web.Helpers;
using System.Security.Claims;
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
// ... your other startup/registration code ...
AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.Name;
}
}
Request.IsAuthenticated
只是檢查當前請求上下文中是否已建立非匿名身份,因此上述任一選項都將起作用。
暫時不說 : 你真的不應該用純文本存儲密碼。 創建用戶記錄時,使用Crypto.HashPassword
創建密碼的鹽漬哈希值,然后存儲密碼,然后在檢查用戶是否輸入正確的密碼時使用Crypto.VerifyHashedPassword
。 您可以在此處找到加密文檔 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.