c#实现microsoft账号登入授权(OAuth 2.0)并获取个人信息

时间:2022-03-14 21:08:48

本博主要介绍microsoft 账号授权(OAuth 2.0)登入并获取用户信息的过程,因为写过google账号授权登入的过程,所以这里就简单介绍一下,google授权登入参考地址:http://www.cnblogs.com/JohnnyYin/p/3447217.html

1.去microsoft官网注册账号,注册完了账号再注册一个app,地址:https://account.live.com/developers/applications/index

 2.其他都不详细介绍了,直接上code

 

c#实现microsoft账号登入授权(OAuth 2.0)并获取个人信息c#实现microsoft账号登入授权(OAuth 2.0)并获取个人信息
/// <summary>
        /// the access token
        /// </summary>
        private static string accessToken;

        /// <summary>
        /// the application id
        /// </summary>
        private static string clientID = ConfigurationSettings.AppSettings["WL_ClientID"].ToString();

        /// <summary>
        /// the application secret
        /// </summary>
        private static string clientSecret = ConfigurationSettings.AppSettings["WL_ClientSecret"].ToString();

        /// <summary>
        /// the application redirect uri path
        /// </summary>
        private static string redirectUri = ConfigurationSettings.AppSettings["WL_RedirectUri"].ToString();
View Code

 

c#实现microsoft账号登入授权(OAuth 2.0)并获取个人信息c#实现microsoft账号登入授权(OAuth 2.0)并获取个人信息
/// <summary>
        ///Get the login with microsoft url
        /// </summary>
        /// <returns></returns>
        /// <author>Johnny</author>
        /// <date>2013/11/15, 16:37:08</date>
        /// <returns>return a twitter login url</returns>
        public string GetLoginUrl()
        {
            string loginUrl = null;
            try
            {
                loginUrl = string.Format("https://login.live.com/oauth20_authorize.srf?" +
                        "client_id={0}&scope={1}&response_type=code&redirect_uri={2}",
                        HttpUtility.UrlEncode(clientID),
                        HttpUtility.UrlEncode("wl.basic,wl.emails"),
                        HttpUtility.UrlEncode(redirectUri)
                        );
            }
            catch (Exception)
            {

                throw;
            }
            return loginUrl;
        }
View Code
c#实现microsoft账号登入授权(OAuth 2.0)并获取个人信息c#实现microsoft账号登入授权(OAuth 2.0)并获取个人信息
/// <summary>
        ///general a post http request
        /// </summary>
        /// <author>Johnny</author>
        /// <date>2013/11/20, 09:21:33</date>
        public string Post(string url, string parameters)
        {
            byte[] postData = System.Text.Encoding.ASCII.GetBytes(parameters);

            System.Net.ServicePointManager.Expect100Continue = false;
            WebRequest request = WebRequest.Create(url);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = postData.Length;

            Stream requestStream = request.GetRequestStream();

            requestStream.Write(postData, 0, postData.Length);
            requestStream.Close();

            WebResponse response = request.GetResponse();
            Stream stream = response.GetResponseStream();
            StreamReader reader = new StreamReader(stream, Encoding.UTF8);
            string content = reader.ReadToEnd();
            reader.Close();
            stream.Close();

            return content;
        }
View Code
c#实现microsoft账号登入授权(OAuth 2.0)并获取个人信息c#实现microsoft账号登入授权(OAuth 2.0)并获取个人信息
/// <summary>
        ///Get an access token
        /// </summary>
        /// <author>Johnny</author>
        /// <date>2013/11/15, 16:37:08</date>
        /// <returns>return an access token</returns>
        public string GetAccessToken()
        {
            try
            {
                if (string.IsNullOrEmpty(accessToken))
                {
                    string code = HttpContext.Current.Request.Params["code"];
                    if (code != null)
                    {
                        string tokenUrl = string.Format("https://login.live.com/oauth20_token.srf");
                        var post = string.Format("client_id={0}&redirect_uri={1}&client_secret={2}&code={3}&grant_type=authorization_code",
                                                    HttpUtility.UrlEncode(clientID),
                                                    HttpUtility.UrlEncode(redirectUri),
                                                    clientSecret,
                                                    code);
                        string result = this.Post(tokenUrl, post);
                        accessToken = JsonConvert.DeserializeAnonymousType(result, new { access_token = "" }).access_token;
                    }
                }
            }
            catch (Exception)
            {

                throw;
            }
            return accessToken;
        }
View Code
c#实现microsoft账号登入授权(OAuth 2.0)并获取个人信息c#实现microsoft账号登入授权(OAuth 2.0)并获取个人信息
/// <summary>
        ///windows live user profile
        /// </summary>
        /// <author>Johnny</author>
        /// <date>2013/11/18, 16:05:51</date>
        private class UserProfile
        {
            public string id { get; set; }
            public emails emails { get; set; }
            public string name { get; set; }
            public string first_name { get; set; }
            public string last_name { get; set; }
            public string link { get; set; }
            public string gender { get; set; }
            public string updated_time { get; set; }
            public string locale { get; set; }
            public string timezone { get; set; }
        }

        private class emails
        {
            public string preferred { get; set; }
            public string account { get; set; }
            public string personal { get; set; }
            public string business { get; set; }
        }

/// <summary>
        ///Get the current user information
        /// </summary>
        /// <author>Johnny</author>
        /// <returns>return an UserInfo</returns>
        /// <date>2013/11/15, 16:37:08</date>
        /// <returns>return the current user information</returns>
        public UserProfile GetUserInfo()
        {
            UserProfile userInfo = null;
            try
            {
                if (!string.IsNullOrEmpty(accessToken))
                {
                    string result = "";
                    string profileUrl = string.Format("https://apis.live.net/v5.0/me?access_token={0}", accessToken);
                    result = webHelper.Get(profileUrl, "");
                    var data = JsonConvert.DeserializeAnonymousType(result, new UserProfile());                               
                }
                else
                {
                    throw new Exception("ERROR: [GoogleProvider] the access token is null or not valid.");
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }

            return userInfo;
        }
View Code

 

c#实现microsoft账号登入授权(OAuth 2.0)并获取个人信息c#实现microsoft账号登入授权(OAuth 2.0)并获取个人信息
/// <summary>
        ///general a get http request
        /// </summary>
        /// <author>Johnny</author>
        /// <date>2013/11/20, 09:21:33</date>
        public string Get(string url, string parameters)
        {
            if (parameters != null && parameters != "")
            {
                if (url.Contains("?"))
                {
                    url += "&" + parameters;
                }
                else
                {
                    url += "?" + parameters;
                }
            }

            WebRequest request = WebRequest.Create(url);
            WebResponse response = request.GetResponse();

            Stream stream = response.GetResponseStream();
            StreamReader reader = new StreamReader(stream, Encoding.UTF8);
            string content = reader.ReadToEnd();
            reader.Close();
            stream.Close();

            return content;
        }
View Code

 

http request 辅助方法

c#实现microsoft账号登入授权(OAuth 2.0)并获取个人信息c#实现microsoft账号登入授权(OAuth 2.0)并获取个人信息
 /// <summary>
        ///general a get http request
        /// </summary>
        /// <author>Johnny</author>
        /// <date>2013/11/20, 09:21:33</date>
        public string Get(string url, Dictionary<string, string> parameters)
        {
            return Get(url, DictionaryToString(parameters));
        }

        /// <summary>
        ///general a get http request
        /// </summary>
        /// <author>Johnny</author>
        /// <date>2013/11/20, 09:21:33</date>
        public string Get(string url, string parameters)
        {
            if (parameters != null && parameters != "")
            {
                if (url.Contains("?"))
                {
                    url += "&" + parameters;
                }
                else
                {
                    url += "?" + parameters;
                }
            }

            WebRequest request = WebRequest.Create(url);
            WebResponse response = request.GetResponse();

            Stream stream = response.GetResponseStream();
            StreamReader reader = new StreamReader(stream, Encoding.UTF8);
            string content = reader.ReadToEnd();
            reader.Close();
            stream.Close();

            return content;
        }

        /// <summary>
        ///general a http request with add header type
        /// </summary>
        /// <author>Johnny</author>
        /// <date>2013/11/26, 17:12:32</date>
        public string HeaderRequest(string method, string url, string headerQuery)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = method;
                request.Headers.Add(headerQuery);
                request.Credentials = CredentialCache.DefaultCredentials;
                WebResponse response = request.GetResponse();
                Stream stream = response.GetResponseStream();
                StreamReader reader = new StreamReader(stream, Encoding.UTF8);
                string content = reader.ReadToEnd();
                reader.Close();
                stream.Close();

                return content;
            }
            catch (Exception)
            {
                
                throw;
            }
        }

        /// <summary>
        ///general a post http request
        /// </summary>
        /// <author>Johnny</author>
        /// <date>2013/11/20, 09:21:33</date>
        public string Post(string url, Dictionary<string, string> parameters)
        {
            return Post(url, DictionaryToString(parameters));
        }

        /// <summary>
        ///general a post http request
        /// </summary>
        /// <author>Johnny</author>
        /// <date>2013/11/20, 09:21:33</date>
        public string Post(string url, string parameters)
        {
            byte[] postData = System.Text.Encoding.ASCII.GetBytes(parameters);

            System.Net.ServicePointManager.Expect100Continue = false;
            WebRequest request = WebRequest.Create(url);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = postData.Length;

            Stream requestStream = request.GetRequestStream();

            requestStream.Write(postData, 0, postData.Length);
            requestStream.Close();

            WebResponse response = request.GetResponse();
            Stream stream = response.GetResponseStream();
            StreamReader reader = new StreamReader(stream, Encoding.UTF8);
            string content = reader.ReadToEnd();
            reader.Close();
            stream.Close();

            return content;
        }

        /// <summary>
        ///general the result string to dictionary
        /// </summary>
        /// <author>Johnny</author>
        /// <date>2013/11/20, 09:23:25</date>
        public string DictionaryToString(Dictionary<string, string> parameters)
        {
            string queryParameter = "";
            foreach (string key in parameters.Keys)
            {
                if (queryParameter != "") queryParameter = "&";
                queryParameter += key + "=" + parameters[key];
            }

            return queryParameter;
        }

        /// <summary>
        ///general the result dictionary to string
        /// </summary>
        /// <author>Johnny</author>
        /// <date>2013/11/20, 09:23:25</date>
        public Dictionary<string, string> StringToDictionary(string queryParameter)
        {
            Dictionary<string, string> parameters = new Dictionary<string, string>();
            foreach (string keyvalue in queryParameter.Split(new char[] { '&' }))
            {
                string[] values = keyvalue.Split(new char[] { '=' });
                parameters.Add(values[0], values[1]);
            }

            return parameters;
        }
View Code

 

 

更多microsoft api信息请参考:http://msdn.microsoft.com/zh-CN/library/live