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("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 + Request.PathBase + Options.CallbackPath;

                string tokenRequest = "grant_type=authorization_code" +
                                      "&code=" + Uri.EscapeDataString(code) +
                                      "&redirect_uri=" + Uri.EscapeDataString(redirectUri) +
                                      "&client_id=" + Uri.EscapeDataString(Options.AppId) +
                                      "&client_secret=" + Uri.EscapeDataString(Options.AppSecret);

                HttpResponseMessage tokenResponse =
                    await _httpClient.GetAsync(TokenEndpoint + "?" + tokenRequest, Request.CallCancelled);

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

                JObject token = JObject.Parse(content);

                string accessToken = token["access_token"].Value <string>();
                string expires     = token["expires_in"].Value <string>();

                // get user info
                string graphAddress = UserInfoEndpoint + "?access_token=" + Uri.EscapeDataString(accessToken);
                if (Options.SendAppSecretProof)
                {
                    graphAddress += "&appsecret_proof=" + GenerateAppSecretProof(accessToken);
                }

                HttpResponseMessage graphResponse = await _httpClient.GetAsync(graphAddress, Request.CallCancelled);

                graphResponse.EnsureSuccessStatusCode();
                content = await graphResponse.Content.ReadAsStringAsync();

                JObject user = JObject.Parse(content);

                // get permissions
                string permissionsAddress = PermissionsEndpoint + "?access_token=" + Uri.EscapeDataString(accessToken);
                if (Options.SendAppSecretProof)
                {
                    permissionsAddress += "&appsecret_proof=" + GenerateAppSecretProof(accessToken);
                }

                HttpResponseMessage permissionsResponse = await _httpClient.GetAsync(permissionsAddress, Request.CallCancelled);

                permissionsResponse.EnsureSuccessStatusCode();
                content = await permissionsResponse.Content.ReadAsStringAsync();

                JObject permissions = JObject.Parse(content);

                // parse reponses
                var context = new FacebookAuthenticatedContext(Context, user, permissions, accessToken, expires);
                context.Identity = new ClaimsIdentity(
                    Options.AuthenticationType,
                    ClaimsIdentity.DefaultNameClaimType,
                    ClaimsIdentity.DefaultRoleClaimType);
                if (!string.IsNullOrEmpty(context.Id))
                {
                    context.Identity.AddClaim(
                        new Claim(ClaimTypes.NameIdentifier, context.Id, 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.Name))
                {
                    context.Identity.AddClaim(
                        new Claim("urn:facebook:name", context.Name, XmlSchemaString, Options.AuthenticationType));

                    // Many Facebook accounts do not set the UserName field.  Fall back to the Name field instead.
                    if (string.IsNullOrEmpty(context.UserName))
                    {
                        context.Identity.AddClaim(
                            new Claim(ClaimsIdentity.DefaultNameClaimType, context.Name, XmlSchemaString, Options.AuthenticationType));
                    }
                }
                if (!string.IsNullOrEmpty(context.Link))
                {
                    context.Identity.AddClaim(
                        new Claim("urn:facebook: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("Authentication failed", ex);
                return(new AuthenticationTicket(null, properties));
            }
        }
Пример #2
0
 /// <summary>
 /// Invoked whenever Facebook 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(FacebookAuthenticatedContext context)
 {
     return(OnAuthenticated(context));
 }