Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-mvc/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用Thinktecture.IdentityModel申请授权_C#_Asp.net Mvc_Security_Claims Based Identity - Fatal编程技术网

C# 使用Thinktecture.IdentityModel申请授权

C# 使用Thinktecture.IdentityModel申请授权,c#,asp.net-mvc,security,claims-based-identity,C#,Asp.net Mvc,Security,Claims Based Identity,如上所述,有两种方法可以使用Thinktecture.IdentityModel设置索赔授权检查。一个是设置一个过滤器。另一个是向要检查的操作添加属性 我正在成功地使用属性选项。但是,我希望覆盖向登录页面发送未经授权(但经过身份验证)请求的行为 相反,我想简单地给出一个401错误(或未经授权的页面)。到目前为止,我有以下类覆盖HandleUnauthorizedRequest并抛出401错误(如果经过身份验证)。然而,我知道如何将它连接起来的唯一方法是将这个类添加为过滤器。通过这样做,它跳过了属

如上所述,有两种方法可以使用Thinktecture.IdentityModel设置索赔授权检查。一个是设置一个过滤器。另一个是向要检查的操作添加属性

我正在成功地使用属性选项。但是,我希望覆盖向登录页面发送未经授权(但经过身份验证)请求的行为

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

    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()
{
  ...
}
此外,我发现即使在我的web.config文件中有以下内容,抛出UnauthorizedAccessException也不会向用户显示指定的401错误页面。相反,他们会收到一般错误页面

<customErrors mode="On" defaultRedirect="ErrorPage.aspx">
   <error statusCode="401" redirect="ErrorNoAccess.aspx" />
</customErrors>
和my web.config错误页指定为:

<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页面,而不是跳转到登录页面(如果我选中“记住我”,该页面实际上会变成一个循环)

我真的不明白微软是怎么想的,因为一个经过有效认证但未经授权的请求,我把用户扔到了登录页面。没有向用户反馈他们为什么会返回登录页面,也没有任何提示用户尝试不同的凭据(他们甚至不太可能有不同的凭据)

<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>