使用thinktecure . identitymodel声明授权



正如在leastprivilege中所解释的,有两种方法可以使用Thinktecture.IdentityModel设置claim Authorization检查。一种是设置一个过滤器。另一种方法是为您想要检查的操作添加属性。

我成功地使用了属性选项。但是,我想重写向登录页面发送未经授权(但经过身份验证)请求的行为。

相反,我想简单地显示401错误(或未经授权的页面)。到目前为止,我有以下类来覆盖HandleUnauthorizedRequest并抛出401错误(如果Authenticated)。然而,我所知道的连接它的唯一方法是将这个类添加为过滤器。通过这样做,它跳过了使用属性修饰,只将动作/资源发送给checkaccess方法,这对我们来说是无用的。

    public class CustomClaimsAuthorizeAttribute : Thinktecture.IdentityModel.Authorization.Mvc.ClaimsAuthorizeAttribute
{
    public CustomClaimsAuthorizeAttribute()
    {
    }
    public CustomClaimsAuthorizeAttribute(string action, params string[] resources)
        : base(action, resources)
    {
    }

    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        if (filterContext.HttpContext.User.Identity.IsAuthenticated)
            throw new UnauthorizedAccessException("Insufficent permissions.");
        base.HandleUnauthorizedRequest(filterContext);
    }
}

谁可能感兴趣。我最终意识到,这就像使用我自己的类名作为属性一样(可笑地)简单。

CustomClaimsAuthorizeAttribute("myParameter")
public ActionResult Index()
{
  ...
}

此外,我发现即使在我的网页中有以下内容。抛出UnauthorizedAccessException不会向用户显示指定的401错误页面。相反,他们会收到一般的错误页面。

<customErrors mode="On" defaultRedirect="ErrorPage.aspx">
   <error statusCode="401" redirect="ErrorNoAccess.aspx" />
</customErrors>

这个异常产生:

" ASP。NET未被授权访问所请求的资源。考虑向ASP授予对资源的访问权限。网络请求的身份。ASP。. NET有一个基本进程标识(通常是{MACHINE} asp.net在iis5或网络服务在iis6和iis7,和(IIS 7.5上配置的应用程序池标识)应用程序没有进行模拟。如果申请是冒充通过,身份将是匿名用户(通常是IUSR_MACHINENAME)或经过身份验证的用户请求用户。"

我决定抛出403 (Forbidden)错误。所以我的重写最终看起来像这样:

protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
    if (filterContext.HttpContext.User.Identity.IsAuthenticated)
        throw new HttpException((int)HttpStatusCode.Forbidden, "Unauthorized access");
    base.HandleUnauthorizedRequest(filterContext);
}

还有我的网。配置错误页面指定为:

<customErrors mode="On" defaultRedirect="ErrorPage.aspx">
  <error statusCode="403" redirect="ErrorNoAccess.aspx" />
  <error statusCode="404" redirect="ErrorNotFound.aspx" />
  <error statusCode="500" redirect="ErrorPage.aspx" />
</customErrors>

我现在可以作为一个没有足够权限的用户登录,并显示ErrorNoAccess。aspx页面,而不是被抛出到登录页面(如果我选中了'remember me',实际上会变成一个循环)。

我真的不明白微软是怎么想的,把用户扔到登录页面,因为一个有效的身份验证,但未经授权的请求。没有反馈给用户为什么他们会被扔回登录页面,也没有提示用户尝试不同的凭据(这是极不可能的,他们甚至有不同的凭据)。

最新更新