Azure AD Authentication with OWIN for ASP.NET WEB Forms Applicaiton - How to logout user after configurable inactive time

Padmasekhar Pottepalem 1 Reputation point
2022-01-28T02:46:03.497+00:00

We have an application which is build using ASP.NET WEB Forms (.NET Framework 4.6.2). Previously, we were using Windows authentication to authenticate user. Now, we want to change it to Azure AD authentication with MFA with OWIN (Open Id Connect) framework. I was able to do a POC till Azure AD authentication and MFA. However, we have another requirement that, Application should ask user for username and password to re-authenticate after 15 min in active time. I am unable to do this. Even, I am not sure whether it is possible with OpenId connect and Azure because I am new to Azure and SSO. Can someone please help me how I can achieve this? This is really important to us.

I have set Cookie expire time as well but, when cookie is expired it is internally re-authenticating user without asking username and password.

I have attached my Startup class.

using Microsoft.IdentityModel.Protocols.OpenIdConnect;
using Microsoft.Owin;
using Microsoft.Owin.Extensions;
using Microsoft.Owin.Host.SystemWeb;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.Notifications;
using Microsoft.Owin.Security.OpenIdConnect;
using Owin;
using System;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;

namespace AzureADWebForms
{
    public partial class Startup
    {
        private static string clientId = ConfigurationManager.AppSettings["ida:ClientId"];
        private static string aadInstance = EnsureTrailingSlash(ConfigurationManager.AppSettings["ida:AADInstance"]);
        //private static string tenant = ConfigurationManager.AppSettings["ida:Tenant"];
        private static string tenantId = ConfigurationManager.AppSettings["ida:TenantId"];
        private static string postLogoutRedirectUri = ConfigurationManager.AppSettings["ida:PostLogoutUri"];
        private static string redirectUri = ConfigurationManager.AppSettings["ida:redirectUri"];
        //private string authority = aadInstance + tenantId;
        private string authority = string.Empty;
        public Startup()
        {
            authority = Path.Combine(aadInstance, tenantId);
            //authority = String.Format(System.Globalization.CultureInfo.InvariantCulture, aadInstance, tenant);
        }


        public void ConfigureAuth(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            app.UseCookieAuthentication(new CookieAuthenticationOptions()
            {
                ExpireTimeSpan = TimeSpan.FromMinutes(2),
                //SlidingExpiration = true,
                Provider = new CookieAuthenticationProvider
                {
                    OnResponseSignIn = OnCustomResponseSignIn,
                    OnValidateIdentity = OnMyCustomValidateIdentity
                }
            });

            app.UseOpenIdConnectAuthentication(
            new OpenIdConnectAuthenticationOptions
            {
                ClientId = clientId,
                Authority = authority,
                RedirectUri = redirectUri,
                PostLogoutRedirectUri = postLogoutRedirectUri,
                Scope = OpenIdConnectScope.OpenIdProfile,
                //ResponseType = OpenIdConnectResponseType.IdToken,
                ResponseType = OpenIdConnectResponseType.CodeIdToken,
                UseTokenLifetime = false,
                Notifications = new OpenIdConnectAuthenticationNotifications()
                {
                    AuthenticationFailed = OnAuthenticationFailed,
                    RedirectToIdentityProvider = OnRedirectToIdentityProvider,
                    SecurityTokenValidated = OnSecurityTokenValidated 
                }

            });

            // This makes any middleware defined above this line run before the Authorization rule is applied in web.config
            app.UseStageMarker(PipelineStage.Authenticate);
        }

        private void OnCustomResponseSignIn(CookieResponseSignInContext context)
        {
            //context.Properties.AllowRefresh = true;
            //context.Properties.ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(2);

            var ticks = context.Options.SystemClock.UtcNow.AddHours(10).UtcTicks;
            context.Properties.Dictionary.Add("absolute", ticks.ToString());
        }

        private Task OnMyCustomValidateIdentity(CookieValidateIdentityContext context)
        {
            bool reject = true;
            string value;
            if (context.Properties.Dictionary.TryGetValue("absolute", out value))
            {
                long ticks;
                if (Int64.TryParse(value, out ticks))
                {
                    reject = context.Options.SystemClock.UtcNow.UtcTicks > ticks;
                }
            }
            if (reject)
            {
                context.RejectIdentity();
                // optionally clear cookie
                //ctx.OwinContext.Authentication.SignOut(ctx.Options.AuthenticationType);
            }

            return Task.FromResult(0);
        }


        private Task OnRedirectToIdentityProvider(RedirectToIdentityProviderNotification
Microsoft Entra ID
Microsoft Entra ID
A Microsoft Entra identity service that provides identity management and access control capabilities. Replaces Azure Active Directory.
19,576 questions
{count} votes

7 answers

Sort by: Newest
  1. shaobin Wang 0 Reputation points
    2023-04-27T03:24:50.2033333+00:00

    Hi Guys, i also have same requirement like Asp.net web forms with AD connection validation please share the sample code at ben_wang@sz.ctil.com if u have, thanks.


  2. Anastácio Gomes 0 Reputation points
    2023-04-11T12:36:03.2766667+00:00

    hi there! same problems here! any code available?

    0 comments No comments

  3. Rajan Kumar 0 Reputation points
    2023-02-10T11:36:44.44+00:00

    hi @Ramu Choudhary

    I will provide you this saturday.

    please wait


  4. Ramu Choudhary 1 Reputation point
    2022-09-02T16:18:15.487+00:00

    Hi @Tushar Kamble

    Have you got any sample impliement Azure AD SSO with ASP.NET WEB Forms .

    If yes please share with me i have also same requirement.

    Thanks

    0 comments No comments

  5. Tushar Kamble 1 Reputation point
    2022-07-28T17:37:59.383+00:00

    Hi @Padmasekhar Pottepalem ,

    There is a requirement in my project to impliement Azure AD SSO.

    My project is a ASP.NET WEB Forms Applicaiton, can you please share some links or sample code for this.

    I am trying but got stuck, On login page I am getting 302 found error but in the response I can see the id_token received from azure.

    It will be very helpful if you share some sample code or any inks where I can get code for SSO in ASP.NET WEB Forms Applicaiton.

    Also in my application on login page there is local login and sing with microsoft login functionality.

    Thanks in advance.

    0 comments No comments