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

            try
            {
                string code = "";

                IReadableStringCollection query  = Request.Query;
                IList <string>            values = query.GetValues("code");

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

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

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

                string requestPrefix = Request.Scheme + Uri.SchemeDelimiter + Request.Host;
                string redirectUri   = requestPrefix + Request.PathBase + Options.CallbackPath;

                //http://api.odnoklassniki.ru/oauth/token.do
                string tokenRequest = TokenEndpoint + "?grant_type=authorization_code&client_id=" +
                                      Uri.EscapeDataString(Options.ClientId) +
                                      "&client_secret=" + Uri.EscapeDataString(Options.ClientSecret) +
                                      "&code=" + Uri.EscapeDataString(code) +
                                      "&redirect_uri=" + Uri.EscapeDataString(redirectUri);

                // USE only POST for odnoklassniki.api
                HttpResponseMessage tokenResponse =
                    await _httpClient.PostAsync(tokenRequest, new HttpRequestMessage().Content, Request.CallCancelled);

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

                //IFormCollection form = WebHelpers.ParseForm(text);
                var    JsonResponse = JsonConvert.DeserializeObject <dynamic>(text);
                string accessToken  = JsonResponse["access_token"];

                //Set the expiration time 60 days (5183999 seconds)
                const string expires = "5183999";

                // Signing.
                // Call API methods using access_token instead of session_key parameter
                // Calculate every request signature parameter sig using a little bit different way described in
                // http://dev.odnoklassniki.ru/wiki/display/ok/Authentication+and+Authorization
                // sig = md5( request_params_composed_string+ md5(access_token + application_secret_key)  )
                // Don't include access_token into request_params_composed_string
                var args = new Dictionary <string, string>
                {
                    { "application_key", Options.ClientPublic },
                    { "method", "users.getCurrentUser" }
                };
                string signature =
                    string.Concat(
                        args.OrderBy(x => x.Key).Select(x => string.Format("{0}={1}", x.Key, x.Value)).ToList());
                signature = (signature + (accessToken + Options.ClientSecret).GetMd5Hash()).GetMd5Hash();
                args.Add("access_token", accessToken);
                args.Add("sig", signature);

                string userInfoLink = UserInfoServiceEndpoint + "?" +
                                      string.Join("&", args.Select(x => x.Key + "=" + x.Value));

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

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

                JObject data    = JObject.Parse(text);
                var     context = new OdnoklassnikiAuthenticatedContext(Context, data, accessToken, expires)
                {
                    Identity = new ClaimsIdentity(
                        Options.AuthenticationType,
                        ClaimsIdentity.DefaultNameClaimType,
                        ClaimsIdentity.DefaultRoleClaimType)
                };

                context.Identity.AddClaim(new Claim("urn:odnoklassniki:accesstoken", context.AccessToken,
                                                    XmlSchemaString, Options.AuthenticationType));

                if (!string.IsNullOrEmpty(context.Id))
                {
                    context.Identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, context.Id, XmlSchemaString,
                                                        Options.AuthenticationType));
                }
                if (!string.IsNullOrEmpty(context.FirstName))
                {
                    context.Identity.AddClaim(new Claim(ClaimTypes.GivenName, context.FirstName,
                                                        XmlSchemaString, Options.AuthenticationType));
                }
                if (!string.IsNullOrEmpty(context.LastName))
                {
                    context.Identity.AddClaim(new Claim(ClaimTypes.Surname, context.LastName,
                                                        XmlSchemaString, Options.AuthenticationType));
                }
                if (!string.IsNullOrEmpty(context.FullName))
                {
                    context.Identity.AddClaim(new Claim(ClaimTypes.Name, context.FullName, XmlSchemaString,
                                                        Options.AuthenticationType));
                }
                if (!string.IsNullOrEmpty(context.Link))
                {
                    context.Identity.AddClaim(new Claim("urn:odnoklassniki: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));
        }
示例#3
0
 public virtual Task Authenticated(OdnoklassnikiAuthenticatedContext context)
 {
     return(OnAuthenticated(context));
 }