ASP.NET MVC View 和 Web API 的基本权限验证
ASP.NET MVC 5.0已经发布一段时间了,适应了一段时间,准备把原来的MVC项目重构了一遍,先把基本权限验证这块记录一下。
环境:Windows 7 Professional SP1 + Microsoft Visual Studio 2013(MVC 5 + Web API 2)
修改Web.config,增加Forms验证模式,在system.web节点中增加以下配置:
<authentication mode="Forms">
<forms loginUrl="~/login" defaultUrl="~/" protection="All" timeout="20" name="__auth" />
</authentication>
【MVC View Controller 篇】
新建一个PageAuth,继承自AuthorizeAttribute:
using System;
using System.Net;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
public class PageAuth : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
if (httpContext == null)
{
return false;
} if (httpContext.User.Identity.IsAuthenticated && base.AuthorizeCore(httpContext))
{
return ValidateUser();
} httpContext.Response.StatusCode = (int)HttpStatusCode.Forbidden;
return false;
} public override void OnAuthorization(AuthorizationContext filterContext)
{
base.OnAuthorization(filterContext); if (filterContext.HttpContext.Response.StatusCode == (int)HttpStatusCode.Forbidden)
{
filterContext.Result = new RedirectToRouteResult("AccessErrorPage", null);
}
} protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
filterContext.HttpContext.Response.Redirect(FormsAuthentication.LoginUrl);
} private bool ValidateUser()
{
//TODO: 权限验证
return true;
}
}
建一个Controller的基类PageBase,继承自Controller:
using System.Web.Mvc;
[PageAuth]
public class PageBase : Controller
{
}
所有View的Controller均继承自PageBase,不再继承自Controller。
继承PageBase之后,所有的Controller均需登录,给允许匿名访问的Controller(或Action)增加AllowAnonymous(以AccountController为例):
using System.Web.Mvc;
public class AccountController : PageBase
{
[AllowAnonymous]
public ActionResult Login() // 可匿名访问
{
ViewBag.Title = "用户登录";
return View();
} public ActionResult Detail(int id) // 需登录访问
{
ViewBag.Title = "用户详情";
return View();
}
}
页面Controller的开发,基本结束,接下来就是在登录页面(~/login)使用js提交登录信息,用post方式提交。
提交之后,需要开发Web API的接口了。
【MVC Web API Controller 篇】
同样,新建一个ApiAuth,继承自ActionFilterAttribute:
using System;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
using System.Web.Security;
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
public class ApiAuth : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
try
{
if (actionContext.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().Count > ) // 允许匿名访问
{
base.OnActionExecuting(actionContext);
return;
} var cookie = actionContext.Request.Headers.GetCookies();
if (cookie == null || cookie.Count < )
{
actionContext.Response = new HttpResponseMessage(HttpStatusCode.Forbidden);
return;
} FormsAuthenticationTicket ticket = null; foreach (var perCookie in cookie[].Cookies)
{
if (perCookie.Name == FormsAuthentication.FormsCookieName)
{
ticket = FormsAuthentication.Decrypt(perCookie.Value);
break;
}
} if (ticket == null)
{
actionContext.Response = new HttpResponseMessage(HttpStatusCode.Forbidden);
return;
} // TODO: 添加其它验证方法 base.OnActionExecuting(actionContext);
}
catch
{
actionContext.Response = new HttpResponseMessage(HttpStatusCode.Forbidden);
}
}
}
新建一个ApiController的基类ApiBase,继承自ApiController:
using System.Web.Http;
[ApiAuth]
public class ApiBase : ApiController
{
}
所有API的Controller均继承自ApiBase,不再继承自ApiController。
继承ApiBase之后,给允许匿名访问的Controller(或Action)增加AllowAnonymous(以LoginController为例):
using System.Web.Http;
using System.Web.Security;
public class LoginController : ApiBase
{
[HttpPost]
[AllowAnonymous]
public bool Login([FromBody]LoginInfo loginInfo)
{
try
{
var cookie = FormsAuthentication.GetAuthCookie("Username", false);
var ticket = FormsAuthentication.Decrypt(cookie.Value);
var newTicket = new FormsAuthenticationTicket(ticket.Version, ticket.Name, ticket.IssueDate, ticket.Expiration, ticket.IsPersistent, "");
cookie.Value = FormsAuthentication.Encrypt(newTicket);
DeyiContext.Response.Cookies.Add(cookie);return true;
}
catch
{
return false;
}
}
}
【写在最后】
网上查了很多方法,还需要时间验证一下各个方法的合理度。
关于Web API的安全性,个人觉得,还是采用SSL的方式更加稳妥一些。
另外,网上很多写的在Web API的权限判断的时候,使用的是actionContext.Request.Headers.Authorization来判断,如下:
if (actionContext.Request.Headers.Authorization == null)
{
// 判断是否允许匿名访问
}
else
{
var ticket = FormsAuthentication.Decrypt(actionContext.Request.Headers.Authorization.Parameter);
// 后续其它验证操作
}
还没有完成测试该方法,慢慢来吧~~~
ASP.NET MVC View 和 Web API 的基本权限验证的更多相关文章
- 如何将一个 ASP.NET MVC 4 和 Web API 项目升级到 ASP.NET MVC 5 和 Web API 2
----转自微软官网www.asp.net/mvc/ ASP.NET MVC 5 和 Web API 2 带来的新功能,包括属性路由. 身份验证筛选器,以及更多的主机.请参阅http://www.as ...
- 在ASP.NET MVC中使用Web API和EntityFramework构建应用程序
最近做了一个项目技术预研:在ASP.NET MVC框架中使用Web API和EntityFramework,构建一个基础的架构,并在此基础上实现基本的CRUD应用. 以下是详细的步骤. 第一步 在数据 ...
- 在ASP.NET MVC里对Web Page网页进行权限控制
我们在ASP.NET MVC开发时,有时候还是得设计ASP.NET的Web Page网页(.aspx和.aspx.cs),来实现一些ASP.NET MVC无法实现的功能,如此篇<Visual S ...
- MVC中使用Web API和EntityFramework
在ASP.NET MVC中使用Web API和EntityFramework构建应用程序 最近做了一个项目技术预研:在ASP.NET MVC框架中使用Web API和EntityFramework ...
- 002.Create a web API with ASP.NET Core MVC and Visual Studio for Windows -- 【在windows上用vs与asp.net core mvc 创建一个 web api 程序】
Create a web API with ASP.NET Core MVC and Visual Studio for Windows 在windows上用vs与asp.net core mvc 创 ...
- ASP.NET Core MVC中构建Web API
在ASP.NET CORE MVC中,Web API是其中一个功能子集,可以直接使用MVC的特性及路由等功能. 在成功构建 ASP.NET CORE MVC项目之后,选中解决方案,先填加一个API的文 ...
- 从头编写 asp.net core 2.0 web api 基础框架 (1)
工具: 1.Visual Studio 2017 V15.3.5+ 2.Postman (Chrome的App) 3.Chrome (最好是) 关于.net core或者.net core 2.0的相 ...
- 【转载】从头编写 asp.net core 2.0 web api 基础框架 (1)
工具: 1.Visual Studio 2017 V15.3.5+ 2.Postman (Chrome的App) 3.Chrome (最好是) 关于.net core或者.net core 2.0的相 ...
- 从零开始学习 asp.net core 2.1 web api 后端api基础框架(二)-创建项目
原文:从零开始学习 asp.net core 2.1 web api 后端api基础框架(二)-创建项目 版权声明:本文为博主原创文章,未经博主允许不得转载. https://blog.csdn.ne ...
随机推荐
- MVC5+EF6+MYSQl,使用codeFirst的数据迁移
之前本人在用MVC4+EF5+MYSQL搭建自己的博客.地址:www.seesharply.com;遇到一个问题,就是采用ef的codefirst模式来编写程序,我们一般会在程序开发初期直接在glob ...
- ASP.NET MVC5+EF6+EasyUI 后台管理系统(69)-微信公众平台开发-功能概述
系列目录 为什么要先发这个文章? 因为接下来的文章是关于微信开发的系列,心中一定要有一个概念,知道自己接下来要做什么功能. 而且微信到处都是坑,我首先要把微信与本地跑通起来才敢发布,否则中间出现坑导致 ...
- 学习ASP.NET Core,怎能不了解请求处理管道[1]: 中间件究竟是个什么东西?
ASP.NET Core管道虽然在结构组成上显得非常简单,但是在具体实现上却涉及到太多的对象,所以我们在 "通过重建Hosting系统理解HTTP请求在ASP.NET Core管道中的处理流 ...
- 一个诡异的COOKIE问题
今天下午,发现本地的测试环境突然跑不动了,thinkphp直接跑到异常页面,按照正常的排错思路,直接看thinkphp的log 有一条 [ error ] [2]setcookie() expects ...
- Web安全相关(三):开放重定向(Open Redirection)
简介 那些通过请求(如查询字符串和表单数据)指定重定向URL的Web程序可能会被篡改,而把用户重定向到外部的恶意URL.这种篡改就被称为开发重定向攻击. 场景分析 假设有一个正规网站http:// ...
- 解决Android Studio 无法显示Layout视图问题
在Android Studio 当中,如果你选择的SDK的版本 与你所显示的视图版本不一致时,会出现这个错误 Exception raised during rendering:com/android ...
- C#发送邮箱
之前自己从来没有做过发送邮箱的功能,前段时间项目需要,在找了很多帖子之后,终于实现了. 之后有整理了一下,写了一个类.直接给类传递信息,就可以发送了. 这里还需要说明的是,发送邮箱需要开通POP3/S ...
- mysql 大表拆分成csv导出
最近公司有一个几千万行的大表需要按照城市的id字段拆分成不同的csv文件. 写了一个自动化的shell脚本 在/home/hdh 下面 linux-xud0:/home/hdh # lltotal 1 ...
- BZOJ 2756: [SCOI2012]奇怪的游戏 [最大流 二分]
2756: [SCOI2012]奇怪的游戏 Time Limit: 40 Sec Memory Limit: 128 MBSubmit: 3352 Solved: 919[Submit][Stat ...
- 闭区间套定理(Nested intervals theorem)
① ②这里用到了极限与不等关系 ③如果a≠b,那么便不会有$\lim _{n\rightarrow \infty }\left| I_n \right| =0$ ④如果还存在一点c在内,那么同样也不会 ...