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中有自带的验证机制,比如如果某个字段的类型是数字或者日期,那么用户在输入汉字或者英文字符时,那么编译器会自动验证并提示用户格式不正确,不过这 ...
随机推荐
- leetcode:Count and Say
The count-and-say sequence is the sequence of integers beginning as follows:1, 11, 21, 1211, 111221, ...
- D3D中深度测试和Alpha混合的关系
我在学习D3D的深度测试和Alpha混合的时候,有一些遗憾.书上提供的例子里说一定要先渲染不透明物体,再渲染透明物体,对渲染状态的设置也有特殊要求.我看的很晕.自己查图形学的书,上网找资料,结果还是糊 ...
- Eclipse 上安装 Maven3插件
原文:http://www.cnblogs.com/quanyongan/archive/2013/04/18/3028181.html eclipse 安装插件的方式最常见的有两种: 1. 一种是在 ...
- [转]微软联合CSDN英雄在线编程大赛
2014 新年将至,微软联合CSDN英雄会共同举办本次第三届在线编程大赛,题目详情如下: 有一个字符串"iinbinbing",截取不同位置的字符‘b’.‘i’.‘n’.‘g’组合 ...
- win7防火墙开启ping
默认情况下,Windows7出于安全考虑是不允许外部主机对其进行Ping测试的. 但在局域网环境中,Ping是测试网络情况的常用手段,如何允许 Windows7的ping测试回显呢? 打开: 控制面板 ...
- Uploadify上传Excel到数据库
前两章简单的介绍了Uploadify上传插件的基本使用和相关的属性说明.这一章结合Uploadify+ssh框架+jquery实现Excel上传并保存到数据库. 以前写的这篇文章 Jq ...
- [转]JavaScript 的性能优化:加载和执行
原文链接:http://www.ibm.com/developerworks/cn/web/1308_caiys_jsload/index.html?ca=drs- JavaScript 的性能优化: ...
- ecshop首页调用评论及图片
1.在library文件夹中建立一个名为index_comment.lbi文件 2.输入以下代码 <meta http-equiv="Content-Type" conten ...
- uva 11991
STL 使用,,由于数据范围没有 超越极限数据 依旧可以用 vector 搞定: #include<iostream> #include<stdio.h> #include& ...
- linux echo命令的-n、-e两个参数
echo -n 不换行输出 $echo -n "123" $echo "456" 最终输出 123456 而不是 123 456 echo -e 处理特殊字符 ...