2016-12-23 12 views
1

Я использую auth0 для аутентификации, ролей и разрешений в своем приложении. Я следую ниже учебник для реализации auth0 в моем приложении,Аутентификация auth0: HttpContext.Current имеет значение NULL. Этот путь кода действителен только в контексте выполнения ASP.NET

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

Он создал экран входа в систему для меня, Дав электронной почты идентификатор и пароль, если он переходит к LoginHandler.ashx. и он показывает ниже страницу с ошибкой.

enter image description here

Я получаю токенов, идентификатор пользователя и другую информацию, но как решить эту ошибку в обработчике?

+0

Можете ли вы предоставить более подробную информацию о том, как вы размещаете этот код (IIS, IIS Express)? Какую версию платформы .NET вы нацеливаете? –

+0

Я использую Visual Studio 2015, Framework 4.6. И я работаю над удаленной системой. –

+0

Для хостинга я использую IIS Express –

ответ

2

Вот мое решение, если кто-то сталкивается с той же проблемой,

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("/"); 

      } 
}