ASP.NET个IAuthorizationFilter OnAuthorization [英] ASP.NET IAuthorizationFilter OnAuthorization

查看:1903
本文介绍了ASP.NET个IAuthorizationFilter OnAuthorization的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好我想实现一个自定义过滤器的授权

Hi I am trying to implement a custom Authorization filter

 //The Authourization attribute on a controller
public class CustomAdminAuthorizationFilter : IAuthorizationFilter
{
    private readonly IAuthentication _authentication;

    public SageAdminAuthorizationFilter(IAuthentication authentication)
    {
        _authentication = authentication;
    }

    public void OnAuthorization(AuthorizationContext filterContext)
    {
       bool result = _authentication.Authorize(filterContext.HttpContext);
    }
}

你可以在OnAuthorization我得到一个结果是假的真见。
什么我需要设置返回我从哪里来?

As you can see on the OnAuthorization I get back a result that is true of false. What do I need to set to return where I came from?

编辑:

这似乎仍然直接扔我到登录页面

It still seems to throw me straight to the log in page

我做的注入IAuthetication

I do inject IAuthetication

 this.BindFilter<CustomAdminAuthorizationFilter>(FilterScope.Controller, 0);
   Bind<IAuthentication>().To<CustomAuthenticationService>();

然后我装点我的控制器动作如此。

Then I decorate my action in the controller as so.

[Authorize]
    public ActionResult Index()
    {
        ViewBag.Title = "Welcome";
        ViewBag.Message = "Welcome to ASP.NET MVC!";

        return View();
    }

在我的web.config进出口使用

In my web.config Im using

<authentication mode="Forms">
  <forms loginUrl="~/Account/LogOn" timeout="2880" />
</authentication>

如果有这样的改变?

Should this be altered?

任何帮助将大大AP preciated。

Any help would be greatly appreciated.

推荐答案

修改成一个属性,而不是简单的一个个IAuthorizationFilter
您还需要抛出 UnauthorizedAccessException 你的 OnAuthorization 方法中

Change that to an Attribute, not simple a IAuthorizationFilter You also need to throw an UnauthorizedAccessException within your OnAuthorization method

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class SageAdminAuthorizeAttribute : AuthorizeAttribute, IAuthorizationFilter
{
    readonly IAuthentication _authentication;

    public SageAdminAuthorizeAttribute(IAuthentication authentication)
    {
        _authentication = authentication;
    }

    public void OnAuthorization(AuthorizationContext filterContext)
    {
        if (!_authentication.Authorize(filterContext.HttpContext))
            throw new UnauthorizedAccessException();
    }
}

和现在,而不是使用 [授权] 使用新的 [SageAdminAuthorize] 属性

And now rather than using [Authorize] use your new [SageAdminAuthorize] attribute

[SageAdminAuthorize]
public ActionResult Index()
{
    ViewBag.Title = "Welcome";
    ViewBag.Message = "Welcome to ASP.NET MVC!";

    return View();
}

这篇关于ASP.NET个IAuthorizationFilter OnAuthorization的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆