如果我们使用Azure AD身份验证,如何保护asp.net网站的所有内容.aspx,.asp,.js和img等?

问题描述

 <authorization>
  <deny users="?"/>
  <allow users="*"/>
</authorization>
<authentication mode="None">
  <forms loginUrl="~/login.aspx" timeout="2880"/>
</authentication>

此配置甚至都不会让我登录屏幕。

enter image description here

我的startup.cs具有Azure AD的配置。但是在什么地方/应该编写什么代码来保护所有内容(.aspx,.asp,.js和.img)

 app.SetDefaultSignInAsAuthenticationType(OpenIdConnectAuthenticationDefaults.AuthenticationType);
        app.UseCookieAuthentication(new CookieAuthenticationoptions());
        app.USEOpenIdConnectAuthentication(
            new OpenIdConnectAuthenticationoptions
            {
                Authority = authority,ClientId = clientId,ClientSecret= clientsecret,RedirectUri = redirectUri,PostlogoutRedirectUri = redirectUri,Scope = $"openid",TokenValidationParameters = new TokenValidationParameters()
                {
                    NameClaimType = "preferred_username",ValidateIssuer = true,Validissuer = tenant
                },Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    RedirectToIdentityProvider = OnRedirectToIdentityProvider,AuthorizationCodeReceived = OnAuthorizationCodeReceived,AuthenticationFailed = OnAuthenticationFailed
                }
            }
        ); 

 private Task OnRedirectToIdentityProvider(RedirectToIdentityProviderNotification<OpenIdConnectMessage,OpenIdConnectAuthenticationoptions> notification)
    {
        var policy = notification.OwinContext.Get<string>("Policy");

        if (!string.IsNullOrEmpty(policy) && !policy.Equals(DefaultPolicy))
        {
            notification.ProtocolMessage.Scope = OpenIdConnectScope.OpenId;
            notification.ProtocolMessage.ResponseType = OpenIdConnectResponseType.IdToken;
            notification.ProtocolMessage.IssuerAddress = notification.ProtocolMessage.IssuerAddress.ToLower().Replace(DefaultPolicy.ToLower(),policy.ToLower());
        }

        return Task.Fromresult(0);
    }
    private Task OnAuthenticationFailed(AuthenticationFailedNotification<OpenIdConnectMessage,OpenIdConnectAuthenticationoptions> context)
    {
        context.HandleResponse();
        context.Response.Redirect("/?errormessage=" + context.Exception.Message);
        return Task.Fromresult(0);
    }
    private async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivednotification notification)
    {
        try
        {                
            IConfidentialClientApplication confidentialClient = MsalAppBuilder.BuildConfidentialClientApplication(new ClaimsPrincipal(notification.AuthenticationTicket.Identity));

            // Upon successful sign in,get & cache a token using MSAL
            AuthenticationResult result = await confidentialClient.AcquiretokenByAuthorizationCode(Scopes,notification.Code).ExecuteAsync();

            string username = notification.AuthenticationTicket.Identity.FindFirst("preferred_username").Value;
            FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1,username,DateTime.Now,DateTime.Now.AddMinutes(60),true,"");
            string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
            notification.Response.Cookies.Append(FormsAuthentication.FormsCookieName,encryptedTicket);
        }
        catch (Exception ex)
        {
            throw new HttpResponseException(new HttpResponseMessage
            {
                StatusCode = HttpStatusCode.BadRequest,ReasonPhrase = $"Unable to get authorization code {ex.Message}."
            });
        }
    }

<authentication mode="Forms">
  <forms loginUrl="~/login.aspx" timeout="2880"/>
</authentication>

此配置可让我进入登录页面。但是即使经过Azure身份验证,也不能实现对用户进行身份验证并且未登陆到default.aspx,而是会再次返回登录屏幕。请帮忙。

解决方法

对于ASPX和ASP页面,您可以实现Http Module来检查请求并验证适当的令牌已附加到请求。对于其他资源,您可以尝试实现同样的Http Handler