How to Prevent login redirect to 'login.microsoftonline.com' when user accesses secure page.

Eric 0 Reputation points
2024-04-16T20:06:27.7333333+00:00

Hello,

I am trying to have any user redirected to my login page, which has a login for ASP.net 4.8 Identity, and a button for Microsoft AD login which sends them to their company login page.

Currently it words great, but if they access a page directly in the secure directory first and are not authenticated via Identity using SQL DB AspNet tables, or AD/Entra, they only get redirected to the Microsoft login (login.microsoftonline.com). I have reviewed extensively this article (https://learn.microsoft.com/en-us/answers/questions/1517432/how-to-stop-auto-redirect-to-login-microsoft-after) to no avail and many other articles for many weeks.

My client has AD users and non-AD users, but all users are sent to login.microsoftonline.com, unless they specifically type the apps login url.., I'd like all users to be sent to my login page, then the AD users can hit the company login.

/Login.aspx (all users can access this page any time)

/App/Home.aspx (secure page) (if not logged in all users are redirected (login.microsoftonline.com) but I want them to go to /Login.aspx )

Here is my Startup.Auth.cs file: Where authMode = "openId".

Any assistance is greatly appreciated.

 public void ConfigureAuth(IAppBuilder app)
 {
     // Configure the db context, user manager and signin manager to use a single instance per request
     app.CreatePerOwinContext(ApplicationDbContext.Create);
     app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
     app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);
     //// Enable the application to use a cookie to store information for the signed in user
     //// and to use a cookie to temporarily store information about a user logging in with a third party login provider
     //// Configure the sign in cookie
     ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
     
     var val = Environment.GetEnvironmentVariable("APPSETTING_USER_TIMEOUT_HOURS");
     int timoutInHours = 168;// 1 week
     if (!string.IsNullOrEmpty(val))
     {
         timoutInHours = Convert.ToInt32(val);
     }
     switch (authMode)
     {
        // other cases removed for clarity
         case "openId":
             
             app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
             app.UseCookieAuthentication(new CookieAuthenticationOptions());
             app.UseOpenIdConnectAuthentication(
                 new OpenIdConnectAuthenticationOptions
                 {
                     ClientId = clientId,
                     Authority = authority,
                     PostLogoutRedirectUri = postLogoutRedirectUri,
                     //Scope = OpenIdConnectScope.OpenIdProfile,
                     //// ResponseType is set to request the code id_token - which contains basic information about the signed-in user
                     //ResponseType = OpenIdConnectResponseType.CodeIdToken,
                     TokenValidationParameters = new TokenValidationParameters()
                     {
                         ValidateIssuer = true // This is a simplification
                     },
                     Notifications = new OpenIdConnectAuthenticationNotifications()
                     {
                         AuthenticationFailed = (context) =>
                         {
                             return Task.FromResult(0);
                         },
                         SecurityTokenValidated = (context) =>
                         {
                             string name = context.AuthenticationTicket.Identity.FindFirst("preferred_username").Value;
                             context.AuthenticationTicket.Identity.AddClaim(new Claim(ClaimTypes.Name, name, string.Empty));
                         
                             
                             
                           
                             }
                             return Task.FromResult(0);
                         }
                     }
                 });
             
             app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));
             // This makes any middleware defined above this line run before the Authorization rule is applied in web.config
             app.UseStageMarker(PipelineStage.Authenticate);
             break;
         
     }
 }
Active Directory
Active Directory
A set of directory-based technologies included in Windows Server.
5,877 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. hossein jalilian 2,835 Reputation points
    2024-04-16T21:44:11.6266667+00:00

    Thanks for posting your question in the Microsoft Q&A forum.

    You can override the OnRedirectToIdentityProvider event to customize the redirection logic:

    public void ConfigureAuth(IAppBuilder app)
     {
         // Configure the db context, user manager and signin manager to use a single instance per request
         app.CreatePerOwinContext(ApplicationDbContext.Create);
         app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
         app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);
         //// Enable the application to use a cookie to store information for the signed in user
         //// and to use a cookie to temporarily store information about a user logging in with a third party login provider
         //// Configure the sign in cookie
         ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
         
         var val = Environment.GetEnvironmentVariable("APPSETTING_USER_TIMEOUT_HOURS");
         int timoutInHours = 168;// 1 week
         if (!string.IsNullOrEmpty(val))
         {
             timoutInHours = Convert.ToInt32(val);
         }
         switch (authMode)
         {
            // other cases removed for clarity
             case "openId":
                 
                 app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
                 app.UseCookieAuthentication(new CookieAuthenticationOptions());
                 app.UseOpenIdConnectAuthentication(
                     new OpenIdConnectAuthenticationOptions
                     {
                         ClientId = clientId,
                         Authority = authority,
                         PostLogoutRedirectUri = postLogoutRedirectUri,
                         //Scope = OpenIdConnectScope.OpenIdProfile,
                         //// ResponseType is set to request the code id_token - which contains basic information about the signed-in user
                         //ResponseType = OpenIdConnectResponseType.CodeIdToken,
    					 Events = new OpenIdConnectAuthenticationEvents
    					    {
    					        OnRedirectToIdentityProvider = context =>
    					        {					            
    					            if (!context.HttpContext.User.Identity.IsAuthenticated)
    					            {					                
    					                context.Response.Redirect("/Login.aspx");
    					            }
    					            return Task.FromResult(0);
    					        }
    					    }
                        ...
                     });
                 
                 app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));
                 // This makes any middleware defined above this line run before the Authorization rule is applied in web.config
                 app.UseStageMarker(PipelineStage.Authenticate);
                 break;
             
         }
     }
    

    Please don't forget to close up the thread here by upvoting and accept it as an answer if it is helpful