public virtual Task Authenticated(StackExchangeAuthenticatedContext context)
 {
     return(OnAuthenticated(context));
 }
 public virtual Task Authenticated(StackExchangeAuthenticatedContext context)
 {
     return OnAuthenticated(context);
 }
        protected override async Task <AuthenticationTicket> AuthenticateCoreAsync()
        {
            AuthenticationProperties properties = null;

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

                IReadableStringCollection query  = Request.Query;
                IList <string>            values = query.GetValues("code");
                if (values != null && values.Count == 1)
                {
                    code = values[0];
                }
                values = query.GetValues("state");
                if (values != null && values.Count == 1)
                {
                    state = values[0];
                }

                properties = Options.StateDataFormat.Unprotect(state);
                if (properties == null)
                {
                    return(null);
                }

                // 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;

                string tokenRequest = "client_id=" + Uri.EscapeDataString(Options.ClientId) +
                                      "&client_secret=" + Uri.EscapeDataString(Options.ClientSecret) +
                                      "&code=" + Uri.EscapeDataString(code) +
                                      "&redirect_uri=" + Uri.EscapeDataString(redirectUri);

                HttpRequestMessage  _httpRequest  = new HttpRequestMessage();
                HttpResponseMessage tokenResponse = await _httpClient.PostAsync(TokenEndpoint + "?" + tokenRequest, _httpRequest.Content, Request.CallCancelled);

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

                IFormCollection form = WebHelpers.ParseForm(text);

                string accessToken = form["access_token"];
                string expires     = form["expires"];

                HttpResponseMessage graphResponse = await _httpClient.GetAsync(
                    ApiEndpoint + "?access_token=" + Uri.EscapeDataString(accessToken) +
                    "&site=" + Uri.EscapeDataString(Options.Site) +
                    "&key=" + Uri.EscapeDataString(Options.Key), Request.CallCancelled);

                graphResponse.EnsureSuccessStatusCode();


                Stream rawStream = await graphResponse.Content.ReadAsStreamAsync();

                using (GZipStream gzipStream = new GZipStream(rawStream, CompressionMode.Decompress))
                    using (StreamReader streamReader = new StreamReader(gzipStream))
                    {
                        text = await streamReader.ReadToEndAsync();
                    }

                JObject info      = JObject.Parse(text);
                JToken  items     = info["items"];
                JToken  userToken = items.First;
                JObject user      = userToken as JObject;

                var context = new StackExchangeAuthenticatedContext(Context, user, accessToken, expires);
                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.DisplayName))
                {
                    context.Identity.AddClaim(new Claim(ClaimsIdentity.DefaultNameClaimType, context.DisplayName, XmlSchemaString, Options.AuthenticationType));
                }
                if (!string.IsNullOrEmpty(context.Email))
                {
                    context.Identity.AddClaim(new Claim(ClaimTypes.Email, context.Email, XmlSchemaString, Options.AuthenticationType));
                }
                if (!string.IsNullOrEmpty(context.AccountId))
                {
                    context.Identity.AddClaim(new Claim("urn:stackexchange:accountId", context.AccountId, XmlSchemaString, Options.AuthenticationType));
                }
                if (!string.IsNullOrEmpty(context.Link))
                {
                    context.Identity.AddClaim(new Claim("urn:stackexchange:link", context.Link, XmlSchemaString, Options.AuthenticationType));
                }
                context.Properties = properties;

                await Options.Provider.Authenticated(context);

                return(new AuthenticationTicket(context.Identity, context.Properties));
            }
            catch (Exception ex)
            {
                _logger.WriteError(ex.Message);
            }
            return(new AuthenticationTicket(null, properties));
        }