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:

Collapse | Copy Code
[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.

Collapse | Copy Code
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过滤器的更多相关文章

  1. mvc中Action前HttpPost的作用

    本文导读:在ASP.NET MVC框架中,为了限制某个action只接受HttpPost的请求,对于HttpGet的请求则提示404找不到页面,可以在action的方法前面加上[HttpPost]属性 ...

  2. ASP.NET MVC和ASP.NET Core MVC中获取当前URL/Controller/Action (转载)

    ASP.NET MVC 一.获取URL(ASP.NET通用): [1]获取完整url(协议名+域名+虚拟目录名+文件名+参数) string url=Request.Url.ToString(); [ ...

  3. Pro ASP.NET Core MVC 第6版 第二章(前半章)

    目录 第二章 第一个MVC 应用程序 学习一个软件开发框架的最好方法是跳进他的内部并使用它.在本章,你将用ASP.NET Core MVC创建一个简单的数据登录应用.我将它一步一步地展示,以便你能看清 ...

  4. MVC中如何在controller的action中输出JS到页面上

    MVC中如何在controller的action中输出JS到页面上 可以通过Http上下文对象(httpContext)就可以了,在Action中的HttpContext就是这个Action所指向的页 ...

  5. 【转】前端Web开发MVC模式-入门示例

    前端Web开发MVC模式-入门示例 MVC概论起初来之桌面应用开发.其实java的structs框架最能体现MVC框架:model模型是理解成服务器端的模块程序:view为发送给客服端的内容:cont ...

  6. ASP.NET MVC 学习7、为Model Class的字段添加验证属性(validation attribuate)

    Adding Validation to the Model ,在Model中添加数据验证 参考:http://www.asp.net/mvc/tutorials/mvc-4/getting-star ...

  7. 在MVC中添加拦截器实现登录后的权限验证

    1.新建一个类 (以下实现了打印日志功能) using System; using System.Collections.Generic; using System.Linq; using Syste ...

  8. ASP.NET MVC和WebForm 轻松实现前端和后端的双重验证 jquery.validate+ValidationSugar

    上次不足的改进 可能上一个贴子给大家带来很多误解,所以我这次把DEMO完善了两个版本 [ASP.NET WEBFROM]和[ ASP.NET MVC] 修改了一些BUG,并且修改了一些细了 在上个贴子 ...

  9. mvc中动态给一个Model类的属性设置验证

    原文:mvc中动态给一个Model类的属性设置验证 在mvc中有自带的验证机制,比如如果某个字段的类型是数字或者日期,那么用户在输入汉字或者英文字符时,那么编译器会自动验证并提示用户格式不正确,不过这 ...

随机推荐

  1. 《OD大数据实战》HBase整合MapReduce和Hive

    一.HBase整合MapReduce环境搭建 1. 搭建步骤1)在etc/hadoop目录中创建hbase-site.xml的软连接.在真正的集群环境中的时候,hadoop运行mapreduce会通过 ...

  2. Python3 学习第十二弹: 补充something

    python中遇到 *keys, **keys的形式 其实 * 代表传递任意个无名字参数,这些参数通过Tuple访问 >>> def sum(*keys): ret= 0 for i ...

  3. C# Winform 获取天气情况

    WebServices(http://www.webxml.com.cn/WebServices/WeatherWebService.asmx)来实现天气预报,该天气预报 Web 服务,数据来源于中国 ...

  4. iOS富文本(三)深入使用Text Kit

    在上一篇中介绍了Text Kit的三种基本组件的关系并且简单的实现了怎么使用这三种基本组件,本片将深入的去使用这三种基本组件. NSTextStorage NSTextStorage是NSMutabl ...

  5. Eclipse附加项目中的某个jar包的源码

    1.这里以web项目为例,打开项目应用的jar包:如下图 2.在想要引入源码的jar包上右键>属性(Properties)

  6. UVa (BFS) The Monocycle

    题目不光要求要到达终点而且要求所走的步数为5的倍数,每个时刻有三个选择,前进,左转弯,右转弯. 所以在vis数组中新增加两个维度即可,vis[x][y][dir][color]表示在(x, y)格子方 ...

  7. linux CPU loading calculate

    http://hi.baidu.com/lionpanther/item/e908c37abdaf1c3f71442380 #include <stdio.h>#include <s ...

  8. PHP学习笔记06——面向对象版图形计算器

    index.php 用于显示页面 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "h ...

  9. #define | enum(enumerator)

    /**************************************************************************** * #define | enum(enume ...

  10. erl0008 - unicode 和 utf-8之间的关系

    转载:http://blog.jobbole.com/84903/ 原文出处: 卢钧轶   欢迎分享原创到伯乐头条 本文将简述字符集,字符编码的概念.以及在遭遇乱码时的一些常用诊断技巧. 背景:字符集 ...