首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >ASP.NET MVC中的用户身份验证和授权

ASP.NET MVC中的用户身份验证和授权
EN

Stack Overflow用户
提问于 2009-02-07 16:38:24
回答 6查看 33.7K关注 0票数 60

在ASP.NET MVC中进行用户授权/认证的最佳方法是什么?

我看到实际上有两种方法:

  • 使用内置的ASP.NET授权系统。
  • 使用具有我自己的用户、权限、UserGroup表等的自定义系统。

我更倾向于第二种选择,因为User是我的域模型的一部分(而且我对ASP.Net的内置内容有zero的经验),但我真的很想知道人们在这方面做了些什么。

EN

回答 6

Stack Overflow用户

回答已采纳

发布于 2009-02-07 16:42:36

实际上还有第三种方法。asp.net成员资格功能基于提供程序模型。您可以编写一个自定义提供程序,从而能够提供您自己的数据存储方式实现,但保留了asp.net成员资格的大部分好处。

关于这个主题的一些文章:

http://msdn.microsoft.com/en-us/library/f1kyba5e.aspx

http://www.asp.net/learn/videos/video-189.aspx

http://www.15seconds.com/issue/050216.htm

http://davidhayden.com/blog/dave/archive/2007/10/11/CreateCustomMembershipProviderASPNETWebsiteSecurity.aspx

票数 32
EN

Stack Overflow用户

发布于 2009-02-07 23:13:46

使用自定义。MembershipProvider对我来说太重了。是的,可以用一种简单的方式来实现它,但是你会得到一个NotSupportedException或NotImplementedException的really bad smell

使用完全自定义的实现,您仍然可以使用IPrincipal、IIdentity和FormsAuth。做你自己的登录页面真的有多难吗?

票数 25
EN

Stack Overflow用户

发布于 2011-04-14 21:21:30

最简单的方法是使用asp.net用户名作为角色名称。您可以编写自己的authorizarion属性来处理授权:

代码语言:javascript
复制
public class CustomAuthorizationAttribute:AuthorizeAttribute
{
    public CustomAuthorizationAttribute():base()
    {
        Users = "registereduser";
    }
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        //You must check if the user has logged in and return true if he did that.
        return (bool)(httpContext.Session["started"]??false); 

    }
    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        filterContext.HttpContext.Response.Redirect("SessionManagement/Index/?returningURL=" + 
            filterContext.HttpContext.Server.UrlEncode(filterContext.HttpContext.Request.Url.ToString()));

    }

}

如果用户启动了会话,代码必须处理AuthorizeCore以返回true,并处理HandleUnauthorizedRequest以将用户重定向到登录页面(可选的,您可以附加返回的url)。

然后在需要授权的控制器方法中,在它们上面设置属性:

代码语言:javascript
复制
public class SecretPageController {
    [CustomAuthorizationAttribute]
    ActionResult Index() {
        //Method that requires authorization
        return View();
    }

}

还要在web配置中将授权方法设置为"Forms“。

Web.config:

代码语言:javascript
复制
  <authentication>
      <forms timeout="120"></forms>
  </authentication>

控制器:

代码语言:javascript
复制
public SessionManagementController:Controller {
    public ActionResult Index(string returningURL)
    {
        return View("Index", new SessionModel() { ReturningURL = returningURL});
    }
    [HttpPost]        
    public ActionResult Index(SessionModel mod)
    {
        if (UserAuthenticated(mod.UserName, mod.Password))
        {
            FormsAuthentication.SetAuthCookie("registereduser", false);
            if (mod.UrlRetorno != null)
            {
                return Redirect(mod.ReturningURL);                    
            }
            return RedirectToAction("Index", "StartPage");
        }
        mod.Error = "Wrong User Name or Password";
        return View(mod);
    }
    bool UserAuthenticated(string userName, string password) {
       //Write here the authentication code (it can be from a database, predefined users,, etc)
        return true;
    }

    public ActionResult FinishSession()
    {
        HttpContext.Session.Clear();//Clear the session information
        FormsAuthentication.SignOut();
        return View(new NotificacionModel() { Message = "Session Finished", URL = Request.Url.ToString() });
    }

}

在控制器中,当用户输入其用户名和密码时,将forms身份验证cookie设置为TRUE (真),通知用户名(本例中为(FormsAuthentication.SetAuthCookie("registereduser",)进行身份验证。然后用户注销,调用FormsAuthentication.SignOut()告诉ASP.NET这样做。

型号:

代码语言:javascript
复制
class SessionModel {
    public string UserName {get;set;}
    public string Password {get;set;}
    public string Error {get;set;}
}  

使用模型来存储用户数据。

视图(呈现SessionModel类型):

代码语言:javascript
复制
        <div class="editor-label">
            <%: Html.LabelFor(model => model.UserName) %>
        </div>
        <div class="editor-field">
            <%: Html.TextBoxFor(model => model.UserName) %>
            <%: Html.ValidationMessageFor(model => model.UserName) %>
        </div>

        <div class="editor-label">
            <%: Html.LabelFor(model => model.Password) %>
        </div>
        <div class="editor-field">
            <%: Html.TextBoxFor(model => model.Password) %>
            <%: Html.ValidationMessageFor(model => model.Password) %>
        </div>
        <div class="field-validation-error"><%:Model==null?"":Model.Error??"" %></div>
        <%:Html.HiddenFor(model=>model.ReturningURL) %>
        <input type="submit" value="Log In" />

使用视图获取数据。在此示例中,有一个用于存储返回URL的隐藏字段

我希望这能有所帮助(我不得不翻译代码,所以我不确定它是否100%正确)。

票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/524086

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档