自定义身份验证和ASP.NET MVC [英] Custom Authentication and ASP.NET MVC

查看:156
本文介绍了自定义身份验证和ASP.NET MVC的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在兴建中 ASP.NET 4 内部Web应用程序。我们被卡住使用由另一个团队建立了一个认证API。如果该站点的用户为网站身份验证成功,我想给他们访问整个网站。

I have an internal web app being built in ASP.NET 4. We are stuck with using an authentication API built by another team. If a user to the site is authenticated successfully for the site I would like to give them access to the entire site.

ASP.NET 天的WebForm我只是用来保持一个自定义的用户对象的会话。如果该对象为null,我知道该用户未通过身份验证。是否有 MVC 此类似,但改进的方法。我不希望有建立自己的ASP.NET成员模型如果可能的供应商。什么是这样做的最简单的方法?

In ASP.NET WebForm days I just used to keep a custom User object in session. If that object was null I knew the user wasn't authenticated. Is there a similar but improved method for this in MVC. I don't want to have to build my own provider of the ASP.NET Membership model if possible. What is the simplest way of doing this?

推荐答案

您可以使用表单验证中一起选择与授权 attibute如下,

You can use Forms Authentication in conjuction with Authorize attibute as follows,

要限制访问视图:

在AuthorizeAttribute属性添加到动作方法的声明,如下图所示,

Add the AuthorizeAttribute attribute to the action method declaration, as shown below,

[Authorize]
public ActionResult Index()
{
    return View();
}

在web.config中配置表单验证

Configuring Forms Authentication in web.config

<authentication mode="Forms">
     <forms loginUrl="~/Account/Login" timeout="2880" />
</authentication>

登录后动作:
设置身份验证cookie,如果用户是有效的。

Login Post Action: Set Authentication cookie if user is valid

[HttpPost]
public ActionResult Login(User model, string returnUrl)
{
        //Validation code

        if (userValid)
        {
             FormsAuthentication.SetAuthCookie(username, false);
        }
}

注销操作:

public ActionResult LogOff()
{
    FormsAuthentication.SignOut();
    return RedirectToAction("Index", "Home");
}

这篇关于自定义身份验证和ASP.NET MVC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆