Search code examples
asp.nethttphandlerauth0asp.net-authentication

auth0 authentication issue: HttpContext.Current is null. This code path is only valid when in the execution context of ASP.NET


I am using auth0 for authentication, roles and permission in my application. I am following below tutorial to implement auth0 in my application,

https://auth0.com/docs/quickstart/webapp/aspnet

It created login screen for me, After giving email-id and password it navigates to LoginHandler.ashx. and it shows below error page.

enter image description here

I am getting token, userid and other information but how to resolve this error in handler?


Solution

  • Here is my solution, If anyone facing same problem,

    public class LoginCallback : IHttpHandler, IRequiresSessionState
    {
        public void ProcessRequest(HttpContext context)
                {
                    AuthenticationApiClient client = new AuthenticationApiClient(
                        new Uri(string.Format("https://{0}", ConfigurationManager.AppSettings["auth0:Domain"])));
    
                    var token = client.ExchangeCodeForAccessTokenAsync(new ExchangeCodeRequest
                    {
                        ClientId = ConfigurationManager.AppSettings["auth0:ClientId"],
                        ClientSecret = ConfigurationManager.AppSettings["auth0:ClientSecret"],
                        AuthorizationCode = context.Request.QueryString["code"],
                        RedirectUri = context.Request.Url.ToString()
                    });
    
                    var profile = client.GetUserInfoAsync(token.Result.AccessToken);
    
                    var user = new List<KeyValuePair<string, object>>
                    {
                        new KeyValuePair<string, object>("name", profile.Result.UserName ?? profile.Result.Email),
                        new KeyValuePair<string, object>("email", profile.Result.Email),
                        new KeyValuePair<string, object>("family_name", profile.Result.LastName),
                        new KeyValuePair<string, object>("given_name", profile.Result.FirstName),
                        new KeyValuePair<string, object>("nickname", profile.Result.NickName),
                        new KeyValuePair<string, object>("picture", profile.Result.Picture),
                        new KeyValuePair<string, object>("user_id", profile.Result.UserId),
                        new KeyValuePair<string, object>("id_token", token.Result.IdToken),
                        new KeyValuePair<string, object>("access_token", token.Result.AccessToken),
                        new KeyValuePair<string, object>("refresh_token", token.Result.RefreshToken),
                        new KeyValuePair<string, object>("connection", profile.Result.Identities.First().Connection),
                        new KeyValuePair<string, object>("provider", profile.Result.Identities.First().Provider)
                    };
    
                    // NOTE: Uncomment the following code in order to include claims from associated identities
                    profile.Result.Identities.ToList().ForEach(i =>
                    {
                        user.Add(new KeyValuePair<string, object>(i.Connection + ".access_token", i.AccessToken));
                        user.Add(new KeyValuePair<string, object>(i.Connection + ".provider", i.Provider));
                        user.Add(new KeyValuePair<string, object>(i.Connection + ".user_id", i.UserId));
                    });
    
                    // NOTE: uncomment this if you send roles
                     user.Add(new KeyValuePair<string, object>(ClaimTypes.Role, profile.Result.ProviderAttributes["roles"]));
    
                    // NOTE: this will set a cookie with all the user claims that will be converted 
                    //       to a ClaimsPrincipal for each request using the SessionAuthenticationModule HttpModule. 
                    //       You can choose your own mechanism to keep the user authenticated (FormsAuthentication, Session, etc.)
                    FederatedAuthentication.SessionAuthenticationModule.CreateSessionCookie(user);
    
                    if (context.Request.QueryString["state"] != null && context.Request.QueryString["state"].StartsWith("ru="))
                    {
                        var state = HttpUtility.ParseQueryString(context.Request.QueryString["state"]);
                        context.Response.Redirect(state["ru"], true);
                    }
    
    
                    context.Response.Redirect("/");
    
                }
    }