MVC Dynamic Authorization--示例市在Action前进行的验证,应提前到Auth过滤器
Introduction
In MVC the default method to perform authorization is hard coding the "Authorize" attribute in the controllers, for each action, in this article I will explain a simple way to implement "Dynamic Authorization" with the ability to assign permissions for actions to roles or users.
Using the code
First I will explain my user authentication and role assigning model, I have used Forms Authentication this scenario, here is my sample login action:

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginModel model, string returnUrl)
{
//sample data
Dictionary<string, string> users = new Dictionary<string, string>();
users.Add("admin", "admin-pass"); string roles; if (users[model.UserName] == model.Password)
{
Session["User"] = model.UserName;
roles = "admin;customer";
// put the roles of the user in the Session
Session["Roles"] = roles; HttpContext.Items.Add("roles", roles); //Let us now set the authentication cookie so that we can use that later.
FormsAuthentication.SetAuthCookie(model.UserName, false); //Login successful lets put him to requested page
string returnUrl = Request.QueryString["ReturnUrl"] as string; return RedirectToLocal(returnUrl); if (returnUrl != null)
{
Response.Redirect(returnUrl);
}
else
{
//no return URL specified so lets kick him to home page
Response.Redirect("Default.aspx");
}
}
else
{
// If we got this far, something failed, redisplay form
ModelState.AddModelError("",
"The user name or password provided is incorrect");
return View(model);
}
}
All the actions that need authentication have to be loaded in a list, and also all of the roles and actions that each role has access to, I have put some sample code to simulate them "AllRoles" and "NeedAuthenticationActions". Then we need to create a base class for controllers in which I have overridden the OnActionExecuting
method, in which the user will be authorized based on its current role and whether he/she has logged in or not, the action may also has no need to be authorized.

public class ControllerBase : Controller
{
private string ActionKey; //sample data for the roles of the application
Dictionary<string, List<string>> AllRoles =
new Dictionary<string, List<string>>(); protected void initRoles()
{
AllRoles.Add("role1", new List<string>() { "Controller1-View",
"Controller1-Create", "Controller1-Edit", "Controller1-Delete" });
AllRoles.Add("role2", new List<string>() { "Controller1-View", "Controller1-Create" });
AllRoles.Add("role3", new List<string>() { "Controller1-View" });
}
//sample data for the pages that need authorization
List<string> NeedAuthenticationActions =
new List<string>() { "Controller1-Edit", "Controller1-Delete"}; protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
ActionKey = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName +
"-" + filterContext.ActionDescriptor.ActionName; string role = Session["Roles"].ToString();//getting the current role
if (NeedAuthenticationActions.Any(s => s.Equals(ActionKey, StringComparison.OrdinalIgnoreCase)))
{
if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
{
string redirectUrl = string.Format("?returnUrl={0}",
filterContext.HttpContext.Request.Url.PathAndQuery);
filterContext.HttpContext.Response.Redirect(FormsAuthentication.LoginUrl + redirectUrl, true);
}
else //check role
{
if (!AllRoles[role].Contains(ActionKey))
{
filterContext.HttpContext.Response.Redirect("~/NoAccess", true);
}
}
}
}
Points of Interest
MVC Dynamic Authorization--示例市在Action前进行的验证,应提前到Auth过滤器的更多相关文章
- mvc中Action前HttpPost的作用
本文导读:在ASP.NET MVC框架中,为了限制某个action只接受HttpPost的请求,对于HttpGet的请求则提示404找不到页面,可以在action的方法前面加上[HttpPost]属性 ...
- ASP.NET MVC和ASP.NET Core MVC中获取当前URL/Controller/Action (转载)
ASP.NET MVC 一.获取URL(ASP.NET通用): [1]获取完整url(协议名+域名+虚拟目录名+文件名+参数) string url=Request.Url.ToString(); [ ...
- Pro ASP.NET Core MVC 第6版 第二章(前半章)
目录 第二章 第一个MVC 应用程序 学习一个软件开发框架的最好方法是跳进他的内部并使用它.在本章,你将用ASP.NET Core MVC创建一个简单的数据登录应用.我将它一步一步地展示,以便你能看清 ...
- MVC中如何在controller的action中输出JS到页面上
MVC中如何在controller的action中输出JS到页面上 可以通过Http上下文对象(httpContext)就可以了,在Action中的HttpContext就是这个Action所指向的页 ...
- 【转】前端Web开发MVC模式-入门示例
前端Web开发MVC模式-入门示例 MVC概论起初来之桌面应用开发.其实java的structs框架最能体现MVC框架:model模型是理解成服务器端的模块程序:view为发送给客服端的内容:cont ...
- ASP.NET MVC 学习7、为Model Class的字段添加验证属性(validation attribuate)
Adding Validation to the Model ,在Model中添加数据验证 参考:http://www.asp.net/mvc/tutorials/mvc-4/getting-star ...
- 在MVC中添加拦截器实现登录后的权限验证
1.新建一个类 (以下实现了打印日志功能) using System; using System.Collections.Generic; using System.Linq; using Syste ...
- ASP.NET MVC和WebForm 轻松实现前端和后端的双重验证 jquery.validate+ValidationSugar
上次不足的改进 可能上一个贴子给大家带来很多误解,所以我这次把DEMO完善了两个版本 [ASP.NET WEBFROM]和[ ASP.NET MVC] 修改了一些BUG,并且修改了一些细了 在上个贴子 ...
- mvc中动态给一个Model类的属性设置验证
原文:mvc中动态给一个Model类的属性设置验证 在mvc中有自带的验证机制,比如如果某个字段的类型是数字或者日期,那么用户在输入汉字或者英文字符时,那么编译器会自动验证并提示用户格式不正确,不过这 ...
随机推荐
- Zookeeper工作原理
ZooKeeper是一个分布式的,开放源码的分布式应用程序协调服务,它包含一个简单的原语集,分布式应用程序可以基于它实现同步服务,配置维护和命名服务等.Zookeeper是hadoop的一个子项目,其 ...
- ASP.NET vs MVC vs WebForms
许多ASP.NET开发人员开始接触MVC认为MVC与ASP.NET完全没有关系,是一个全新的Web开发,事实上ASP.NET是创建WEB应用的框架而MVC是能够用更好的方法来组织并管理代码的一种更高级 ...
- iOS基础CGAffineTransform的简单使用
CoreGraphics框架中的CGAffineTransform类可用于设定UIView的transform属性,控制视图的缩放.旋转和平移操作: 另称放射变换矩阵,可参照线性代数的矩阵实现方式0. ...
- acdream 1685 多民族王国(DFS,并查集)
Problem Description 娜娜好不容易才回忆起自己是娜娜而不是什么Alice,也回忆起了自己要继续探索这个世界的目标,便偷偷溜出皇宫.娜娜发现这个王国有很多个民族组成,每个民族都有自己的 ...
- php flock注意事项
对于实际的运用,必须将其添加到所有使用的文件脚本中 但注意:其函数无法再NFS或其他网络文件系统中使用也无法在多线程服务器API中使用.
- MYSQL建立索引需要注意几点
1.建立索引的时机:若表中的某字段出现在select.过滤.排序条件中,为该字段建立索引是值得的.2.对于like '%xxx'的模糊查询,普通的索引是无法满足的,需要建立全文索引.3.对于有多个条件 ...
- CSS hack——不同浏览器的CSS应对法
1.IE条件注释法: lte表示“小于等于”,“lt”表示“小于”,“gte”表示“大于等于”,“gt”表示“大于”,“!”表示“不等于”. <!--[if IE 6]> <link ...
- 更改 input type 的值
需要实现的效果:一个输入框,当输入框未获得焦点的时候,value 值为 “密码”:当输入框失去焦点的时候,输入内容显示为”*****” <input name=”password” type=” ...
- SQLSERVER 检查字段值域并输出行数和值列表
select * from ( SELECT 'C_DILEI' as fen,'地类' as fcn, 'NVARCHAR'as ftype, '2'as flen, ( SELECT count( ...
- 64 位系统遇到未在本地计算机上注册 Microsoft.Jet.OLEDB.4.0
本人写的.net程序部署在windowsserver 2003的操作系统上正常,部署到windows server 2008上时候报错“未在本地计算机上注册 Microsoft.Jet.OLEDB.4 ...