阿里、蚂蚁、晟腾、中科加禾精彩分享 AI 基础设施洞见,现购票可享受 9 折优惠 |AICon 了解详情
写点什么

ASP.NET MVC 5 改进了基于过滤器的身份验证

  • 2013-09-09
  • 本文字数:764 字

    阅读完需:约 3 分钟

ASP.NET MVC 5 包含在最近发布的 Visual Studio 2013 开发者预览版中,它使开发人员可以应用身份验证过滤器,它们提供了使用各种第三方供应商或自定义的身份验证提供程序进行用户身份验证的能力。不过,这些过滤器要在调用授权过滤器之前应用。

为了创建身份验证过滤器,开发人员需要新建一个 C#ASP.NET 工程,并且从列出的工程类型中选择 MVC。来自 Kunz,Leigh&Associates 公司的高级软件开发工程师 Eric Vogel 已经测试了身份验证过滤器的用法。他创建了一个自定义过滤器,如果用户未通过身份验证,就将其重定向回登录页面。

Eric 创建了一个 CustomAttributes 目录和一个新类 CustomeAttribute,该类继承了

复制代码
ActionFilterAttribute 和 IAuthenticationFilter:
public class BasicAuthAttribute: ActionFilterAttribute,IAuthenticationFilter

接口 IAuthenticationFilter 的 OnAuthentication()方法可以用于执行任何需要的身份验证,而 OnAuthenticationChallenge 方法基于已验证用户的身份限制其访问。

OnAuthenticationChallenge 方法接收 AuthenticationChallengeContext 参数,其实现代码如下所示:

复制代码
public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext)
{
var user = filterContext.HttpContext.User;
if (user == null || !user.Identity.IsAuthenticated)
{
filterContext.Result = new HttpUnauthorizedResult();
}
}

读者可以从 Eric 的博文获得完整的源代码。BasicAuthAttribute 类很容易测试,打开 HomeController 类文件,并添加下面的代码即可:

复制代码
using VSMMvc5AuthFilterDemo.CustomAttributes;

最后,将自定义属性应用到 HomeController 类,如下所示:

复制代码
[BasicAuthAttribute]
public class HomeController : Controller

查看英文原文: Improved Authentication with Filters in ASP.NET MVC 5

2013-09-09 07:538456
用户头像

发布了 256 篇内容, 共 81.6 次阅读, 收获喜欢 11 次。

关注

评论

发布
暂无评论
发现更多内容

Kotlin 协程使用手册

android 程序员 移动开发

Kotlin-+-协程-+-Retrofit-+-MVVM优雅的实现网络请求

android 程序员 移动开发

Kotlin从头开始(一):lambda表达式和高阶函数 一

android 程序员 移动开发

Jetpack-在数据变化时如何优雅更新Views数据

android 程序员 移动开发

Java之JNI初步认识

android 程序员 移动开发

Java的Url编码和解码

android 程序员 移动开发

Jaxb2 实现JavaBean与xml互转

android 程序员 移动开发

JetPack现在都成了Android开发必备技能嘛?

android 程序员 移动开发

Jetpack系列(一) — Navigation

android 程序员 移动开发

Linux 的make及makefile文件格式

android 程序员 移动开发

Linux虚拟机与Windows宿主机间的通信

android 程序员 移动开发

IOS开发之——事件处理-hiTest(69)

android 程序员 移动开发

Kotlin的自定义View,实现带弧形的进度条

android 程序员 移动开发

Linux上SSH免密登录

android 程序员 移动开发

IOS开发之——CABasicAnimation(95)

android 程序员 移动开发

JETPACK-COMPOSE-ALPHA-版现已发布!

android 程序员 移动开发

Koltin28

android 程序员 移动开发

Java线程(十):CAS

android 程序员 移动开发

JNI 与 NDK 入门(一)

android 程序员 移动开发

Koltin47

android 程序员 移动开发

ListView 与 RecyclerView 你应该弄懂的都在这里了

android 程序员 移动开发

Java 创建型模式:单态模式,原型模式,工厂方法

android 程序员 移动开发

JS Bridge实现

android 程序员 移动开发

Kotlin协程实现原理概述

android 程序员 移动开发

JAVA-Android-多线程实现方式及并发与同步

android 程序员 移动开发

Fabric.js 从入门到________

德育处主任

大前端 可视化 canvas 画布 FabricJS

Kotlin Lambda巩固

android 程序员 移动开发

JETPACK-COMPOSE-ALPHA-版现已发布!(1)

android 程序员 移动开发

Jetpack Compose 1

android 程序员 移动开发

Jetpack系列——ViewModel

android 程序员 移动开发

Java 网络:InetAddress类的应用以及通过Socket实现TCP编程

android 程序员 移动开发

ASP.NET MVC 5改进了基于过滤器的身份验证_安全_Anand Narayanaswamy_InfoQ精选文章