在MVC中使用AzureAD身份验证保护静态文件(.html,.css,.png等)

时间:2020-09-04 12:10:49

标签: c# model-view-controller azure-active-directory static-files

我有一个.NET MVC网站,使用AzureAD对用户进行身份验证。 所有控制器均以[Authorize]属性修饰。

考虑到安全性,我们不希望未经身份验证的用户访问/下载应用程序的静态内容,例如图像,.js,.css文件。

谁能建议一个好的方法。

2 个答案:

答案 0 :(得分:0)

Saca发布的解决方案为我指明了正确的方向,但是将JS添加到每一页对我来说都不是有效的解决方案。有成千上万的HTML文件,很多没有普通的JS文件,我可以将ADAL代码添加到其中。我本来必须找到一种在所有这些页面上插入该JS的方法。

我的第一个解决方案是简单地创建一个具有正确身份验证的普通.NET MVC应用。然后,我只是通过iFrame加载了这些旧内容。这行得通,但对用户是有限制的。

正如费雪在另一条评论中提到的那样,下一个解决方案涉及到废弃iFrame,而是通过控制器路由对静态文件的所有请求。以此作为理解以下内容的参考:https://weblogs.asp.net/jongalloway/asp-net-mvc-routing-intercepting-file-requests-like-index-html-and-what-it-teaches-about-how-routing-works

以上解决方案有效。但是,最终此应用最终以Azure应用服务的身份出现,我只是使用纯HTML文件在应用服务级别打开了身份验证

答案 1 :(得分:0)

我发现了这一点并通过使用以下方法成功实现了这一点:

  1. 在最后添加app.UseStageMarker(PipelineStage.Authenticate); app.UseOpenIdConnectAuthentication()。请参考下面Startup类的代码。

  2. 在 Web.configs 中添加以下内容。

    enter image description here

  3. 下添加以下内容

    enter image description here

public partial class Startup
{
    public Startup()
    {
    }

    public void ConfigureAuth(IAppBuilder app)
    {
        app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            CookieManager = new SystemWebChunkingCookieManager(),
        });

        app.UseOpenIdConnectAuthentication(
            new OpenIdConnectAuthenticationOptions
            {
                MetadataAddress = String.Format(Globals.WellKnownMetadata, Globals.TenantId, Globals.DefaultPolicy),

                ClientId = Globals.ClientId,
                RedirectUri = Globals.RedirectUri,
                PostLogoutRedirectUri = Globals.LogoutPostUri,

                TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = true,
                },

                ResponseType = OpenIdConnectResponseType.CodeIdToken,
                Scope = OpenIdConnectScope.OpenIdProfile + OpenIdConnectScope.OfflineAccess,
                CookieManager = new SystemWebCookieManager()
            }
        );
        app.UseStageMarker(PipelineStage.Authenticate);
    }
}