diff options
Diffstat (limited to 'src/DotNetOpenAuth.AspNet/Clients/OAuth2')
7 files changed, 344 insertions, 395 deletions
diff --git a/src/DotNetOpenAuth.AspNet/Clients/OAuth2/FacebookClient.cs b/src/DotNetOpenAuth.AspNet/Clients/OAuth2/FacebookClient.cs index 073223d..623d595 100644 --- a/src/DotNetOpenAuth.AspNet/Clients/OAuth2/FacebookClient.cs +++ b/src/DotNetOpenAuth.AspNet/Clients/OAuth2/FacebookClient.cs @@ -1,104 +1,91 @@ -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Net; -using System.Web; -using DotNetOpenAuth.AspNet.Resources; -using DotNetOpenAuth.Messaging; +namespace DotNetOpenAuth.AspNet.Clients { + using System; + using System.Collections.Generic; + using System.Globalization; + using System.Net; + using System.Web; + using DotNetOpenAuth.AspNet.Resources; + using DotNetOpenAuth.Messaging; -namespace DotNetOpenAuth.AspNet.Clients -{ - public sealed class FacebookClient : OAuth2Client - { - private const string AuthorizationEndpoint = "https://www.facebook.com/dialog/oauth"; - private const string TokenEndpoint = "https://graph.facebook.com/oauth/access_token"; + public sealed class FacebookClient : OAuth2Client { + private const string AuthorizationEndpoint = "https://www.facebook.com/dialog/oauth"; + private const string TokenEndpoint = "https://graph.facebook.com/oauth/access_token"; - private readonly string _appId; - private readonly string _appSecret; + private readonly string _appId; + private readonly string _appSecret; - public FacebookClient(string appId, string appSecret) - : base("facebook") - { - if (String.IsNullOrEmpty(appId)) - { - throw new ArgumentException( - String.Format(CultureInfo.CurrentCulture, WebResources.Argument_Cannot_Be_Null_Or_Empty, "appId"), - "appId"); - } + public FacebookClient(string appId, string appSecret) + : base("facebook") { + if (String.IsNullOrEmpty(appId)) { + throw new ArgumentException( + String.Format(CultureInfo.CurrentCulture, WebResources.Argument_Cannot_Be_Null_Or_Empty, "appId"), + "appId"); + } - if (String.IsNullOrEmpty("appSecret")) - { - throw new ArgumentException( - String.Format(CultureInfo.CurrentCulture, WebResources.Argument_Cannot_Be_Null_Or_Empty, "appSecret"), - "appSecret"); - } + if (String.IsNullOrEmpty("appSecret")) { + throw new ArgumentException( + String.Format(CultureInfo.CurrentCulture, WebResources.Argument_Cannot_Be_Null_Or_Empty, "appSecret"), + "appSecret"); + } - _appId = appId; - _appSecret = appSecret; - } + _appId = appId; + _appSecret = appSecret; + } - protected override Uri GetServiceLoginUrl(Uri returnUrl) - { - // Note: Facebook doesn't like us to url-encode the redirect_uri value - var builder = new UriBuilder(AuthorizationEndpoint); - MessagingUtilities.AppendQueryArgs(builder, - new KeyValuePair<string, string>[] { + protected override Uri GetServiceLoginUrl(Uri returnUrl) { + // Note: Facebook doesn't like us to url-encode the redirect_uri value + var builder = new UriBuilder(AuthorizationEndpoint); + MessagingUtilities.AppendQueryArgs(builder, + new KeyValuePair<string, string>[] { new KeyValuePair<string, string>("client_id", _appId), new KeyValuePair<string, string>("redirect_uri", returnUrl.ToString()) }); - return builder.Uri; - } + return builder.Uri; + } - protected override string QueryAccessToken(Uri returnUrl, string authorizationCode) - { - // Note: Facebook doesn't like us to url-encode the redirect_uri value - var builder = new UriBuilder(TokenEndpoint); - MessagingUtilities.AppendQueryArgs(builder, - new KeyValuePair<string, string>[] { + protected override string QueryAccessToken(Uri returnUrl, string authorizationCode) { + // Note: Facebook doesn't like us to url-encode the redirect_uri value + var builder = new UriBuilder(TokenEndpoint); + MessagingUtilities.AppendQueryArgs(builder, + new KeyValuePair<string, string>[] { new KeyValuePair<string, string>("client_id", _appId), new KeyValuePair<string, string>("redirect_uri", returnUrl.ToString()), new KeyValuePair<string, string>("client_secret", _appSecret), new KeyValuePair<string, string>("code", authorizationCode) }); - using (WebClient client = new WebClient()) - { - string data = client.DownloadString(builder.Uri); - if (String.IsNullOrEmpty(data)) - { - return null; - } + using (WebClient client = new WebClient()) { + string data = client.DownloadString(builder.Uri); + if (String.IsNullOrEmpty(data)) { + return null; + } - var parsedQueryString = HttpUtility.ParseQueryString(data); - if (parsedQueryString != null) - { - return parsedQueryString["access_token"]; - } - } - return null; - } + var parsedQueryString = HttpUtility.ParseQueryString(data); + if (parsedQueryString != null) { + return parsedQueryString["access_token"]; + } + } + return null; + } - protected override IDictionary<string, string> GetUserData(string accessToken) - { - FacebookGraphData graphData; - var request = WebRequest.Create("https://graph.facebook.com/me?access_token=" + Uri.EscapeDataString(accessToken)); - using (var response = request.GetResponse()) - { - using (var responseStream = response.GetResponseStream()) - { - graphData = JsonHelper.Deserialize<FacebookGraphData>(responseStream); - } - } + protected override IDictionary<string, string> GetUserData(string accessToken) { + FacebookGraphData graphData; + var request = WebRequest.Create("https://graph.facebook.com/me?access_token=" + Uri.EscapeDataString(accessToken)); + using (var response = request.GetResponse()) { + using (var responseStream = response.GetResponseStream()) { + graphData = JsonHelper.Deserialize<FacebookGraphData>(responseStream); + } + } - // this dictionary must contains - var userData = new Dictionary<string, string>(); - userData.AddItemIfNotEmpty("id", graphData.Id); - userData.AddItemIfNotEmpty("username", graphData.Email); - userData.AddItemIfNotEmpty("name", graphData.Name); - userData.AddItemIfNotEmpty("link", graphData.Link == null ? null : graphData.Link.ToString()); - userData.AddItemIfNotEmpty("gender", graphData.Gender); - userData.AddItemIfNotEmpty("birthday", graphData.Birthday); - return userData; - } - } + // this dictionary must contains + var userData = new Dictionary<string, string>(); + userData.AddItemIfNotEmpty("id", graphData.Id); + userData.AddItemIfNotEmpty("username", graphData.Email); + userData.AddItemIfNotEmpty("name", graphData.Name); + userData.AddItemIfNotEmpty("link", graphData.Link == null ? null : graphData.Link.ToString()); + userData.AddItemIfNotEmpty("gender", graphData.Gender); + userData.AddItemIfNotEmpty("birthday", graphData.Birthday); + return userData; + } + } } diff --git a/src/DotNetOpenAuth.AspNet/Clients/OAuth2/FacebookGraphData.cs b/src/DotNetOpenAuth.AspNet/Clients/OAuth2/FacebookGraphData.cs index 0f23907..a2605bf 100644 --- a/src/DotNetOpenAuth.AspNet/Clients/OAuth2/FacebookGraphData.cs +++ b/src/DotNetOpenAuth.AspNet/Clients/OAuth2/FacebookGraphData.cs @@ -1,36 +1,34 @@ -using System; -using System.Runtime.Serialization; -using System.ComponentModel; +namespace DotNetOpenAuth.AspNet.Clients { + using System; + using System.Runtime.Serialization; + using System.ComponentModel; -namespace DotNetOpenAuth.AspNet.Clients -{ - /// <summary> - /// Contains data of a Facebook user. - /// </summary> - /// <remarks> - /// Technically, this class doesn't need to be public, but because we want to make it serializable - /// in medium trust, it has to be public. - /// </remarks> - [DataContract] - [EditorBrowsable(EditorBrowsableState.Never)] - public class FacebookGraphData - { - [DataMember(Name = "id")] - public string Id { get; set; } + /// <summary> + /// Contains data of a Facebook user. + /// </summary> + /// <remarks> + /// Technically, this class doesn't need to be public, but because we want to make it serializable + /// in medium trust, it has to be public. + /// </remarks> + [DataContract] + [EditorBrowsable(EditorBrowsableState.Never)] + public class FacebookGraphData { + [DataMember(Name = "id")] + public string Id { get; set; } - [DataMember(Name = "email")] - public string Email { get; set; } + [DataMember(Name = "email")] + public string Email { get; set; } - [DataMember(Name = "name")] - public string Name { get; set; } + [DataMember(Name = "name")] + public string Name { get; set; } - [DataMember(Name = "link")] - public Uri Link { get; set; } + [DataMember(Name = "link")] + public Uri Link { get; set; } - [DataMember(Name = "gender")] - public string Gender { get; set; } + [DataMember(Name = "gender")] + public string Gender { get; set; } - [DataMember(Name = "birthday")] - public string Birthday { get; set; } - } + [DataMember(Name = "birthday")] + public string Birthday { get; set; } + } } diff --git a/src/DotNetOpenAuth.AspNet/Clients/OAuth2/JsonHelper.cs b/src/DotNetOpenAuth.AspNet/Clients/OAuth2/JsonHelper.cs index 8bc6f7c..bc8af46 100644 --- a/src/DotNetOpenAuth.AspNet/Clients/OAuth2/JsonHelper.cs +++ b/src/DotNetOpenAuth.AspNet/Clients/OAuth2/JsonHelper.cs @@ -1,20 +1,16 @@ -using System; -using System.IO; -using System.Runtime.Serialization.Json; +namespace DotNetOpenAuth.AspNet.Clients { + using System; + using System.IO; + using System.Runtime.Serialization.Json; -namespace DotNetOpenAuth.AspNet.Clients -{ - internal static class JsonHelper - { - public static T Deserialize<T>(Stream stream) where T : class - { - if (stream == null) - { - throw new ArgumentNullException("stream"); - } + internal static class JsonHelper { + public static T Deserialize<T>(Stream stream) where T : class { + if (stream == null) { + throw new ArgumentNullException("stream"); + } - var serializer = new DataContractJsonSerializer(typeof(T)); - return (T)serializer.ReadObject(stream); - } - } + var serializer = new DataContractJsonSerializer(typeof(T)); + return (T)serializer.ReadObject(stream); + } + } } diff --git a/src/DotNetOpenAuth.AspNet/Clients/OAuth2/OAuth2AccessTokenData.cs b/src/DotNetOpenAuth.AspNet/Clients/OAuth2/OAuth2AccessTokenData.cs index a2ecb30..7cb902e 100644 --- a/src/DotNetOpenAuth.AspNet/Clients/OAuth2/OAuth2AccessTokenData.cs +++ b/src/DotNetOpenAuth.AspNet/Clients/OAuth2/OAuth2AccessTokenData.cs @@ -1,20 +1,18 @@ -using System.Runtime.Serialization; +namespace DotNetOpenAuth.AspNet.Clients { + using System.Runtime.Serialization; -namespace DotNetOpenAuth.AspNet.Clients -{ - [DataContract] - public class OAuth2AccessTokenData - { - [DataMember(Name = "access_token")] - public string AccessToken { get; set; } + [DataContract] + public class OAuth2AccessTokenData { + [DataMember(Name = "access_token")] + public string AccessToken { get; set; } - [DataMember(Name = "refresh_token")] - public string RefreshToken { get; set; } + [DataMember(Name = "refresh_token")] + public string RefreshToken { get; set; } - [DataMember(Name = "scope")] - public string Scope { get; set; } + [DataMember(Name = "scope")] + public string Scope { get; set; } - [DataMember(Name = "token_type")] - public string TokenType { get; set; } - } + [DataMember(Name = "token_type")] + public string TokenType { get; set; } + } } diff --git a/src/DotNetOpenAuth.AspNet/Clients/OAuth2/OAuth2Client.cs b/src/DotNetOpenAuth.AspNet/Clients/OAuth2/OAuth2Client.cs index 859b3be..276f5f4 100644 --- a/src/DotNetOpenAuth.AspNet/Clients/OAuth2/OAuth2Client.cs +++ b/src/DotNetOpenAuth.AspNet/Clients/OAuth2/OAuth2Client.cs @@ -1,133 +1,119 @@ -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.Web; - -namespace DotNetOpenAuth.AspNet.Clients -{ - /// <summary> - /// Represents the base class for OAuth 2.0 clients - /// </summary> - public abstract class OAuth2Client : IAuthenticationClient - { - private readonly string _providerName; - private Uri _returnUrl; - - /// <summary> - /// Initializes a new instance of the <see cref="OAuth2Client"/> class with the specified provider name. - /// </summary> - /// <param name="providerName">Name of the provider.</param> - protected OAuth2Client(string providerName) - { - if (providerName == null) - { - throw new ArgumentNullException("providerName"); - } - - _providerName = providerName; - } - - /// <summary> - /// Gets the name of the provider which provides authentication service. - /// </summary> - public string ProviderName - { - get { return _providerName; } - } - - /// <summary> - /// Attempts to authenticate users by forwarding them to an external website, and - /// upon succcess or failure, redirect users back to the specified url. - /// </summary> - /// <param name="returnUrl">The return url after users have completed authenticating against external website.</param> - public virtual void RequestAuthentication(HttpContextBase context, Uri returnUrl) - { - if (context == null) - { - throw new ArgumentNullException("context"); - } - - if (returnUrl == null) - { - throw new ArgumentNullException("returnUrl"); - } - - _returnUrl = returnUrl; - - string redirectUrl = GetServiceLoginUrl(returnUrl).ToString(); - context.Response.Redirect(redirectUrl, endResponse: true); - } - - /// <summary> - /// Check if authentication succeeded after user is redirected back from the service provider. - /// </summary> - /// <returns> - /// An instance of <see cref="AuthenticationResult"/> containing authentication result. - /// </returns> - public virtual AuthenticationResult VerifyAuthentication(HttpContextBase context) - { - if (context == null) - { - throw new ArgumentNullException("context"); - } - - string code = context.Request.QueryString["code"]; - if (String.IsNullOrEmpty(code)) - { - return AuthenticationResult.Failed; - } - - string accessToken = QueryAccessToken(_returnUrl, code); - if (accessToken == null) - { - return AuthenticationResult.Failed; - } - - IDictionary<string, string> userData = GetUserData(accessToken); - if (userData == null) - { - return AuthenticationResult.Failed; - } - string id = userData["id"]; - string name; - // Some oAuth providers do not return value for the 'username' attribute. - // In that case, try the 'name' attribute. If it's still unavailable, fall back to 'id' - if (!userData.TryGetValue("username", out name) && !userData.TryGetValue("name", out name)) - { - name = id; - } - - return new AuthenticationResult( - isSuccessful: true, - provider: ProviderName, - providerUserId: id, - userName: name, - extraData: userData); - } - - /// <summary> - /// Gets the full url pointing to the login page for this client. The url should include the - /// specified return url so that when the login completes, user is redirected back to that url. - /// </summary> - /// <param name="returnUrl">The return URL.</param> - /// <returns></returns> - [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms", MessageId = "Login", Justification = "Login is used more consistently in ASP.Net")] - protected abstract Uri GetServiceLoginUrl(Uri returnUrl); - - /// <summary> - /// Queries the access token from the specified authorization code. - /// </summary> - /// <param name="returnUrl">The return URL.</param> - /// <param name="authorizationCode">The authorization code.</param> - /// <returns></returns> - protected abstract string QueryAccessToken(Uri returnUrl, string authorizationCode); - - /// <summary> - /// Given the access token, gets the logged-in user's data. The returned dictionary must include - /// two keys 'id', and 'username'. - /// </summary> - /// <param name="accessToken">The access token of the current user.</param> - /// <returns>A dictionary contains key-value pairs of user data</returns> - protected abstract IDictionary<string, string> GetUserData(string accessToken); - } +namespace DotNetOpenAuth.AspNet.Clients { + using System; + using System.Collections.Generic; + using System.Diagnostics.CodeAnalysis; + using System.Web; + + /// <summary> + /// Represents the base class for OAuth 2.0 clients + /// </summary> + public abstract class OAuth2Client : IAuthenticationClient { + private readonly string _providerName; + private Uri _returnUrl; + + /// <summary> + /// Initializes a new instance of the <see cref="OAuth2Client"/> class with the specified provider name. + /// </summary> + /// <param name="providerName">Name of the provider.</param> + protected OAuth2Client(string providerName) { + if (providerName == null) { + throw new ArgumentNullException("providerName"); + } + + _providerName = providerName; + } + + /// <summary> + /// Gets the name of the provider which provides authentication service. + /// </summary> + public string ProviderName { + get { return _providerName; } + } + + /// <summary> + /// Attempts to authenticate users by forwarding them to an external website, and + /// upon succcess or failure, redirect users back to the specified url. + /// </summary> + /// <param name="returnUrl">The return url after users have completed authenticating against external website.</param> + public virtual void RequestAuthentication(HttpContextBase context, Uri returnUrl) { + if (context == null) { + throw new ArgumentNullException("context"); + } + + if (returnUrl == null) { + throw new ArgumentNullException("returnUrl"); + } + + _returnUrl = returnUrl; + + string redirectUrl = GetServiceLoginUrl(returnUrl).ToString(); + context.Response.Redirect(redirectUrl, endResponse: true); + } + + /// <summary> + /// Check if authentication succeeded after user is redirected back from the service provider. + /// </summary> + /// <returns> + /// An instance of <see cref="AuthenticationResult"/> containing authentication result. + /// </returns> + public virtual AuthenticationResult VerifyAuthentication(HttpContextBase context) { + if (context == null) { + throw new ArgumentNullException("context"); + } + + string code = context.Request.QueryString["code"]; + if (String.IsNullOrEmpty(code)) { + return AuthenticationResult.Failed; + } + + string accessToken = QueryAccessToken(_returnUrl, code); + if (accessToken == null) { + return AuthenticationResult.Failed; + } + + IDictionary<string, string> userData = GetUserData(accessToken); + if (userData == null) { + return AuthenticationResult.Failed; + } + string id = userData["id"]; + string name; + // Some oAuth providers do not return value for the 'username' attribute. + // In that case, try the 'name' attribute. If it's still unavailable, fall back to 'id' + if (!userData.TryGetValue("username", out name) && !userData.TryGetValue("name", out name)) { + name = id; + } + + return new AuthenticationResult( + isSuccessful: true, + provider: ProviderName, + providerUserId: id, + userName: name, + extraData: userData); + } + + /// <summary> + /// Gets the full url pointing to the login page for this client. The url should include the + /// specified return url so that when the login completes, user is redirected back to that url. + /// </summary> + /// <param name="returnUrl">The return URL.</param> + /// <returns></returns> + [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms", MessageId = "Login", Justification = "Login is used more consistently in ASP.Net")] + protected abstract Uri GetServiceLoginUrl(Uri returnUrl); + + /// <summary> + /// Queries the access token from the specified authorization code. + /// </summary> + /// <param name="returnUrl">The return URL.</param> + /// <param name="authorizationCode">The authorization code.</param> + /// <returns></returns> + protected abstract string QueryAccessToken(Uri returnUrl, string authorizationCode); + + /// <summary> + /// Given the access token, gets the logged-in user's data. The returned dictionary must include + /// two keys 'id', and 'username'. + /// </summary> + /// <param name="accessToken">The access token of the current user.</param> + /// <returns>A dictionary contains key-value pairs of user data</returns> + protected abstract IDictionary<string, string> GetUserData(string accessToken); + } }
\ No newline at end of file diff --git a/src/DotNetOpenAuth.AspNet/Clients/OAuth2/WindowsLiveClient.cs b/src/DotNetOpenAuth.AspNet/Clients/OAuth2/WindowsLiveClient.cs index 8d81c02..bddb801 100644 --- a/src/DotNetOpenAuth.AspNet/Clients/OAuth2/WindowsLiveClient.cs +++ b/src/DotNetOpenAuth.AspNet/Clients/OAuth2/WindowsLiveClient.cs @@ -1,41 +1,35 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Net; -using System.Text; -using DotNetOpenAuth.Messaging; +namespace DotNetOpenAuth.AspNet.Clients { + using System; + using System.Collections.Generic; + using System.IO; + using System.Net; + using System.Text; + using DotNetOpenAuth.Messaging; -namespace DotNetOpenAuth.AspNet.Clients -{ - public sealed class WindowsLiveClient : OAuth2Client - { - private const string TokenEndpoint = "https://oauth.live.com/token"; - private const string AuthorizationEndpoint = "https://oauth.live.com/authorize"; - private readonly string _appId; - private readonly string _appSecret; + public sealed class WindowsLiveClient : OAuth2Client { + private const string TokenEndpoint = "https://oauth.live.com/token"; + private const string AuthorizationEndpoint = "https://oauth.live.com/authorize"; + private readonly string _appId; + private readonly string _appSecret; - public WindowsLiveClient(string appId, string appSecret) - : base("windowslive") - { - if (String.IsNullOrEmpty(appId)) - { - throw new ArgumentNullException("appId"); - } + public WindowsLiveClient(string appId, string appSecret) + : base("windowslive") { + if (String.IsNullOrEmpty(appId)) { + throw new ArgumentNullException("appId"); + } - if (String.IsNullOrEmpty("appSecret")) - { - throw new ArgumentNullException("appSecret"); - } + if (String.IsNullOrEmpty("appSecret")) { + throw new ArgumentNullException("appSecret"); + } - _appId = appId; - _appSecret = appSecret; - } + _appId = appId; + _appSecret = appSecret; + } - protected override Uri GetServiceLoginUrl(Uri returnUrl) - { - var builder = new UriBuilder(AuthorizationEndpoint); - MessagingUtilities.AppendQueryArgs(builder, - new KeyValuePair<string, string>[] + protected override Uri GetServiceLoginUrl(Uri returnUrl) { + var builder = new UriBuilder(AuthorizationEndpoint); + MessagingUtilities.AppendQueryArgs(builder, + new KeyValuePair<string, string>[] { new KeyValuePair<string, string>("client_id", _appId), new KeyValuePair<string, string>("scope", "wl.basic"), @@ -43,67 +37,59 @@ namespace DotNetOpenAuth.AspNet.Clients new KeyValuePair<string, string>("redirect_uri", returnUrl.ToString()) }); - return builder.Uri; - } + return builder.Uri; + } - protected override string QueryAccessToken(Uri returnUrl, string authorizationCode) - { - var builder = new StringBuilder(); - builder.AppendFormat("client_id={0}", _appId); - builder.AppendFormat("&redirect_uri={0}", Uri.EscapeDataString(returnUrl.ToString())); - builder.AppendFormat("&client_secret={0}", _appSecret); - builder.AppendFormat("&code={0}", authorizationCode); - builder.Append("&grant_type=authorization_code"); + protected override string QueryAccessToken(Uri returnUrl, string authorizationCode) { + var builder = new StringBuilder(); + builder.AppendFormat("client_id={0}", _appId); + builder.AppendFormat("&redirect_uri={0}", Uri.EscapeDataString(returnUrl.ToString())); + builder.AppendFormat("&client_secret={0}", _appSecret); + builder.AppendFormat("&code={0}", authorizationCode); + builder.Append("&grant_type=authorization_code"); - WebRequest tokenRequest = WebRequest.Create(TokenEndpoint); - tokenRequest.ContentType = "application/x-www-form-urlencoded"; - tokenRequest.ContentLength = builder.Length; - tokenRequest.Method = "POST"; + WebRequest tokenRequest = WebRequest.Create(TokenEndpoint); + tokenRequest.ContentType = "application/x-www-form-urlencoded"; + tokenRequest.ContentLength = builder.Length; + tokenRequest.Method = "POST"; - using (Stream requestStream = tokenRequest.GetRequestStream()) - { - var writer = new StreamWriter(requestStream); - writer.Write(builder.ToString()); - writer.Flush(); - } + using (Stream requestStream = tokenRequest.GetRequestStream()) { + var writer = new StreamWriter(requestStream); + writer.Write(builder.ToString()); + writer.Flush(); + } - HttpWebResponse tokenResponse = (HttpWebResponse)tokenRequest.GetResponse(); - if (tokenResponse.StatusCode == HttpStatusCode.OK) - { - using (Stream responseStream = tokenResponse.GetResponseStream()) - { - var tokenData = JsonHelper.Deserialize<OAuth2AccessTokenData>(responseStream); - if (tokenData != null) - { - return tokenData.AccessToken; - } - } - } + HttpWebResponse tokenResponse = (HttpWebResponse)tokenRequest.GetResponse(); + if (tokenResponse.StatusCode == HttpStatusCode.OK) { + using (Stream responseStream = tokenResponse.GetResponseStream()) { + var tokenData = JsonHelper.Deserialize<OAuth2AccessTokenData>(responseStream); + if (tokenData != null) { + return tokenData.AccessToken; + } + } + } - return null; - } + return null; + } - protected override IDictionary<string, string> GetUserData(string accessToken) - { - WindowsLiveUserData graph; - var request = WebRequest.Create("https://apis.live.net/v5.0/me?access_token=" + Uri.EscapeDataString(accessToken)); - using (var response = request.GetResponse()) - { - using (var responseStream = response.GetResponseStream()) - { - graph = JsonHelper.Deserialize<WindowsLiveUserData>(responseStream); - } - } + protected override IDictionary<string, string> GetUserData(string accessToken) { + WindowsLiveUserData graph; + var request = WebRequest.Create("https://apis.live.net/v5.0/me?access_token=" + Uri.EscapeDataString(accessToken)); + using (var response = request.GetResponse()) { + using (var responseStream = response.GetResponseStream()) { + graph = JsonHelper.Deserialize<WindowsLiveUserData>(responseStream); + } + } - var userData = new Dictionary<string, string>(); - userData.AddItemIfNotEmpty("id", graph.Id); - userData.AddItemIfNotEmpty("username", graph.Name); - userData.AddItemIfNotEmpty("name", graph.Name); - userData.AddItemIfNotEmpty("link", graph.Link == null ? null : graph.Link.ToString()); - userData.AddItemIfNotEmpty("gender", graph.Gender); - userData.AddItemIfNotEmpty("firstname", graph.FirstName); - userData.AddItemIfNotEmpty("lastname", graph.LastName); - return userData; - } - } + var userData = new Dictionary<string, string>(); + userData.AddItemIfNotEmpty("id", graph.Id); + userData.AddItemIfNotEmpty("username", graph.Name); + userData.AddItemIfNotEmpty("name", graph.Name); + userData.AddItemIfNotEmpty("link", graph.Link == null ? null : graph.Link.ToString()); + userData.AddItemIfNotEmpty("gender", graph.Gender); + userData.AddItemIfNotEmpty("firstname", graph.FirstName); + userData.AddItemIfNotEmpty("lastname", graph.LastName); + return userData; + } + } } diff --git a/src/DotNetOpenAuth.AspNet/Clients/OAuth2/WindowsLiveUserData.cs b/src/DotNetOpenAuth.AspNet/Clients/OAuth2/WindowsLiveUserData.cs index 7371250..8147e2f 100644 --- a/src/DotNetOpenAuth.AspNet/Clients/OAuth2/WindowsLiveUserData.cs +++ b/src/DotNetOpenAuth.AspNet/Clients/OAuth2/WindowsLiveUserData.cs @@ -1,36 +1,34 @@ -using System; -using System.Runtime.Serialization; -using System.ComponentModel; +namespace DotNetOpenAuth.AspNet.Clients { + using System; + using System.Runtime.Serialization; + using System.ComponentModel; -namespace DotNetOpenAuth.AspNet.Clients -{ - /// <summary> - /// Contains data of a Windows Live user. - /// </summary> - /// <remarks> - /// Technically, this class doesn't need to be public, but because we want to make it serializable - /// in medium trust, it has to be public. - /// </remarks> - [DataContract] - [EditorBrowsable(EditorBrowsableState.Never)] - public class WindowsLiveUserData - { - [DataMember(Name = "id")] - public string Id { get; set; } + /// <summary> + /// Contains data of a Windows Live user. + /// </summary> + /// <remarks> + /// Technically, this class doesn't need to be public, but because we want to make it serializable + /// in medium trust, it has to be public. + /// </remarks> + [DataContract] + [EditorBrowsable(EditorBrowsableState.Never)] + public class WindowsLiveUserData { + [DataMember(Name = "id")] + public string Id { get; set; } - [DataMember(Name = "name")] - public string Name { get; set; } + [DataMember(Name = "name")] + public string Name { get; set; } - [DataMember(Name = "link")] - public Uri Link { get; set; } + [DataMember(Name = "link")] + public Uri Link { get; set; } - [DataMember(Name = "gender")] - public string Gender { get; set; } + [DataMember(Name = "gender")] + public string Gender { get; set; } - [DataMember(Name = "first_name")] - public string FirstName { get; set; } + [DataMember(Name = "first_name")] + public string FirstName { get; set; } - [DataMember(Name = "last_name")] - public string LastName { get; set; } - } + [DataMember(Name = "last_name")] + public string LastName { get; set; } + } } |