protected override async Task <AuthenticationTicket> AuthenticateCoreAsync()
        {
            AuthenticationProperties properties = null;

            try
            {
                string state = null;
                string code  = null;

                IReadableStringCollection query = Request.Query;
                IList <string>            values;

                values = query.GetValues("state");
                if (values != null && values.Count == 1)
                {
                    state = values[0];
                }
                properties = Options.StateDataFormat.Unprotect(state);
                if (properties == null)
                {
                    return(null);
                }

                values = query.GetValues("error");
                if (values != null && values.Count == 1)
                {
                    return(new AuthenticationTicket(null, properties));
                }

                values = query.GetValues("code");
                if (values != null && values.Count == 1)
                {
                    code = values[0];
                }

                // OAuth2 10.12 CSRF
                if (!ValidateCorrelationId(properties, _logger))
                {
                    return(new AuthenticationTicket(null, properties));
                }

                string requestPrefix = Request.Scheme + "://" + Request.Host;
                string redirectUri   = requestPrefix + Request.PathBase + Options.CallbackPath;

                var requestJson = new JObject
                {
                    { "grant_type", "authorization_code" },
                    { "client_id", Options.ClientId },
                    { "client_secret", Options.ClientSecret },
                    { "code", code },
                    { "redirect_uri", redirectUri }
                };

                // Request the token
                var tokenResponse = await _httpClient.PostAsync(
                    TokenEndpoint, new StringContent(requestJson.ToString(), Encoding.UTF8, "application/json"));

                tokenResponse.EnsureSuccessStatusCode();
                string content = await tokenResponse.Content.ReadAsStringAsync();

                // Deserializes the token response
                var      response           = JsonConvert.DeserializeObject <JObject>(content);
                string   accessToken        = response["access_token"].Value <string>();
                string   accessTokenExpires = response["expires_in"].Value <string>();
                string   refreshToken       = response["refresh_token"].Value <string>();
                string[] scope = response["scope"]?["bearerPermissions"] != null ?
                                 response["scope"]?["bearerPermissions"].Value <string>().Split(new char[] { ',' }) :
                                 new string[0];
                string userId = response["scope"]?["user"]?.Value <string>();

                var userResponse = await _httpClient.GetAsync(String.Format(UserInfoEndpointFormat, userId, accessToken));

                var userContent = await userResponse.Content.ReadAsStringAsync();

                JObject userJson = null;
                if (userResponse.IsSuccessStatusCode)
                {
                    userJson = JObject.Parse(userContent);
                }

                var context = new BlueJeansAuthenticatedContext(Context,
                                                                accessToken, accessTokenExpires, refreshToken, scope, userId, userJson);
                context.Identity = new ClaimsIdentity(
                    Options.AuthenticationType,
                    ClaimsIdentity.DefaultNameClaimType,
                    ClaimsIdentity.DefaultRoleClaimType);

                if (!String.IsNullOrEmpty(context.UserId))
                {
                    context.Identity.AddClaim(
                        new Claim(ClaimTypes.NameIdentifier, context.UserId, XmlSchemaString, Options.AuthenticationType));
                }
                if (!String.IsNullOrEmpty(context.Username))
                {
                    context.Identity.AddClaim(
                        new Claim(ClaimsIdentity.DefaultNameClaimType, context.Username, XmlSchemaString, Options.AuthenticationType));
                }
                if (!String.IsNullOrEmpty(context.Email))
                {
                    context.Identity.AddClaim(
                        new Claim(ClaimTypes.Email, context.Email, XmlSchemaString, Options.AuthenticationType));
                }
                if (!string.IsNullOrEmpty(context.GivenName))
                {
                    context.Identity.AddClaim(
                        new Claim(ClaimTypes.GivenName, context.GivenName, XmlSchemaString, Options.AuthenticationType));
                }
                if (!string.IsNullOrEmpty(context.Surname))
                {
                    context.Identity.AddClaim(
                        new Claim(ClaimTypes.Surname, context.Surname, XmlSchemaString, Options.AuthenticationType));
                }
                context.Properties = properties;

                await Options.Provider.Authenticated(context);

                return(new AuthenticationTicket(context.Identity, context.Properties));
            }
            catch (Exception ex)
            {
                _logger.WriteError("Authentication failed", ex);
                return(new AuthenticationTicket(null, properties));
            }
        }
 /// <summary>
 /// Invoked whenever BlueJeans successfully authenticates a user
 /// </summary>
 /// <param name="context">Contains information about the login session as well as the user <see cref="System.Security.Claims.ClaimsIdentity"/>.</param>
 /// <returns>A <see cref="Task"/> representing the completed operation.</returns>
 public virtual Task Authenticated(BlueJeansAuthenticatedContext context)
 {
     return(OnAuthenticated(context));
 }