简体   繁体   English

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

[英]How to protect all contents(.aspx,.asp,.js and img ,etc) of an asp.net web site if we use Azure AD authentication?

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

This configuration doesn't even taking me login screen.这个配置甚至不带我登录屏幕。

在此处输入图片说明

My startup.cs has configuration for Azure AD.我的 startup.cs 有 Azure AD 的配置。 but where exactly/what code to be made for protecting all contents(.aspx,.asp,.js and .img)但是为了保护所有内容(.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>

This config lets me to go login page.这个配置让我去登录页面。 but even after Azure authentication , it doesn't that realize user is authenticated and not landing to default.aspx , instead it goes back login screen again.但即使在 Azure 身份验证之后,它也没有意识到用户已通过身份验证并且没有登陆到 default.aspx ,而是再次返回登录屏幕。 Please help.请帮忙。

For ASPX and ASP pages you can implement an Http Module that inspects the request and validates the appropiate token has been attached to the request.对于 ASPX 和 ASP 页面,您可以实现一个Http 模块来检查请求并验证是否已附加到请求中。 For other resources you might try implementing an Http Handler that does the same.对于其他资源,您可以尝试实现执行相同操作的Http 处理程序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM