Пример #1
0
        protected override async Task <AuthenticationTicket> AuthenticateCoreAsync()
        {
            AuthenticationProperties properties = null;

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

                var query  = Request.Query;
                var 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));
                }

                var requestPrefix = Request.Scheme + "://" + this.GetHostName();
                var redirectUri   = requestPrefix + Request.PathBase + Options.CallbackPath;

                // Build up the body for the token request
                var body = 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),
                    new KeyValuePair <string, string>("client_secret", Options.ClientSecret)
                };

                if (Options.RequirePkce)
                {
                    if (properties.Dictionary.ContainsKey(PkceCodeVerifierKey))
                    {
                        string codeVerifier = properties.Dictionary[PkceCodeVerifierKey];
                        body.Add(new KeyValuePair <string, string>("code_verifier", codeVerifier));
                    }
                    else
                    {
                        return(new AuthenticationTicket(null, properties));
                    }
                }

                // Request the token
                var tokenResponse = await _httpClient.PostAsync(Options.Endpoints.TokenEndpoint, new FormUrlEncodedContent(body));

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

                // Deserializes the token response
                dynamic response     = JsonConvert.DeserializeObject <dynamic>(text);
                string  accessToken  = (string)response.access_token;
                string  tokenType    = (string)response.token_type;
                string  expires      = (string)response.expires_in;
                string  refreshToken = (string)response.refresh_token;

                // Get the Geocaching user
                var userInfoEndpoint = Options.Endpoints.UserInfoEndpoint + "/me?fields=" + string.Join("%2C", Options.ProfileFields.Distinct().ToArray());

                var userRequest = new HttpRequestMessage(HttpMethod.Get, userInfoEndpoint);
                userRequest.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);

                var graphResponse = await _httpClient.SendAsync(userRequest, Request.CallCancelled);

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

                var user = JObject.Parse(text);

                var context = new GeocachingAuthenticatedContext(Context, user, accessToken, refreshToken, expires)
                {
                    Identity = new ClaimsIdentity(
                        Options.AuthenticationType,
                        ClaimsIdentity.DefaultNameClaimType,
                        ClaimsIdentity.DefaultRoleClaimType)
                };

                if (!string.IsNullOrEmpty(context.ReferenceCode))
                {
                    context.Identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, context.ReferenceCode, XmlSchemaString, Options.AuthenticationType));
                }
                if (!string.IsNullOrEmpty(context.Username))
                {
                    context.Identity.AddClaim(new Claim(ClaimTypes.Name, context.Username, XmlSchemaString, Options.AuthenticationType));
                }
                if (!string.IsNullOrEmpty(context.RefreshToken))
                {
                    context.Identity.AddClaim(new Claim(Claims.RefreshToken, context.RefreshToken, XmlSchemaString, Options.AuthenticationType));
                }
                if (!string.IsNullOrEmpty(context.AccessToken))
                {
                    context.Identity.AddClaim(new Claim(Claims.AccessToken, context.AccessToken, XmlSchemaString, Options.AuthenticationType));
                }
                if (!string.IsNullOrEmpty(context.MembershipLevelId))
                {
                    context.Identity.AddClaim(new Claim(Claims.MembershipLevelId, context.MembershipLevelId, XmlSchemaString, Options.AuthenticationType));
                }
                if (!string.IsNullOrEmpty(context.AvatarUrl))
                {
                    context.Identity.AddClaim(new Claim(Claims.AvatarUrl, context.AvatarUrl, XmlSchemaString, Options.AuthenticationType));
                }
                if (!string.IsNullOrEmpty(context.BannerUrl))
                {
                    context.Identity.AddClaim(new Claim(Claims.BannerUrl, context.BannerUrl, XmlSchemaString, Options.AuthenticationType));
                }
                if (!string.IsNullOrEmpty(context.Url))
                {
                    context.Identity.AddClaim(new Claim(Claims.Url, context.Url, XmlSchemaString, Options.AuthenticationType));
                }
                if (!string.IsNullOrEmpty(context.FindCount))
                {
                    context.Identity.AddClaim(new Claim(Claims.FindCount, context.FindCount, XmlSchemaString, Options.AuthenticationType));
                }
                if (!string.IsNullOrEmpty(context.HideCount))
                {
                    context.Identity.AddClaim(new Claim(Claims.HideCount, context.HideCount, XmlSchemaString, Options.AuthenticationType));
                }
                if (!string.IsNullOrEmpty(context.FavoritePoints))
                {
                    context.Identity.AddClaim(new Claim(Claims.FavoritePoints, context.FavoritePoints, XmlSchemaString, Options.AuthenticationType));
                }
                if (!string.IsNullOrEmpty(context.ProfileText))
                {
                    context.Identity.AddClaim(new Claim(Claims.ProfileText, context.ProfileText, XmlSchemaString, Options.AuthenticationType));
                }
                if (!string.IsNullOrEmpty(context.HomeCoordinates))
                {
                    context.Identity.AddClaim(new Claim(Claims.HomeCoordinates, context.HomeCoordinates, XmlSchemaString, Options.AuthenticationType));
                }
                if (!string.IsNullOrEmpty(context.GeocacheLimits))
                {
                    context.Identity.AddClaim(new Claim(Claims.GeocacheLimits, context.GeocacheLimits, 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));
        }
Пример #2
0
 /// <summary>
 /// Invoked whenever Geocaching 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(GeocachingAuthenticatedContext context)
 {
     return(OnAuthenticated(context));
 }