本博主要介绍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

/// <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();
/// <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;
}
/// <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, , 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>
///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;
}
/// <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;
}
/// <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;
}

http request 辅助方法

 /// <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, , 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[], values[]);
} return parameters;
}

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

c#实现microsoft账号登入授权(OAuth 2.0)并获取个人信息的更多相关文章

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

    c#实现Google账号登入授权(OAuth 2.0)并获取个人信息   此博主要介绍通过google 账号(gmail)实现登入,授权方式OAuth2.0,下面我们开始介绍. 1.去google官网 ...

  2. 用户授权 OAuth 2.0

    什么是OAuth OAuth是一个关于授权(Authorization)的开放网络标准,目前的版本是2.0版.OAuth适用于各种各样的包括提供用户身份验证机制的应用程序,注意是Authorizati ...

  3. 夺命雷公狗---微信开发51----网页授权(oauth2.0)获取用户基本信息接口(1)

    如果用户在微信客户端访问第三方网页,公众号可以通过微信网页授权机制,来获取用户基本信息,从而实现业务逻辑. 一般我们用来“数据采集”,“市场调查”,“投票”,只要授权了第三方网页,微信用户无需注册就可 ...

  4. 夺命雷公狗---微信开发53----网页授权(oauth2.0)获取用户基本信息接口(3)实现世界留言版

    前面两节课我们讲的是base型的授权了,那么现在我们开始Userinfo型授权, 先来看下我们的原理图 我们这节课来做一个 世界留言版 系统 1..首先我还是在微信测试平台那里设置好回调页面的域名 2 ...

  5. [微信开发] - weixin4j获取网页授权后的code进而获取用户信息

    weixin4j封装好的SnsComponent组件中的方法可以执行该步骤 WeixinUserInfoController : package com.baigehuidi.demo.control ...

  6. 夺命雷公狗---微信开发52----网页授权(oauth2.0)获取用户基本信息接口(2)

    我们在上一节课已经发送code给第三方了,那么这就要获取code去换取到用户的openid. 第一步:编写create_baseurl.php(上一节课程已经写完了) 第二步:编写vote1.php( ...

  7. QQ登入(6)腾讯微博-获取微博用户信息,发送微博

    1.1获取weibo用户信息 //先登入授权,可以参考QQ登入(1) Weibo mWeibo = new Weibo(this, mQQAuth.getQQToken()); mWeibo.getW ...

  8. QQ登入(5)获取空间相册,新建相册,上传图片到空间相册

    ///////////////////////////////////////////////////////////////////// 获取相册列表:必须先授权登入 1.1.  String mA ...

  9. discuz之同步登入

    前言   首先感谢dozer学长吧UCenter翻译成C# 博客地址----------->http://www.dozer.cc/   其次感谢群友快乐々止境同学的热心指导,虽然萍水相逢但让我 ...

随机推荐

  1. c语言获取符号位整数和浮点

    1. 为什么你应该得到的签位 非常多的时间,我们需要推断的数目值正和负,做了相应的逻辑处理.完成这一要求条件推断语句可以很好. 有时会出现以下情况, if (x > 0) { x = x - 1 ...

  2. sql server中的索引详情

    什么是索引 拿汉语字典的目录页(索引)打比方:正如汉语字典中的汉字按页存放一样,SQL Server中的数据记录也是按页存放的,每页容量一般为4K .为了加快查找的速度,汉语字(词)典一般都有按拼音. ...

  3. iOS10收集IDFA,植入第三方广告[终结]--ADMob

    [PS: 前段时间,公司做ASO推广,需要在应用中收集IDFA值,跟广告平台做交互!于是有了这个需求--] 1.首先,考虑了一下情况(自己懒 -_-#),就直接在首页上写了一个Banner,循环加载广 ...

  4. 【高德地图API】从零开始学高德JS API(一)地图展现——仙剑地图,麻点图,街景,室内图

    原文:[高德地图API]从零开始学高德JS API(一)地图展现——仙剑地图,麻点图,街景,室内图 摘要:关于地图的显示,我想大家最关心的就是麻点图,自定义底图的解决方案了吧.在过去,marker大于 ...

  5. [转载]CSS元素的定位position

    CSS元素的定位position 属性position   值 描述 absolute                             生成绝对定位的元素,相对于 static 定位以外的第一 ...

  6. CSS3+HTML5特效7 - 特殊的 Loading 效果

    效果如下     实现原理: 利用CSS3的@keyframes规则创建动画效果: 使用CSS3的animation效果完成滚动切换. 代码说明: 样式表中@-webkit-keyframes及@ke ...

  7. foj 2082 树链剖分 第2天

    擦,没啥好说的,这个模板至少得打10遍..纪念自己成功的打错了.. #include <iostream> #include <cstdio> #include <cst ...

  8. sql级联删除

    原文:sql级联删除 功能:在删除主表时,自动删除副表(外键约束)相应内容 删除包含主键值的行的操作,该值由其它表的现有行中的外键列引用.在级联删除中,还删除其外键值引用删除的主键值的所有行. 如: ...

  9. 3D人脸识别预处理,3D face recognition preprocess

    本文由兔崩溃公布http://blog.csdn.net/smartempire/article/details/31373817. 转载请注明出处.howdeshui#163.com 近期在做三维人 ...

  10. javascirpt怎样模仿块级作用域(js高程笔记)

    因为javascript没有块级作用域的概念,所以在块语句中定义的变量,实际上是在包括函数中而非语句中创建的. 如: function outputNumbers(count){ for(var i= ...