AllowAnonymous属性不工作MVC 5

时间:2017-01-03 13:58:01

标签: asp.net-mvc azure asp.net-mvc-5 authorization

在Azure门户内部,我将App Service Authentication设置为“On”对于我的Web App,我使用AAD作为身份验证提供程序。

到目前为止这已经很好用,我需要一个允许匿名用户的端点,但是属性[AllowAnonymous]不起作用,我仍然需要登录。

代码:

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

我认为代码是正确的,它是否与我为我的Web应用程序使用App Service身份验证这一事实有关?

编辑: 因此,我发现了问题的根源,如果您将“未经过身份验证时采取的操作”设置为“使用Azure Active Directory登录”,则在Azure中,它永远不会允许匿名。

但是,如果我将其更改为允许匿名,则在尝试使用[Authorize] -Attribute访问控件时不会提示用户登录,它只是告诉我“您无权查看此目录或页面“。 这是有意的吗?这看起来很奇怪。如果有[Authorize] -Attribute。

,我希望用户被重定向到Login

为清晰起见屏幕截图:

enter image description here enter image description here

2 个答案:

答案 0 :(得分:7)

如果您有

,请检查您的web.config
<authorization>
  <deny users="?" />
</authorization>

其覆盖[AllowAnonymous] 添加

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

允许匿名访问

答案 1 :(得分:1)

我刚刚在我的书中写到了这一点 - http://aka.ms/zumobook - 请参阅第6章的MVC部分。

它的基本要点是你需要做更多的事情来启用身份验证;最具体地说,您需要设置一个auth管道(Azure Mobile Apps Server SDK将为您执行此操作),您需要在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>

由于将移动应用程序SDK添加到ASP.NET应用程序有几个细节,因此我将参考引用的章节了解这些细节。