ASP.NET MVC中的基本认证5
发布时间:2020-05-25 02:05:22 所属栏目:asp.Net 来源:互联网
导读:在 ASP.NET MVC 5中执行基本认证必须采取哪些步骤? 我读过OWIN不支持无Cookie认证,基本认证通常是可能的吗? 我需要一个自定义属性吗?我不知道这些属性如何工作。 您可以使用此简单而有效的机制使用自定义ActionFilter属性: public class BasicAuthentica
|
在 ASP.NET MVC 5中执行基本认证必须采取哪些步骤? 我读过OWIN不支持无Cookie认证,基本认证通常是可能的吗? 我需要一个自定义属性吗?我不知道这些属性如何工作。 解决方法您可以使用此简单而有效的机制使用自定义ActionFilter属性:public class BasicAuthenticationAttribute : ActionFilterAttribute
{
public string BasicRealm { get; set; }
protected string Username { get; set; }
protected string Password { get; set; }
public BasicAuthenticationAttribute(string username,string password)
{
this.Username = username;
this.Password = password;
}
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var req = filterContext.HttpContext.Request;
var auth = req.Headers["Authorization"];
if (!String.IsNullOrEmpty(auth))
{
var cred = System.Text.ASCIIEncoding.ASCII.GetString(Convert.FromBase64String(auth.Substring(6))).Split(':');
var user = new { Name = cred[0],Pass = cred[1] };
if (user.Name == Username && user.Pass == Password) return;
}
filterContext.HttpContext.Response.AddHeader("WWW-Authenticate",String.Format("Basic realm="{0}"",BasicRealm ?? "Ryadel"));
/// thanks to eismanpat for this line: http://www.ryadel.com/en/http-basic-authentication-asp-net-mvc-using-custom-actionfilter/#comment-2507605761
filterContext.Result = new HttpUnauthorizedResult();
}
}
它可以用于将基本认证置于整个控制器中: [BasicAuthenticationAttribute("your-username","your-password",BasicRealm = "your-realm")]
public class HomeController : BaseController
{
...
}
或具体ActionResult: public class HomeController : BaseController
{
[BasicAuthenticationAttribute("your-username",BasicRealm = "your-realm")]
public ActionResult Index()
{
...
}
}
你也可以read here for more info。 (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- asp.net – 由于其保护级别,未声明变量可能无法访问
- 在Asp.net中加载平衡,在开发时我应该考虑什么?
- asp.net – Web.config自定义错误模式冲突
- ASP.NET Web应用程序(MVC)部署自动化和Subversion
- asp.net-mvc – ASP.NET MVC模型/ ViewModel验证
- asp.net-mvc – 使用IIS基本身份验证的OWIN身份验证
- asp.net-mvc-4 – SimpleMembershipInitializer不会初始化
- 尝试将AutoMapper用于具有子集合的模型,在Asp.Net MVC 3中获
- asp.net-mvc – 在visual studio中快速更改视图和控制器的方
- asp.net-mvc – 在MVC3中使用两个可选参数的路由不起作用
推荐文章
站长推荐
- asp.net – 在oauth身份验证后获取Twitter用户名
- asp.net-core – 是否可以直接在Azure WebApps中
- asp.net-mvc – ASP.NET MVC – 从查询字符串中获
- asp.net-mvc-3 – 根据asp.net mvc3中的下拉列表
- .net – 是否必须在自定义实现中覆盖默认的成员资
- asp.net-mvc – 将依赖项注入自定义模型绑定器并
- ASP.NET Ajax客户端框架无法加载.将ScriptManage
- 将用户添加到角色ASP.NET身份
- asp.net – 将数值强制为HTML表导出为excel的文本
- asp.net-mvc – 在嵌套内容的区域上使用_ViewSta
热点阅读
