MVC 中的身份验证和授权

本文关键字:授权 身份验证 MVC | 更新日期: 2023-09-27 17:56:46

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

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

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

下一步是有一个授权方法,该方法在用户想要执行任何操作时运行(当用户单击按钮或链接时检查)。

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

我的问题是:

1-每当用户想要执行任何操作时,我如何运行授权功能?

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

MVC 中的身份验证和授权

1 在用户想要做任何操作时运行授权功能

添加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=部分可能不是应用程序身份验证方法所需的部分。 但原理是一样的。