Question

Is it possible to use the AllowAnonymous attribute with Windows Azure AD?

I need a part of my web api to be anonymous, but not the actual website.

Any ideas?

Was it helpful?

Solution

Azure AD does not need to support anonymous auth for you to be able to use the AllowAnonymous attribute in your WebAPI.

I believe what you desire is unauthenticated access to some controllers of the WebAPI. It is possible. See this .Net sample: https://github.com/AzureADSamples/WebAPI-ManuallyValidateJwt-DotNet/blob/master/TodoListService-ManualJwt/Global.asax.cs. It validates the token and sets the Thread.CurrentPrincipal if the token is valid and returns an error if it can't find a token.

For your WebAPI - you wont return an error here - but instead not set the Thread.CurrentPrincipal when no token is present. - then you will decorate your controllers with Authorize and AllowAnonymous attributes to disallow or allow anonymous access.

Hope this helps.

PS: Down vote wasn't mine :-)

OTHER TIPS

Ok, I could solve it by choosing in the Identity and Access windows that the auth should go in a controller. Then I added this code:

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);
        }
    }
}

This attribute goes now in my 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());
        }
    }
}

And in my web.config I added this passiveRedirectEnabled="false" in configuration/system.identityModel.services/federationConfiguration/wsFederation that works perfect :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top