MVC中的身份验证和授权

时间:2015-06-17 09:05:53

标签: c# asp.net asp.net-mvc authentication

我用MVC创建了一个asp.net Web应用程序。到目前为止,一切都很好,除了身份验证和授权。

我想这样做:创建一个身份验证功能并将用户名和密码传递给它。

我已经创建了返回true或false的存储过程。身份验证函数只调用过程并返回true或false - 如果返回true,则用户将被验证,我们很高兴。

下一步是拥有一个授权方法,该方法在用户想要做任何事情时运行(当用户点击按钮或链接时进行检查)。

所以我创建了一个授权函数,并将用户名和函数ID传递给它。与身份验证功能一样,存储过程返回true或false。 True表示用户可以执行此操作,否则用户必须返回登录页面。

我的问题是:

1-如果用户想要做什么,我怎么能运行授权功能?

2-如何定义唯一的功能ID?我的意思是功能ID应该是什么? (对象ID?)

1 个答案:

答案 0 :(得分:1)

  只要用户想要做任何事情,

1运行authoristion函数

添加ActionFilterAttribute并将其应用于所有控制器

  

2给每个函数一个唯一的id

不需要,每个函数都有一个唯一的名称:控制器名称+动作名称(除非你有一些非常奇怪,无法管理的设置......)

示例:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public sealed class AuthoriseActionAttribute : ActionFilterAttribute
{
    public override void OnResultExecuted(ResultExecutedContext filterContext)
    {
        var user = HttpContext.Current.Request.LogonUserIdentity;
        var controller = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
        var action = filterContext.ActionDescriptor.ActionName;

        // call existing authorisation function here
        // using user, controller, action to determine if user has access
        bool authorised = ...

        if (!authorised) {
            // throw exception or redirect
            throw new UnauthorizedAccessException("You are not authorised to perform this action.");
        }

        base.OnAuthorization(filterContext);            
    }
}

用法:

[AuthoriseAction]
public class HomeController : Controller 

注意:我使用Windows身份验证,因此user=部分可能不是您的应用程序身份验证方法所需的部分。但原则是一样的。