Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AllowAnonymous Attribute not working MVC 5

Inside the Azure Portal I set App Service Authentication "On" For my Web App and I use AAD as Authentication Provider.

This has worked great up until now, I need an endpoint that will allow anonymous users, however the attribute [AllowAnonymous] does not work, I am still required to sign in.

Code:

[Authorize]
[RoutePrefix("users")]
public class UsersController : Controller
{
    [Route("register/{skypeid}")]
    public ActionResult Register(string skypeid)
    {
            ///stuff...            
        }
        catch (Exception ex)
        {
            return Content(ex + "");
        }

        ViewBag.Name = name;
        return View();

    }

    [AllowAnonymous]
    [Route("exists/{skypeid}")]
    public ActionResult Exists(string skypeid)
    {
        return Content("Hello " + skypeid);
    }

I think the code is right, so does it have something to do with the fact that I use App Service Authentication for my Web App?

EDIT: So, I found the source of the problem, In Azure if you set "Action to take when not Authenticated" to "Sign in with Azure Active Directory", it does never allow anonymous.

However, If I change it to allow anonymous then users are not prompted to sign in when trying to access a control with the [Authorize]-Attribute, it just tells me "You do not have permission to view this directory or page." Is this intended? It seems really weird. I want users to be redirected to Login if there is an [Authorize]-Attribute.

Screenshots for clarity:

enter image description here enter image description here

like image 636
Green_qaue Avatar asked Jan 03 '17 13:01

Green_qaue


2 Answers

Check your web.config if you have

<authorization>
  <deny users="?" />
</authorization>

its override [AllowAnonymous] add

<location path="YourController/AnonymousMethod">
    <system.web>
      <authorization>
        <allow users="*"/>
      </authorization>
    </system.web>
  </location>

to allow anonymous access

like image 72
alexey Avatar answered Oct 03 '22 06:10

alexey


I've just written about this in my book - http://aka.ms/zumobook - look in Chapter 6 for the MVC section.

The basic gist of it is that you need to do a little more to enable authentication; most specifically, you need to set up an auth pipeline (Azure Mobile Apps Server SDK will do this for you) and you need to set up a forms redirect within Web.config:

<system.web>
  <compilation debug="true" targetFramework="4.5.2"/>
  <httpRuntime targetFramework="4.5.2"/>
  <authentication mode="Forms">
    <forms loginUrl="/.auth/login/aad" timeout="2880"/>
  </authentication>
</system.web>

Since there are several details to adding the Mobile Apps SDK to your ASP.NET application, I'd refer to the referenced chapter for those details.

like image 25
Adrian Hall Avatar answered Sep 29 '22 06:09

Adrian Hall