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中有自带的验证机制,比如如果某个字段的类型是数字或者日期,那么用户在输入汉字或者英文字符时,那么编译器会自动验证并提示用户格式不正确,不过这 ...
随机推荐
- Qt Linguist介绍
简介 Qt提供了一款优秀的支持Qt C++和Qt Quick应用程序的翻译工具.发布者.翻译者和开发者可以使用这款工具来完成他们的任务. 发布者:承担了全面发布应用程序的责任.通常,他们协调开发者和翻 ...
- 关于Qt
什么是Qt Qt是一个针对桌面.嵌入式.移动设备的一个跨平台的应用程序开发框架,支持的平台包括Linux.OS X.Windows.VxWorks.QNX.Android.iOS.BlackBerry ...
- POJ 1458 最长公共子序列
子序列就是子序列中的元素是母序列的子集,且子序列中元素的相对顺序和母序列相同. 题目要求便是寻找两个字符串的最长公共子序列. dp[i][j]表示字符串s1左i个字符和s2左j个字符的公共子序列的最大 ...
- [反汇编练习] 160个CrackMe之024
[反汇编练习] 160个CrackMe之024. 本系列文章的目的是从一个没有任何经验的新手的角度(其实就是我自己),一步步尝试将160个CrackMe全部破解,如果可以,通过任何方式写出一个类似于注 ...
- yii2.0 url 跳转
//转发 $this->render('page1',['id'=>3,'mark'=>2]); //显示page1页面 并传递 id mark 2个参数 //重定向 $thi ...
- HDU 4627 The Unsolvable Problem 2013 Multi-University Training Contest 3
给你一个数 n ( 2 <= n <= 109 ),现在需要你找到一对数a, b (a + b = n),并且使得LCM(a, b)尽可能的大,然后输出最大的 LCM(a, b). (为什 ...
- JVM——三个ClassLoader详解
类装载工作由ClassLoader及其子类负责,ClassLoader是一个重要的Java执行时系统组件,它负责在运行时查找和装入Class字节码文件.JVM在运行时会产生三个ClassLoader: ...
- Android 注解的一些应用以及原理
在这边文章之前你首先需要对java 的注解部分有一个基本的了解(不需要太过的深入). 简单来说,注解这个东西就是用于辅助我们开发java代码的,注解本身无法干扰java源代码的执行. 在android ...
- 在python中如何设置当前工作目录
import osos.chdir('要设置的当前目录') >>> import os >>> os.getcwd() 'D:\\Python27' >> ...
- jQuery基础知识--Form基础(续)
下拉框应用 <!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF ...