protected override AuthenticationResult VerifyAuthenticationCore(AuthorizedTokenResponse response) { string accessToken = response.AccessToken; string userId = response.ExtraData["user_id"]; string userName = response.ExtraData["screen_name"]; var profileRequestUrl = new Uri("http://api.twitter.com/1/users/show.xml?user_id=" + MessagingUtilities.EscapeUriDataStringRfc3986(userId)); var profileEndpoint = new MessageReceivingEndpoint(profileRequestUrl, HttpDeliveryMethods.GetRequest); HttpWebRequest request = this.WebWorker.PrepareAuthorizedRequest(profileEndpoint, accessToken); var extraData = new Dictionary<string, string>(); extraData.Add("accesstoken", accessToken); try { using (WebResponse profileResponse = request.GetResponse()) { using (Stream responseStream = profileResponse.GetResponseStream()) { XDocument document = XDocument.Load(responseStream); extraData.AddDataIfNotEmpty(document, "name"); extraData.AddDataIfNotEmpty(document, "location"); extraData.AddDataIfNotEmpty(document, "description"); extraData.AddDataIfNotEmpty(document, "url"); } } } catch (Exception) { // At this point, the authentication is already successful. // Here we are just trying to get additional data if we can. // If it fails, no problem. } return new AuthenticationResult( isSuccessful: true, provider: this.ProviderName, providerUserId: userId, userName: userName, extraData: extraData); }
protected override AuthenticationResult VerifyAuthenticationCore(AuthorizedTokenResponse response) { try { if (response != null && !String.IsNullOrWhiteSpace(response.AccessToken)) { ChelloClient client = new ChelloClient(_consumerKey, response.AccessToken); Member member = client.Members.Single("me"); response.ExtraData.Add("url", member.Url); response.ExtraData.Add("gravatar", member.Gravatar); response.ExtraData.Add("username", member.Username); response.ExtraData.Add("bio", member.Bio); response.ExtraData.Add("fullName", member.FullName); return new AuthenticationResult(true, _providerName, response.AccessToken, member.Username, response.ExtraData); } return new AuthenticationResult(false); } catch (Exception ex) { return new AuthenticationResult(ex, _providerName); } }
protected override AuthenticationResult VerifyAuthenticationCore(AuthorizedTokenResponse response) { // See here for Field Selectors API http://developer.linkedin.com/docs/DOC-1014 const string profileRequestUrl = "http://api.linkedin.com/v1/people/~:(id,first-name,last-name,headline,industry,summary)"; string accessToken = response.AccessToken; var profileEndpoint = new MessageReceivingEndpoint(profileRequestUrl, HttpDeliveryMethods.GetRequest); HttpWebRequest request = this.WebWorker.PrepareAuthorizedRequest(profileEndpoint, accessToken); try { using (WebResponse profileResponse = request.GetResponse()) { using (Stream responseStream = profileResponse.GetResponseStream()) { XDocument document = XDocument.Load(responseStream); string userId = document.Root.Element("id").Value; string firstName = document.Root.Element("first-name").Value; string lastName = document.Root.Element("last-name").Value; string userName = firstName + " " + lastName; var extraData = new Dictionary<string, string>(); extraData.Add("accesstoken", accessToken); extraData.Add("name", userName); extraData.AddDataIfNotEmpty(document, "headline"); extraData.AddDataIfNotEmpty(document, "summary"); extraData.AddDataIfNotEmpty(document, "industry"); return new AuthenticationResult( isSuccessful: true, provider: this.ProviderName, providerUserId: userId, userName: userName, extraData: extraData); } } } catch (Exception exception) { return new AuthenticationResult(exception); } }
/// Check if authentication succeeded after user is redirected back from the service provider. /// The response token returned from service provider authentication result. protected override AuthenticationResult VerifyAuthenticationCore(AuthorizedTokenResponse response) { var accessToken = response.AccessToken; var accessSecret = (response as ITokenSecretContainingMessage).TokenSecret; var userId = response.ExtraData["user_id"]; var userName = response.ExtraData["screen_name"]; var extraData = new Dictionary<string, string> { {"accesstoken", accessToken}, {"accesssecret", accessSecret} }; return new AuthenticationResult(true, ProviderName, userId, userName, extraData); }
protected override AuthenticationResult VerifyAuthenticationCore(AuthorizedTokenResponse response) { var profileEndpoint = new MessageReceivingEndpoint("https://publicapi.avans.nl/oauth/studentnummer/?format=json", HttpDeliveryMethods.GetRequest); string accessToken = response.AccessToken; consumerKey = ConfigurationManager.AppSettings["AvansOAuthConsumerKey"]; consumerSecret = ConfigurationManager.AppSettings["AvansOAuthConsumerSecret"]; InMemoryOAuthTokenManager tokenManager = new InMemoryOAuthTokenManager(consumerKey, consumerSecret); tokenManager.ExpireRequestTokenAndStoreNewAccessToken(String.Empty, String.Empty, accessToken, (response as ITokenSecretContainingMessage).TokenSecret); WebConsumer webConsumer = new WebConsumer(AvansServiceDescription, tokenManager); HttpWebRequest request = webConsumer.PrepareAuthorizedRequest(profileEndpoint, accessToken); try { using (WebResponse profileResponse = request.GetResponse()) { using (Stream profileResponseStream = profileResponse.GetResponseStream()) { using (StreamReader reader = new StreamReader(profileResponseStream)) { string jsonText = reader.ReadToEnd(); var user = JsonConvert.DeserializeObject<List<OAuthUser>>(jsonText); Dictionary<string, string> extraData = new Dictionary<string, string>(); extraData.Add("Id", user[0].Studentnummer ?? "Onbekend"); extraData.Add("Login", user[0].Inlognaam ?? "Onbekend"); DatabaseFactory.getInstance().getDAOStudent().putStudentInDatabase(Convert.ToInt32(user[0].Studentnummer), user[0].Inlognaam); return new DotNetOpenAuth.AspNet.AuthenticationResult(true, ProviderName, extraData["Id"], extraData["Login"], extraData); } } } return new AuthenticationResult(false); } catch (WebException ex) { using (Stream s = ex.Response.GetResponseStream()) { using (StreamReader sr = new StreamReader(s)) { string body = sr.ReadToEnd(); return new DotNetOpenAuth.AspNet.AuthenticationResult(new Exception(body, ex)); } } } }
internal AuthenticationResult VerifyAuthenticationInternal(AuthorizedTokenResponse response) { var msg = response as ITokenSecretContainingMessage; if (msg == null) return AuthenticationResult.Failed; string oauthToken = msg.Token; string oauthTokenSecret = msg.TokenSecret; var authenticator = OAuth1Authenticator.ForProtectedResource(_consumerKey, _consumerSecret, oauthToken, oauthTokenSecret); Uri uri = new Uri("https://bitbucket.org/api/1.0/user"); var request = new RestRequest(Method.GET); request.Resource = uri.AbsoluteUri; var client = new RestClient(); client.Authenticator = authenticator; var apiresponse = client.Execute(request); if (apiresponse.StatusCode != HttpStatusCode.OK) return AuthenticationResult.Failed; string userName = null; try { var json = JObject.Parse(apiresponse.Content); userName = json["user"]["username"].ToString(); } catch { return AuthenticationResult.Failed; } Dictionary<string, string> strs = new Dictionary<string, string>() { { "accesstoken", response.AccessToken } }; return new AuthenticationResult(true, base.ProviderName, userName, userName, strs); }
public void VerifyAuthenticationFailsIfAccessTokenIsInvalid() { // Arrange var endpoint = new MessageReceivingEndpoint("http://live.com/path/?a=b", HttpDeliveryMethods.GetRequest); var request = new AuthorizedTokenRequest(endpoint, new Version("1.0")); var response = new AuthorizedTokenResponse(request) { AccessToken = "invalid token" }; var webWorker = new Mock<IOAuthWebWorker>(MockBehavior.Strict); webWorker.Setup(w => w.ProcessUserAuthorization()).Returns(response).Verifiable(); var client = new MockOAuthClient(webWorker.Object); var context = new Mock<HttpContextBase>(); // Act AuthenticationResult result = client.VerifyAuthentication(context.Object); // Assert webWorker.Verify(); Assert.False(result.IsSuccessful); }
/// <summary> /// Check if authentication succeeded after user is redirected back from the service provider. /// </summary> /// <param name="response">The response token returned from service provider</param> /// <returns> /// Authentication result /// </returns> protected override AuthenticationResult VerifyAuthenticationCore(AuthorizedTokenResponse response) { // Create a endpoint with which we will be retrieving the Trello profile of the authenticated user var profileEndpoint = new MessageReceivingEndpoint(ProfileUrl, HttpDeliveryMethods.GetRequest); // We need to prepare the profile endpoint for authorization using the access token we have // just retrieved. If we would not do this, no access token would be sent along with the // profile request and the request would fail due to it not being authorized var request = this.WebWorker.PrepareAuthorizedRequest(profileEndpoint, response.AccessToken); try { using (var profileResponse = request.GetResponse()) using (var profileResponseStream = profileResponse.GetResponseStream()) using (var profileStreamReader = new StreamReader(profileResponseStream)) { var profileStreamContents = profileStreamReader.ReadToEnd(); // Deserialize the profile contents which is returned in JSON format var profile = JsonConvert.DeserializeObject<dynamic>(profileStreamContents); // Return the (successful) authentication result, which also retrieves the user id and username // from the return profile contents return new AuthenticationResult( isSuccessful: true, provider: this.ProviderName, providerUserId: (string)profile.id, userName: (string)profile.username, extraData: GetExtraData(profile)); } } catch (Exception exception) { // When an exception occurs, we also return that as an authentication result to allow // the exception to be gracefully handled return new AuthenticationResult(exception); } }
public static AuthenticationResult CreateAuthenticationResult(AuthorizedTokenResponse response, string providerName) { var accessToken = response.AccessToken; var accessTokenSecret = (response as ITokenSecretContainingMessage).TokenSecret; var extraData = response.ExtraData; string userId = null; string userName = null; extraData.TryGetValue("userid", out userId); extraData.TryGetValue("username", out userName); var randomString = Guid.NewGuid().ToString().Substring(0, 5); userId = userId ?? "userIdNotFound" + randomString; userName = userName ?? "userNameNotFound" + randomString; // todo: fetch user profile (insert into extra data) to pre-populate user registration fields. // var profile = Helper.GetUserProfile(this.TokenManager, null, accessToken); const bool isSuccessful = true; return new AuthenticationResult(isSuccessful, providerName, userId, userName, extraData); }
/// <summary> /// Prepares and sends an access token to a Consumer, and invalidates the request token. /// </summary> /// <param name="request">The Consumer's message requesting an access token.</param> /// <returns>The HTTP response to actually send to the Consumer.</returns> public AuthorizedTokenResponse PrepareAccessTokenMessage(AuthorizedTokenRequest request) { Requires.NotNull(request, "request"); ErrorUtilities.VerifyProtocol(this.TokenManager.IsRequestTokenAuthorized(request.RequestToken), OAuthStrings.AccessTokenNotAuthorized, request.RequestToken); string accessToken = this.TokenGenerator.GenerateAccessToken(request.ConsumerKey); string tokenSecret = this.TokenGenerator.GenerateSecret(); this.TokenManager.ExpireRequestTokenAndStoreNewAccessToken(request.ConsumerKey, request.RequestToken, accessToken, tokenSecret); var grantAccess = new AuthorizedTokenResponse(request) { AccessToken = accessToken, TokenSecret = tokenSecret, }; return grantAccess; }
protected override AuthenticationResult VerifyAuthenticationCore(AuthorizedTokenResponse response) { return VerifyAuthenticationInternal(response); }
/// <summary> /// Prepares and sends an access token to a Consumer, and invalidates the request token. /// </summary> /// <param name="request">The Consumer's message requesting an access token.</param> /// <returns>The HTTP response to actually send to the Consumer.</returns> public AuthorizedTokenResponse PrepareAccessTokenMessage(AuthorizedTokenRequest request) { if (request == null) { throw new ArgumentNullException("request"); } if (!this.TokenManager.IsRequestTokenAuthorized(request.RequestToken)) { throw new ProtocolException( string.Format( CultureInfo.CurrentCulture, OAuthStrings.AccessTokenNotAuthorized, request.RequestToken)); } string accessToken = this.TokenGenerator.GenerateAccessToken(request.ConsumerKey); string tokenSecret = this.TokenGenerator.GenerateSecret(); this.TokenManager.ExpireRequestTokenAndStoreNewAccessToken(request.ConsumerKey, request.RequestToken, accessToken, tokenSecret); var grantAccess = new AuthorizedTokenResponse(request) { AccessToken = accessToken, TokenSecret = tokenSecret, }; return grantAccess; }
protected override AuthenticationResult VerifyAuthenticationCore(AuthorizedTokenResponse response) { LOG.Debug("vERITY"); return Helper.CreateAuthenticationResult(response, this.ProviderName); }
public TokenResponse(AuthorizedTokenResponse response) { _response = response; }
public void VerifyAuthenticationSucceeds() { // Arrange var endpoint = new MessageReceivingEndpoint("http://live.com/path/?a=b", HttpDeliveryMethods.GetRequest); var request = new AuthorizedTokenRequest(endpoint, new Version("1.0")); var response = new AuthorizedTokenResponse(request) { AccessToken = "ok" }; var webWorker = new Mock<IOAuthWebWorker>(MockBehavior.Strict); webWorker.Setup(w => w.ProcessUserAuthorization()).Returns(response).Verifiable(); var client = new MockOAuthClient(webWorker.Object); var context = new Mock<HttpContextBase>(); // Act AuthenticationResult result = client.VerifyAuthentication(context.Object); // Assert webWorker.Verify(); Assert.True(result.IsSuccessful); Assert.AreEqual("mockoauth", result.Provider); Assert.AreEqual("12345", result.ProviderUserId); Assert.AreEqual("super", result.UserName); Assert.IsNotNull(result.ExtraData); Assert.IsTrue(result.ExtraData.ContainsKey("accesstoken")); Assert.AreEqual("ok", result.ExtraData["accesstoken"]); }
/// <summary> /// Check if authentication succeeded after user is redirected back from the service provider. /// </summary> /// <param name="response"> /// The response token returned from service provider /// </param> /// <returns> /// Authentication result /// </returns> protected abstract AuthenticationResult VerifyAuthenticationCore(AuthorizedTokenResponse response);
/// <summary> /// Analyzes an incoming request message payload to discover what kind of /// message is embedded in it and returns the type, or null if no match is found. /// </summary> /// <param name="request"> /// The message that was sent as a request that resulted in the response. /// Null on a Consumer site that is receiving an indirect message from the Service Provider. /// </param> /// <param name="fields">The name/value pairs that make up the message payload.</param> /// <returns> /// A newly instantiated <see cref="IProtocolMessage"/>-derived object that this message can /// deserialize to. Null if the request isn't recognized as a valid protocol message. /// </returns> /// <remarks> /// The response messages are: /// UnauthorizedTokenResponse /// AuthorizedTokenResponse /// </remarks> public virtual IDirectResponseProtocolMessage GetNewResponseMessage(IDirectedProtocolMessage request, IDictionary<string, string> fields) { ErrorUtilities.VerifyArgumentNotNull(request, "request"); ErrorUtilities.VerifyArgumentNotNull(fields, "fields"); MessageBase message = null; // All response messages have the oauth_token field. if (!fields.ContainsKey("oauth_token")) { return null; } // All direct message responses should have the oauth_token_secret field. if (!fields.ContainsKey("oauth_token_secret")) { Logger.OAuth.Error("An OAuth message was expected to contain an oauth_token_secret but didn't."); return null; } var unauthorizedTokenRequest = request as UnauthorizedTokenRequest; var authorizedTokenRequest = request as AuthorizedTokenRequest; if (unauthorizedTokenRequest != null) { Protocol protocol = fields.ContainsKey("oauth_callback_confirmed") ? Protocol.V10a : Protocol.V10; message = new UnauthorizedTokenResponse(unauthorizedTokenRequest, protocol.Version); } else if (authorizedTokenRequest != null) { message = new AuthorizedTokenResponse(authorizedTokenRequest); } else { Logger.OAuth.ErrorFormat("Unexpected response message given the request type {0}", request.GetType().Name); throw new ProtocolException(OAuthStrings.InvalidIncomingMessage); } if (message != null) { message.SetAsIncoming(); } return message; }
protected override AuthenticationResult VerifyAuthenticationCore(AuthorizedTokenResponse response) { if (response.AccessToken == "ok") { return new AuthenticationResult(true, "mockoauth", "12345", "super", response.ExtraData); } return AuthenticationResult.Failed; }