Asp.Net Webforms AuthO

Hi, we have a legacy ASP.Net app that is implemented using webforms (.Net 4.7.2) and we are trying to implement AuthO using ASP.Net OWIN.

The initial login into AuthO works okay and navigates back to correct callback URL and states in the logs that the user has authenticated within OAuth. However, in the code behind file the http context user is not authenticated and does not have any claims. Does anybody have any ideas on what’s causing this?

Hi @ben.trebble,

Welcome to the Auth0 Community!

It may be helpful to provide some additional information, like code snippets, errors, or any other contextual information that can help troubleshoot the issue.

Thanks,
Dan

Hi Dan,

As requested, I’ve included some snippets of code below that are used to authenticate with Auth0.

Start Up Class

using Microsoft.Owin;
using Owin;
using Hangfire;
using MSharp.Framework;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
using Microsoft.IdentityModel.Tokens;
using Microsoft.Owin.Host.SystemWeb;
using Microsoft.Owin.Security.OpenIdConnect;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security;
using System.Configuration;
using System.Threading.Tasks;
using System;
using System.Security.Claims;

[assembly: OwinStartup(typeof(Website.OwinStartup))]
namespace Website
{

    public class OwinStartup
    {

        private readonly static string RequestScheme = ConfigurationManager.AppSettings["auth0:RequestScheme"];

        public void Configuration(IAppBuilder app)
        {
            if (!Config.Get<bool>("IsHangfireDisabled"))
            {
                app.UseHangfireDashboard();
            }

            string redirectUri = ConfigurationManager.AppSettings["auth0:RedirectUri"];
            string postLogoutRedirectUri = ConfigurationManager.AppSettings["auth0:LogoutRedirectUri"];

            string domain = ConfigurationManager.AppSettings["auth0:Domain"];
            string clientId = ConfigurationManager.AppSettings["auth0:ClientId"];

            app.Use((context, next) =>
            {
                if (context.Request.Headers["x-forwarded-proto"] == "https")
                {
                    context.Request.Scheme = "https";
                }
                return next();
            });

            // Set Cookies as default authentication type
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
            app.UseCookieAuthentication(
                new CookieAuthenticationOptions
                {
                    AuthenticationType = CookieAuthenticationDefaults.AuthenticationType,
                    LoginPath = new PathString("/Account/Login"),

                    CookieSameSite = SameSiteMode.Lax,

                    // More information on why the CookieManager needs to be set can be found here: 
                    // https://github.com/aspnet/AspNetKatana/wiki/System.Web-response-cookie-integration-issues
                    CookieManager = new SystemWebCookieManager()
                }
            );
            app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
            {
                AuthenticationType = "Auth0",
                Authority = $"https://{domain}",
                ClientId = clientId,
                RedirectUri = redirectUri,
                PostLogoutRedirectUri = postLogoutRedirectUri,
                ResponseType = OpenIdConnectResponseType.CodeIdToken,
                Scope = "openid profile email",
                TokenValidationParameters = new TokenValidationParameters
                {
                    NameClaimType = "name"
                },
                // More information on why the CookieManager needs to be set can be found here: 
                // https://docs.microsoft.com/en-us/aspnet/samesite/owin-samesite
                CookieManager = new SystemWebCookieManager(),
                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    RedirectToIdentityProvider = notification =>
                    {
                        if (notification.ProtocolMessage.RequestType == OpenIdConnectRequestType.Logout)
                        {
                            var logoutUri = $"https://{domain}/v2/logout?client_id={clientId}";

                            var postLogoutUri = this.DetermineRedirectUri(notification.Request);

                            if (!string.IsNullOrEmpty(postLogoutUri))
                            {
                                if (postLogoutUri.StartsWith("/"))
                                {
                                    // transform to absolute
                                    var request = notification.Request;
                                    postLogoutUri = request.Scheme + "://" + request.Host + request.PathBase + postLogoutUri;
                                }

                                logoutUri += $"&returnTo={Uri.EscapeDataString(postLogoutUri)}";
                            }

                            notification.Response.Redirect(logoutUri);
                            notification.HandleResponse();
                        }
                        else if (notification.ProtocolMessage.RequestType == OpenIdConnectRequestType.Authentication)
                        {
                            var authUri =
                                $"{this.DetermineRedirectUri(notification.Request)}/CompanySelect.aspx";

                            notification.ProtocolMessage.RedirectUri = authUri;
                        }

                        return Task.FromResult(0);
                    },
                }
            });
        }

        private string DetermineRedirectUri(IOwinRequest request)
        {
            return RequestScheme + request.Host + request.PathBase;
        }

    }
}

Method to start the authO authentication

    protected void btnSSOLogIn_Click(object sender, EventArgs e)
    {
        if (!Request.IsAuthenticated)
        {
            this.Response.SuppressFormsAuthenticationRedirect = true;
            this.Context.GetOwinContext().Authentication.Challenge(
                new AuthenticationProperties
                {
                    RedirectUri = "/CompanySelect.aspx"
                },
                "Auth0"
            );
        }
    }

This is the code from the Company Select page that is called from the callback URL of AuthO after the user has successfully logged in. However, for some reason the HttpContext.Current.User.Identity is not authenticated and does not contain any claims.

    [Authorize]
    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);
        PopulateList();
        DataBind();

        string emailAddress = null;

        var claimsIdentity = HttpContext.Current.User.Identity as ClaimsIdentity;

        if (claimsIdentity.IsAuthenticated || this.Request.IsAuthenticated)
        {
            emailAddress = claimsIdentity?.FindFirst(c => c.Type == ClaimTypes.Email)
                                         ?.Value;
        }
        else
        {
            HttpContext.Current.Response.Redirect("~/Pages/UserAccount/Login.aspx", true);
        }
    }
1 Like

Hi @ben.trebble,

It looks like the claimsIdentity is treated a bit differently in our quickstart example.

I don’t have much more information than that, but can reach out to a colleague if this doesn’t solve it. Are you seeing any errors?

Hi @dan.woda,

I’ve tried changing it to the page User as the above example, but I’m still getting back a generic user that is not authenticated and has no claims. I’ve included a screenshot below of the user contents:

Hello, I have not tested this, but does solution of this SO question help?
Specificially the remark about AuthenticationMode = AuthenticationMode.Active in the CookieAuthenticationOptions being important (and preventing headbanging a wall).