mvc 权限
来源:互联网 发布:win732位安装SQL无反应 编辑:程序博客网 时间:2024/06/08 19:55
在ASP.NET MVC中,通过使用其所提供的内置
[Authorize]
public ActionResult Index()
标记的方式,可以实现所标记的ACTION必须是认证用户才能访问;
通过使用
[Authorize(Users="username")]
的方式,可以实现所标记的ACTION必须是某个具体的用户才能访问,以上两种方式使用起来非常方便,在NeedDinner示例程序中已有具休的实现过程,
但是,我们在实际的应用中所使用的大都是基于角色(Roles)的认证方式,NeedDinner中却未给出,本文给出具体实现(基于ASP.NET Forms验证)过程:
step 1
在完成UserName和Password认证后,向客户端写入认证Cookie
FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(
1,
userName,
DateTime.Now,
DateTime.Now.AddMinutes(20),
false,
"admin"//写入用户角色
);
string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
System.Web.HttpCookie authCookie = new System.Web.HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
System.Web.HttpContext.Current.Response.Cookies.Add(authCookie);
step 2
在Global.asax.cs文件中加入以下代码,用于在用户登陆网站时读取Cookie
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
HttpCookie authCookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie == null || authCookie.Value == "")
{
return;
}
FormsAuthenticationTicket authTicket = null;
try
{
authTicket = FormsAuthentication.Decrypt(authCookie.Value);
}
catch
{
return;
}
string[] roles = authTicket.UserData.Split(new char[] { ';' });
if (Context.User != null)
{
Context.User = new System.Security.Principal.GenericPrincipal(Context.User.Identity, roles);
}
}
{
HttpCookie authCookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie == null || authCookie.Value == "")
{
return;
}
FormsAuthenticationTicket authTicket = null;
try
{
authTicket = FormsAuthentication.Decrypt(authCookie.Value);
}
catch
{
return;
}
string[] roles = authTicket.UserData.Split(new char[] { ';' });
if (Context.User != null)
{
Context.User = new System.Security.Principal.GenericPrincipal(Context.User.Identity, roles);
}
}
step 3
这样以来,就可以使用实现以下效果
[Authorize(Roles="admin")]
public ActionResult Index(int ? page)
public ActionResult Index(int ? page)
非常方便!
0 0
- mvc 权限
- MVC中权限
- MVC 权限验证Filter
- mvc 权限控制
- spring mvc 权限拦截
- mvc 权限控制
- MVC权限设计
- MVC模式中的权限控制
- .NET MVC 中的权限控制
- asp.net MVC 权限设计
- asp.net MVC 权限设计
- asp.net MVC 权限设计
- Asp.net MVC自定义权限
- MVC 全局菜单权限过滤器
- asp.net MVC 权限设计
- MVC身份验证及权限管理
- asp.net core mvc权限控制:权限控制介绍
- asp.net core mvc权限控制:分配权限
- sgu-250 Constructive Plan
- 财务会计基础知识
- hdu 3533 搜索+预处理
- jsp中的ServletContext
- netstat
- mvc 权限
- android中的屏幕适配
- oracle查询常用的知识点之日期,重复字段,groupby,查询大量数据时优化
- NSDictionary 字典类
- the Sieve of Eratosthenes
- 分享到微信/空间/微博
- 测试看看
- 一、我们应当怎样做需求分析
- What is JNI?