NET允许匿名访问OData

NET允许匿名访问OData

本文介绍了当站点具有全局AuthorizeAttribute时,ASP.NET允许匿名访问OData $ metadata的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ASP.NET OData站点,该站点在WebApiConfig文件中具有以下内容:

I have an ASP.NET OData site that has the following in the WebApiConfig file:

config.Filters.Add(new AuthorizeAttribute())

这将强制所有调用方在调用任何控制器之前进行身份验证.
不幸的是,这也迫使用户认证访问"$ metadata" URL.
我需要全局强制所有控制器访问进行身份验证,同时还允许匿名访问"$ metadata" URL.

This forces all callers to authenticate before calling any of the controllers.
Unfortunately, this also forces user authentication to access the "$metadata" url.
I need to globally force authentication for all controller access while also allowing anonymous access the the "$metadata" url.

推荐答案

创建一个从AuthorizeAttribute派生并自定义IsAuthorized方法的自定义过滤器,如下所示:

Create a custom filter that derives from AuthorizeAttribute and override the IsAuthorized method as follows:

public class CustomAuthorizationFilter : AuthorizeAttribute
{
    protected override bool IsAuthorized(HttpActionContext actionContext)
    {
        if (actionContext.Request.RequestUri.AbsolutePath == "/$metadata" ||
            actionContext.Request.RequestUri.AbsolutePath == "/%24metadata")
        {
            return true;
        }

        return base.IsAuthorized(actionContext);
    }
}

注册过滤器:

config.Filters.Add(new CustomAuthorizationFilter());

这篇关于当站点具有全局AuthorizeAttribute时,ASP.NET允许匿名访问OData $ metadata的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 04:30