Search code examples
c#asp.netadfs2.0owin-middleware

OWIN Context is not initialized properly in ASP.NET Forms application


I'm new to OWIN and ADFS. I'm trying to authenticate users from ADFS using OWIN middleware. But when i run the app and perform login, the return HttpContext.Current.GetOwinContext() is not initialized properly.

enter image description here

owin_middleware_startup.cs

public void Configuration(IAppBuilder app)
    {
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=316888
        ConfigureAuth(app);

    }

    public void ConfigureAuth(IAppBuilder app)
    {
        app.UseCookieAuthentication(
        new CookieAuthenticationOptions
        {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, // application cookie which is generic for all the authentication types.
            LoginPath = new PathString("/login.aspx"), // redirect if not authenticated.
            AuthenticationMode = AuthenticationMode.Passive
        });

        app.UseWsFederationAuthentication(
        new WsFederationAuthenticationOptions
        {
            MetadataAddress = "https://adfs-server/federationmetadata/2007-06/federationmetadata.xml", //adfs meta data.
            Wtrealm = "https://localhost/", //reltying party
            Wreply = "/home.aspx" // redirect
        });

        app.SetDefaultSignInAsAuthenticationType(DefaultAuthenticationTypes.ApplicationCookie);
    }

login.aspx.cs

    private IAuthenticationManager AuthenticationManager
    {
        get { return HttpContext.Current.GetOwinContext().Authentication; }
    }
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void loginSSObtn_Click(object sender, EventArgs e)
    {
        IdentitySignin("administrator");
    }

    private void IdentitySignin(string userName)
    {
        //Create list of claims for Identity
        var claims = new List<Claim>();
        claims.Add(new Claim(ClaimTypes.Name, userName));

        var identity = new ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie);

        AuthenticationManager.SignIn(new AuthenticationProperties()
        {
            AllowRefresh = true,
            IsPersistent = true,
            IssuedUtc = DateTime.UtcNow,
            ExpiresUtc = DateTime.UtcNow.AddDays(2)
        }, identity);

        //Response.Redirect("/home.aspx");
    }

My goal is to redirect to the ADFS login and authenticate the user. Highly appreciate any help. Thanks.


Solution

  • Found the issue, I had missed the RUN method - app.Run() in the middle-ware. This inserts the extension to the OWIN startup. And executes it for all the requests. Fix :

    public void Configuration(IAppBuilder app)
        {
            // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=316888
            ConfigureAuth(app);
    
        }
    
        public void ConfigureAuth(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(DefaultAuthenticationTypes.ApplicationCookie);
            app.UseCookieAuthentication(
            new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, // application cookie which is generic for all the authentication types.
                LoginPath = new PathString("/login.aspx"), // redirect if not authenticated.
                AuthenticationMode = AuthenticationMode.Passive
            });
    
            app.UseWsFederationAuthentication(
            new WsFederationAuthenticationOptions
            {
                AuthenticationType = "test auth",
                MetadataAddress = "https://adfs-server/federationmetadata/2007-06/federationmetadata.xml", //adfs meta data.
                Wtrealm = "https://localhost/", //reltying party
                Wreply = "/home.aspx"//redirect
            });
    
            AuthenticateAllRequests(app, "test auth");
    
        }
    
        private static void AuthenticateAllRequests(IAppBuilder app, params string[] authenticationTypes)
        {
            app.Use((context, continuation) =>
            {
                if (context.Authentication.User != null &&
                    context.Authentication.User.Identity != null &&
                    context.Authentication.User.Identity.IsAuthenticated)
                {
                    return continuation();
                }
                else
                {
                    context.Authentication.Challenge(authenticationTypes);
                    return Task.Delay(0);
                }
            });
        }
    

    But if we want to execute the extensions/middle-wares only for some specific path then we can use app.Use() this is just one usage of it.

    feel free to correct me if i'm wrong.