使用isAuthenticated的C#.NET

使用isAuthenticated的C#.NET,c#,asp.net-mvc,C#,Asp.net Mvc,Im使用MVC格式创建网站。现在,它所做的只是从SQL server管理用户。我现在要做的是让用户登录,然后能够管理用户。从登录页面,它应该转到帐户的索引,但我只希望此页面可由经过身份验证的用户查看。如果我: 1) 将控制器中的函数设置为[AllowAnonymous](这不是我想要的) 2) 允许Windows身份验证(这不是我想要的,因为一旦部署,它将在web上) 它实际上只是归结为如何对用户进行身份验证,然后使该身份验证保持不变 以下是登录页面: @model myWebsite.Mode

Im使用MVC格式创建网站。现在,它所做的只是从SQL server管理用户。我现在要做的是让用户登录,然后能够管理用户。从登录页面,它应该转到帐户的索引,但我只希望此页面可由经过身份验证的用户查看。如果我:

1) 将控制器中的函数设置为[AllowAnonymous](这不是我想要的)

2) 允许Windows身份验证(这不是我想要的,因为一旦部署,它将在web上)

它实际上只是归结为如何对用户进行身份验证,然后使该身份验证保持不变

以下是登录页面:

@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>
}
老路™ 如果您所关心的只是坚持用户向您提供有效凭据的事实,那么最简单的选项可能是FormsAuthentication:

FormsAuthentication.SetAuthCookie(model.UserName, false);

这些要求FormsAuthentication模块处于活动状态,因此您可以在web.config中查找如下行:

<remove name="FormsAuthentication" />
然后,在对用户进行身份验证时,您可以执行以下操作:

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);

您还需要在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
。您可以找到。

请注意,模型视图控制器标记用于回答有关模式的问题。ASP.NET-MVC实现有一个特定的标记。没有。在Login()方法中验证用户的位置。建议您创建一个新的MVC项目,并研究VS为您创建的代码。请访问MVC站点,阅读关于此应用程序是否使用OWIN的部分也值得一提-如果您使用OWIN,可用的方法会略有变化。我对整个ASP.NET相当陌生,对C#来说有些新东西@所以说实话我不知道。虽然我没有检查或显式导入OWIN@StephenMuecke很抱歉我在写这篇文章时犯了错误。我仍然习惯于这个论坛。至于检查VS使用什么进行身份验证,这是非常深入的,有一天我想完全理解它的功能,但现在这些类中所做的大部分工作都超出了我的理解范围,我真的更愿意理解,而不是复制代码并使其工作,但不知道编写了什么。你的“右倾”解决方案有效,但现在我遇到一个错误:“提供的ClaimsEntity上不存在类型为“”或“”的声明”。我尝试使用以下行更改AntiForgeryConfig.UniqueClaimTypeIdentifier=ClaimTypes.Name;但我还是收到了错误。移除防伪标识是有效的(毫不奇怪),但我读的越多,这似乎是一个很好的使用方法。@Hippiewho抱歉,你是对的-我遗漏了部分答案。请参见编辑。除此之外,我在当前项目中使用的代码大致相同,没有错误。”您还需要在Global.asax文件中设置以下值:“好的,很酷。”。。哪里谢谢。@ScottK.Fraley
应用程序启动
,正常情况下。我已经更新了这一点。
<remove name="FormsAuthentication" />
<authentication mode="Forms">
  <forms loginUrl="~/account/login" timeout="2880" defaultUrl="~/" protection="All" />
</authentication>
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);
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;
    }
}