powered by simpleCommunicator - 2.0.59     © 2026 Programmizd 02
Целевая тема:
Создать новую тему:
Автор:
Закрыть
Цитировать
Форумы / ASP.NET [игнор отключен] [закрыт для гостей] / Вывод данных из соц.сети
8 сообщений из 8, страница 1 из 1
Вывод данных из соц.сети
    #38643543
Sabyrov.Talgat
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
в ASP.NET MVC(Razor) нужно вывести форму авторизации социальной сети. При успешном авторизации, в переменную присвоить значение id и другие данные пользователя в этой соц.сети. Как пример можно взять vk.com. Как это сделать?
...
Рейтинг: 0 / 0
Вывод данных из соц.сети
    #38643579
Фотография hVostt
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
...
Рейтинг: 0 / 0
Вывод данных из соц.сети
    #38643686
Andrey1306
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
hVostt,

Код: c#
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
77.
78.
79.
80.
81.
82.
83.
84.
85.
86.
87.
88.
89.
90.
91.
92.
93.
94.
95.
96.
97.
98.
99.
100.
101.
102.
103.
104.
105.
106.
107.
108.
109.
110.
111.
112.
113.
114.
115.
116.
117.
118.
119.
120.
121.
122.
123.
124.
125.
126.
127.
128.
129.
130.
131.
132.
133.
134.
135.
136.
137.
138.
139.
140.
141.
142.
143.
144.
145.
146.
147.
148.
149.
150.
151.
152.
153.
154.
155.
156.
157.
158.
159.
160.
161.
162.
163.
164.
165.
166.
167.
168.
 public class VKontakteScopedClient : IAuthenticationClient
    {
        private string appId;
        private string appSecret;

      

        private const string baseUrl = "https://oauth.vk.com/authorize?client_id=";
        private const string graphApiToken= "https://oauth.vk.com/access_token?client_id=";
        private const string graphApiMe = "https://api.vk.com/method/";

      

        public VKontakteScopedClient(string appId, string appSecret)
        {
            this.appId = appId;
            this.appSecret = appSecret;
        }

        public string ProviderName
        {
            get { return "VKontakte"; }
        }

        public void RequestAuthentication(System.Web.HttpContextBase context, Uri returnUrl)
        {
            string url = baseUrl + appId + "&redirect_uri=" + HttpUtility.UrlEncode(returnUrl.ToString()) + "&response_type=code";
            context.Response.Redirect(url);

           
        }

        public AuthenticationResult VerifyAuthentication(System.Web.HttpContextBase context)
        {
            string code = context.Request.QueryString["code"];

            string rawUrl = context.Request.Url.OriginalString;
            //From this we need to remove code portion
            rawUrl = Regex.Replace(rawUrl, "&code=[^&]*", "");

            IDictionary<string, string> userData = GetUserData(code, rawUrl);

            if (userData == null)
                return new AuthenticationResult(false, ProviderName, null, null, null);

            string id = userData["id"];
            //string username = userData["username"];
            //userData.Remove("id");
            //userData.Remove("username");

            AuthenticationResult result = new AuthenticationResult(true, ProviderName, id, userData["email"], userData);
            return result;
        }
        private static string GetHTML(string URL)
        {
            string connectionString = URL;

            try
            {
                System.Net.HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(connectionString);
                myRequest.Credentials = CredentialCache.DefaultCredentials;
                //// Get the response
                WebResponse webResponse = myRequest.GetResponse();
                Stream respStream = webResponse.GetResponseStream();
                ////
                StreamReader ioStream = new StreamReader(respStream);
                string pageContent = ioStream.ReadToEnd();
                //// Close streams
                ioStream.Close();
                respStream.Close();
                return pageContent;
            }
            catch (Exception er)
            {
                string e = er.Message;
            }
            return null;
        }

        private IDictionary<string, string> GetUserData(string accessCode, string redirectURI)
        {
            string token = GetHTML(graphApiToken + appId + "&redirect_uri=" + HttpUtility.UrlEncode(redirectURI) + "&client_secret=" + appSecret + "&code=" + accessCode);
            if (token == null || token == "")
            {
                return null;
            }

            /* fields
             * перечисленные через запятую поля анкет, 
             * необходимые для получения. Доступные значения: 
             * uid, first_name, last_name, nickname, screen_name,
             * sex, bdate (birthdate), city, country, timezone, 
             * photo, photo_medium, photo_big, has_mobile, rate, 
             * contacts, education, online, counters.
             */

            Dictionary<string, string> AccessTokenParam = JsonConvert.DeserializeObject<Dictionary<string, string>>(token);
            string data = GetHTML(string.Format("{0}getProfiles?uid={1}&access_token={2}&fields=sex,bdate,nickname,screen_name,city,photo,contacts", graphApiMe, AccessTokenParam["user_id"], AccessTokenParam["access_token"]));
            //// this dictionary must contains
            var userData = JsonConvert.DeserializeObject(data);
            VKontakteResponce vkr = JsonConvert.DeserializeObject<VKontakteResponce>(data);
            return (vkr.VKontakteUserArray.GetValue(0) as VKontakteUser).VKontakteUserData;
        }
       
    }

     [JsonObject]
    public class VKontakteResponce
    {
         public VKontakteResponce ()
         {
             VKontakteUserArray = new VKontakteUser [1];
         }

         [JsonProperty("response")]
         public VKontakteUser[] VKontakteUserArray
         {
             get;
             set;
         }
    }


   
    [JsonObject]
    public class VKontakteUser : Dictionary<string,string>
    {
        
        [JsonProperty("uid")]
        public int uid {get; set;}
        [JsonProperty("first_name")]
        public string first_name {get;set;}
        [JsonProperty("last_name")]
        public string last_name {get;set;}
        [JsonProperty("sex")]
        public string sex { get; set; }
        [JsonProperty("bdate")]
        public string bdate { get; set; }
        [JsonProperty("nickname")]
        public string nickname { get; set; }
        [JsonProperty("screen_name")]
        public string screen_name { get; set; }
        [JsonProperty("city")]
        public string city { get; set; }
        [JsonProperty("photo")]
        public string photo { get; set; }
        [JsonProperty("contacts")]
        public string contacts { get; set; }

        public IDictionary<string, string> VKontakteUserData
        {

         

            get
            {
                Dictionary<string, string> dict = new Dictionary<string, string>();

                dict.Add(SSOUserPropertiesEnum.id.ToString(), uid.ToString());
                dict.Add(SSOUserPropertiesEnum.first_name.ToString(),first_name);
                dict.Add(SSOUserPropertiesEnum.last_name.ToString(), last_name);
                dict.Add(SSOUserPropertiesEnum.gender.ToString(), sex);
                dict.Add(SSOUserPropertiesEnum.birthday.ToString(), bdate);
                dict.Add(SSOUserPropertiesEnum.email.ToString(), contacts);
                return dict;
            }
        }
    }
...
Рейтинг: 0 / 0
Вывод данных из соц.сети
    #38643687
Andrey1306
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
OAuthWebSecurity.RegisterClient(new VKontakteScopedClient("Код", "Пароль"), "VKontakte", null);
...
Рейтинг: 0 / 0
Вывод данных из соц.сети
    #38646228
Sabyrov.Talgat
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Andrey1306,
SSOUserPropertiesEnum - здесь выдает ошибку.
The name 'SSOUserPropertiesEnum' does not exist in the current context
Поискал в классе dictionary, там не нашел. Может есть другой вариант.
...
Рейтинг: 0 / 0
Вывод данных из соц.сети
    #38647680
Andrey1306
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Sabyrov.TalgatAndrey1306,
SSOUserPropertiesEnum - здесь выдает ошибку.
The name 'SSOUserPropertiesEnum' does not exist in the current context
Поискал в классе dictionary, там не нашел. Может есть другой вариант.

ну так или уберите , или

public enum SSOUserPropertiesEnum
{
id,
birthday,
website,
username,
first_name,
middle_name,
last_name,
location,
name,
email,
gender,
link
}
...
Рейтинг: 0 / 0
Вывод данных из соц.сети
    #38647826
Andrey1306
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Sabyrov.Talgat,

ну и во избежание дальнейших вопросов АссountControler



Код: c#
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
  [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult ExternalLogin(string provider, string returnUrl)
        {
            return new ExternalLoginResult(provider, Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl }));
        }

        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult ExternalRegistry(string provider, string returnUrl)
        {
            return new ExternalLoginResult(provider, Url.Action("ExternalRegistryCallback", new { ReturnUrl = returnUrl }));
        }

        [AllowAnonymous]
        [HttpGet]
        public ActionResult ExternalRegistryCallback(string returnUrl)
        {
            AuthenticationResult result = OAuthWebSecurity.VerifyAuthentication(Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl }));
            if (!result.IsSuccessful)
            {
                return RedirectToAction("ExternalLoginFailure", new { error = result.Error.Message });
            }
            else
            {
                RegisterModel rm = new RegisterModel();
                rm.FirstName = ExternalUserData(result, "first_name");
                rm.SecondName = ExternalUserData(result, "middle_name");
                rm.Surname = ExternalUserData(result, "last_name");
                rm.UserName = ExternalUserData(result, "email");
                rm.Provider = result.Provider;
                rm.ProviderUserId = result.ProviderUserId;
                //UrlPhoto = ExternalUserData(result, "picture"),
                return View("Register", rm);
            }
        }




...
Рейтинг: 0 / 0
Вывод данных из соц.сети
    #38651601
Sabyrov.Talgat
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Спасибо большое))
...
Рейтинг: 0 / 0
8 сообщений из 8, страница 1 из 1
Форумы / ASP.NET [игнор отключен] [закрыт для гостей] / Вывод данных из соц.сети
Найденые пользователи ...
Разблокировать пользователей ...
Читали форум (0):
Пользователи онлайн (0):
x
x
Закрыть


Просмотр
0 / 0
Close
Debug Console [Select Text]