MVC框架的一个很重要的优势在于可拓展性很高。权限的管理在每一个Web应用程序中都非常重要,虽然微软提供了Membership的默认权限设置,但在更多的情况下,Membership默认的权限设置并不能满足我们实际的需要。
下面本文将用一种简单的办法来自定义权限。
在MVC框架中,属性常用来限定控制器(Controller)的访问。所以我们首先从AuthorizeAttribute类中继承一个自定义的权限类。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MvcApplication_AuthorizeAttribute.Models
{
public class MyAuthAttribute : AuthorizeAttribute
{
// 只需重载此方法,模拟自定义的角色授权机制
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
if (!httpContext.User.Identity.IsAuthenticated)//判断用户是否通过验证
return false;
string[] StrRoles = Roles.Split(',');//通过逗号来分割允许进入的用户角色
if (string.IsNullOrWhiteSpace(Roles))//如果只要求用户登录,即可访问的话
return true;
bool isAccess = JudgeAuthorize(httpContext.User.Identity.Name, StrRoles);
if (StrRoles.Length > 0 && isAccess) //先判断是否有设用户权限,如果没有不允许访问
return false;
return true;
}
/// <summary>
/// 根据用户名判断用户是否有对应的权限
/// </summary>
/// <param name="UserName"></param>
/// <param name="StrRoles"></param>
/// <returns></returns>
private bool JudgeAuthorize(string UserName, string[] StrRoles)
{
string UserAuth = GetRole(UserName); //从数据库中读取用户的权限
return StrRoles.Contains(UserAuth, //将用户的权限跟权限列表中做比较
StringComparer.OrdinalIgnoreCase); //忽略大小写
}
// 返回用户对应的角色, 在实际中, 可以从SQL数据库中读取用户的角色信息
private string GetRole(string name)
{
switch (name)
{
case "aaa": return "User";
case "bbb": return "Admin";
case "ccc": return "God";
default: return "Fool";
}
}
}
}