/// <summary>
 /// Invoked whenever BioID succesfully 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(BioIDAuthenticatedContext context)
 {
     return OnAuthenticated(context);
 }
 /// <summary>
 /// Invoked whenever BioID succesfully 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(BioIDAuthenticatedContext context)
 {
     return(OnAuthenticated(context));
 }
        protected override async Task <AuthenticationTicket> AuthenticateCoreAsync()
        {
            AuthenticationProperties properties = null;

            try
            {
                // OAuth2 4.1.2. Authorization Response
                string code  = null;
                string state = null;
                IReadableStringCollection query = Request.Query;

                IList <string> values = query.GetValues("error");
                if (values != null && values.Count >= 1)
                {
                    _logger.WriteVerbose("Remote server returned an error: " + Request.QueryString);
                }
                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));
                }

                if (code == null)
                {
                    // Null if the remote server returns an error.
                    return(new AuthenticationTicket(null, properties));
                }

                string requestPrefix          = Request.Scheme + "://" + Request.Host;
                string redirectUri            = requestPrefix + RequestPathBase + Options.CallbackPath;
                var    tokenRequestParameters = new List <KeyValuePair <string, string> >()
                {
                    new KeyValuePair <string, string>("grant_type", "authorization_code"),
                    new KeyValuePair <string, string>("code", code),
                    new KeyValuePair <string, string>("redirect_uri", redirectUri),
                    new KeyValuePair <string, string>("client_id", Options.ClientId),
                };

                HttpRequestMessage tokenRequest = new HttpRequestMessage(HttpMethod.Post, TokenEndpoint);
                tokenRequest.Content = new FormUrlEncodedContent(tokenRequestParameters);
                string secret = Convert.ToBase64String(System.Text.Encoding.GetEncoding("iso-8859-1").GetBytes(Options.ClientId + ":" + Options.ClientSecret));
                tokenRequest.Headers.Authorization = new AuthenticationHeaderValue("Basic", secret);
                HttpResponseMessage response = await _httpClient.SendAsync(tokenRequest, Request.CallCancelled);

                response.EnsureSuccessStatusCode();
                string oauthTokenResponse = await response.Content.ReadAsStringAsync();

                JObject oauth2Token  = JObject.Parse(oauthTokenResponse);
                var     accessToken  = oauth2Token["access_token"].Value <string>();
                var     refreshToken = oauth2Token.Value <string>("refresh_token");
                var     expire       = oauth2Token.Value <string>("expires_in");

                if (string.IsNullOrWhiteSpace(accessToken))
                {
                    _logger.WriteWarning("Access token was not found");
                    return(new AuthenticationTicket(null, properties));
                }

                HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, BioIDApiEndpoint);
                request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
                HttpResponseMessage graphResponse = await _httpClient.SendAsync(request, Request.CallCancelled);

                graphResponse.EnsureSuccessStatusCode();
                string accountString = await graphResponse.Content.ReadAsStringAsync();

                JObject accountInformation = JObject.Parse(accountString);

                var context = new BioIDAuthenticatedContext(Context, accountInformation, accessToken, refreshToken, expire);
                context.Identity = new ClaimsIdentity(Options.AuthenticationType, ClaimsIdentity.DefaultNameClaimType, ClaimsIdentity.DefaultRoleClaimType);
                context.Identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, context.Id, "http://www.w3.org/2001/XMLSchema#string", Options.AuthenticationType));
                context.Identity.AddClaim(new Claim(IdentityProviderClaimType, Options.AuthenticationType, "http://www.w3.org/2001/XMLSchema#string", Options.AuthenticationType));
                if (!string.IsNullOrWhiteSpace(context.Name))
                {
                    context.Identity.AddClaim(new Claim(ClaimTypes.Name, context.Name, "http://www.w3.org/2001/XMLSchema#string", Options.AuthenticationType));
                }
                if (!string.IsNullOrWhiteSpace(context.Profile))
                {
                    context.Identity.AddClaim(new Claim(BioIDClaimTypes.Profile, context.Profile, "http://www.w3.org/2001/XMLSchema#string", Options.AuthenticationType));
                }
                if (!string.IsNullOrWhiteSpace(context.Email))
                {
                    context.Identity.AddClaim(new Claim(ClaimTypes.Email, context.Email, "http://www.w3.org/2001/XMLSchema#string", Options.AuthenticationType));
                }
                if (!string.IsNullOrWhiteSpace(context.BCID))
                {
                    context.Identity.AddClaim(new Claim(BioIDClaimTypes.BCID, context.BCID, "http://www.w3.org/2001/XMLSchema#string", Options.AuthenticationType));
                }
                if (context.Roles != null)
                {
                    foreach (var role in context.Roles)
                    {
                        context.Identity.AddClaim(new Claim(ClaimTypes.Role, role, "http://www.w3.org/2001/XMLSchema#string", Options.AuthenticationType));
                    }
                }

                await Options.Provider.Authenticated(context);

                context.Properties = properties;

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