【问题标题】:Azure AD allow anonymousAzure AD 允许匿名
【发布时间】:2014-09-22 19:38:00
【问题描述】:

是否可以在 Windows Azure AD 中使用 AllowAnonymous 属性?

我需要我的网络 API 的一部分是匿名的,但不是实际的网站。

有什么想法吗?

【问题讨论】:

    标签: c# asp.net-mvc asp.net-web-api azure-active-directory


    【解决方案1】:

    Azure AD 无需支持匿名身份验证即可在 WebAPI 中使用 AllowAnonymous 属性。

    我相信您想要的是未经身份验证访问 WebAPI 的某些控制器。有可能的。请参阅此 .Net 示例:https://github.com/AzureADSamples/WebAPI-ManuallyValidateJwt-DotNet/blob/master/TodoListService-ManualJwt/Global.asax.cs。它验证令牌并在令牌有效时设置 Thread.CurrentPrincipal 并在找不到令牌时返回错误。

    对于您的 WebAPI - 您不会在此处返回错误 - 但在不存在令牌时不设置 Thread.CurrentPrincipal。 - 然后您将使用 Authorize 和 AllowAnonymous 属性装饰您的控制器,以禁止或允许匿名访问。

    希望这会有所帮助。

    PS:否决票不是我的 :-)

    【讨论】:

    • 谢谢 :) 我稍后再试试 :)
    • 看看我的回答stackoverflow.com/a/25057396/1126393 但我想我会接受你的回答:)
    • 这段代码不起作用,如果我调用 api 它只是重定向到登录页面。
    【解决方案2】:

    好的,我可以通过在身份和访问窗口中选择身份验证应该进入控制器来解决这个问题。然后我添加了这段代码:

    CustomAuthorize

    using System.Configuration;
    using System.Web;
    using System.Web.Mvc;
    namespace Namespace.Filters {
        public class CustomAuthorize : AuthorizeAttribute {
            protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) {
                string issuer = System.Configuration.ConfigurationManager.AppSettings.Get("ida:Issuer");
    
                // default issuer, use if loading from AppSettings fails.
                if (issuer == null) {
                    issuer = "https://login.windows.net/98297c67-25a1-404d-aab3-673b6096747f/wsfed";
                }
                var reply = ConfigurationManager.AppSettings["reply"];
                reply = HttpUtility.UrlEncode(HttpUtility.UrlEncode(reply));
                var SignInRequest = string.Format(@"{0}?wa=wsignin1.0&wtrealm=https%3a%2f%2f{myapp}%2f&wctx=rm%3d0%26id%3d2fcc67c4-3671-408b-b6fe-0c2cae2763c9%26ru%3d{1}&wct=2014-07-31T01%3a21%3a16Z", issuer, reply);
                filterContext.RequestContext.HttpContext.Response.Redirect(SignInRequest);
            }
        }
    }
    

    这个属性现在在我的FilterConfig

    using Namespace.Filters;
    using System.Web;
    using System.Web.Mvc;
    
    namespace Namespace {
        public class FilterConfig {
            public static void RegisterGlobalFilters(GlobalFilterCollection filters) {
                filters.Add(new HandleErrorAttribute());
                filters.Add(new CustomAuthorize());
            }
        }
    }
    

    在我的 web.config 中,我在 configuration/system.identityModel.services/federationConfiguration/wsFederation 中添加了这个 passiveRedirectEnabled="false",效果很好:)

    【讨论】:

      猜你喜欢
      • 2020-07-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-30
      • 2016-01-11
      相关资源
      最近更新 更多