Пример #1
0
        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"]);
        }
Пример #2
0
        protected void identifierBox_LoggedIn(object sender, OpenIdEventArgs e)
        {
            State.FetchResponse = e.Response.GetExtension <FetchResponse>();

            ServiceProviderDescription serviceDescription = new ServiceProviderDescription {
                AccessTokenEndpoint      = new MessageReceivingEndpoint(new Uri(e.Response.Provider.Uri, "/access_token.ashx"), HttpDeliveryMethods.AuthorizationHeaderRequest | HttpDeliveryMethods.PostRequest),
                TamperProtectionElements = new ITamperProtectionChannelBindingElement[] { new HmacSha1SigningBindingElement() },
            };
            var consumer = new WebConsumerOpenIdRelyingParty(serviceDescription, Global.OwnSampleOPHybridTokenManager);

            AuthorizedTokenResponse accessToken = consumer.ProcessUserAuthorization(e.Response);

            if (accessToken != null)
            {
                this.MultiView1.SetActiveView(this.AuthorizationGiven);

                // At this point, the access token would be somehow associated with the user
                // account at the RP.
                ////Database.Associate(e.Response.ClaimedIdentifier, accessToken.AccessToken);
            }
            else
            {
                this.MultiView1.SetActiveView(this.AuthorizationDenied);
            }

            // Avoid the redirect
            e.Cancel = true;
        }
Пример #3
0
        public ActionResult HandleLoginWithMiiCard()
        {
            var tokenManager = this.GetTokenManager();
            var consumer     = miiCard.Consumers.MiiCardConsumer.GetConsumer(tokenManager);

            var model = new HarnessViewModel();

            AuthorizedTokenResponse response = null;

            try
            {
                response = consumer.ProcessUserAuthorization();
            }
            catch (Exception ex)
            {
                model.OAuthProcessErrorText = ex.ToString();
            }

            if (response != null)
            {
                model.AccessToken       = response.AccessToken;
                model.AccessTokenSecret = tokenManager.GetTokenSecret(model.AccessToken);
            }

            model.ConsumerKey    = Session[SESSION_KEY_CONSUMER_KEY] as string;
            model.ConsumerSecret = Session[SESSION_KEY_CONSUMER_SECRET] as string;

            return(View("Index", model));
        }
Пример #4
0
        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));
            }
        }
Пример #5
0
        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("https://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 = LoadXDocumentFromStream(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));
        }
Пример #6
0
        /// <summary>
        /// Check if authentication succeeded after user is redirected back from the service provider.
        /// </summary>
        /// <param name="context">
        /// The context.
        /// </param>
        /// <returns>
        /// An instance of <see cref="AuthenticationResult"/> containing authentication result.
        /// </returns>
        public virtual AuthenticationResult VerifyAuthentication(HttpContextBase context)
        {
            AuthorizedTokenResponse response = this.WebWorker.ProcessUserAuthorization();

            if (response == null)
            {
                return(AuthenticationResult.Failed);
            }

            AuthenticationResult result = this.VerifyAuthenticationCore(response);

            if (result.IsSuccessful && result.ExtraData != null)
            {
                // add the access token to the user data dictionary just in case page developers want to use it
                var wrapExtraData = result.ExtraData.IsReadOnly
                                        ? new Dictionary <string, string>(result.ExtraData)
                                        : result.ExtraData;
                wrapExtraData["accesstoken"] = response.AccessToken;

                AuthenticationResult wrapResult = new AuthenticationResult(
                    result.IsSuccessful,
                    result.Provider,
                    result.ProviderUserId,
                    result.UserName,
                    wrapExtraData);

                result = wrapResult;
            }

            return(result);
        }
Пример #7
0
        /// <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);
        }
Пример #8
0
            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));
            }
Пример #9
0
        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);
        }
Пример #10
0
            protected override AuthenticationResult VerifyAuthenticationCore(AuthorizedTokenResponse response)
            {
                if (response.AccessToken == "ok")
                {
                    return(new AuthenticationResult(true, "mockoauth", "12345", "super", response.ExtraData));
                }

                return(AuthenticationResult.Failed);
            }
Пример #11
0
        protected override AuthenticationResult VerifyAuthenticationCore(AuthorizedTokenResponse response)
        {
            string accessToken  = response.AccessToken;
            string accessSecret = (response as ITokenSecretContainingMessage).TokenSecret;
            string text         = response.ExtraData["user_id"];
            string userName     = response.ExtraData["screen_name"];
            Dictionary <string, string> dictionary = new Dictionary <string, string>();

            dictionary.Add("accesstoken", accessToken);
            dictionary.Add("secret", accessSecret);
            return(new AuthenticationResult(true, base.ProviderName, text, userName, dictionary));
        }
Пример #12
0
        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)));
                    }
                }
            }
        }
Пример #13
0
        public void ProcessRequest(HttpContext context)
        {
            IProtocolMessage         request      = m_Provider.ReadRequest();
            UnauthorizedTokenRequest requestToken = null;
            UserAuthorizationRequest requestAuth  = null;
            AuthorizedTokenRequest   requestAccessToken;

            if ((requestToken = request as UnauthorizedTokenRequest) != null)
            {
                UnauthorizedTokenResponse response = m_Provider.PrepareUnauthorizedTokenMessage(requestToken);
                m_Provider.Channel.Send(response);
            }
            else if ((requestAuth = request as UserAuthorizationRequest) != null)
            {
                string token = ((ITokenContainingMessage)requestAuth).Token;

                ((TokenProvider)m_Provider.TokenManager).UpdatePendingUserAuthorizationRequest(token, requestAuth);

                TokenProvider.SetTokenCookie(token);

                if (context == null)
                {
                    throw new ArgumentNullException("context");
                }

                context.Response.Redirect(ActionProvider.FindAction(ActionProvider.OAuthPageActionId).AbsoluteNavigateUrl);
            }
            else if ((requestAccessToken = request as AuthorizedTokenRequest) != null)
            {
                AuthorizedTokenResponse response = m_Provider.PrepareAccessTokenMessage(requestAccessToken);

                OAuthDataSet.OAuthTokenRow row = (OAuthDataSet.OAuthTokenRow)m_Provider.TokenManager.GetAccessToken(response.AccessToken);
                response.ExtraData.Add(new KeyValuePair <string, string>("api_token", LoginProvider.Current.GetToken(row.LoginId)));

                if (!row.IsOrganizationIdNull())
                {
                    response.ExtraData.Add(new KeyValuePair <string, string>("org", OrganizationProvider.GetOrganization(row.OrganizationId).PseudoId));
                    if (!row.IsInstanceIdNull())
                    {
                        response.ExtraData.Add(new KeyValuePair <string, string>("dept", InstanceProvider.GetInstance(row.InstanceId, row.OrganizationId).PseudoId));
                    }
                }

                m_Provider.Channel.Send(response);
            }
            else
            {
                throw new InvalidOperationException();
            }
        }
Пример #14
0
        private void PopulateTwitterInfo(AuthorizedTokenResponse response, TwitterAuthenticationInfo info)
        {
            string      url      = String.Format("http://api.twitter.com/1/users/show.xml?user_id={0}", info.Identifier);
            XmlDocument document = new XmlDocument();

            document.Load(url);
            XmlNode userNode = document.DocumentElement.SelectSingleNode("//user");

            string[] firstnameAndLastname = userNode["name"].InnerText.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);
            if (firstnameAndLastname.Length > 1)
            {
                info.FirstName = firstnameAndLastname[0];
                info.LastName  = firstnameAndLastname[1];
            }
        }
Пример #15
0
        protected override AuthenticationResult VerifyAuthenticationCore(AuthorizedTokenResponse response)
        {
            // See here for Field Selectors API http://developer.linkedin.com/docs/DOC-1014
            const string profileRequestUrl =
                "https://api.linkedin.com/v1/people/~:(id,first-name,last-name,interests,headline,industry,summary,email-address,location:(name),picture-url,positions,associations,languages,honors,educations,date-of-birth,primary-twitter-account,three-current-positions,three-past-positions,group-memberships,specialties,skills)";


            string accessToken = response.AccessToken;
            string tokenSecret = (response as ITokenSecretContainingMessage).TokenSecret;
            //string Verifier = response.ExtraData.Values.First();


            var profileEndpoint =
                new MessageReceivingEndpoint(profileRequestUrl, HttpDeliveryMethods.GetRequest);
            HttpWebRequest request =
                WebWorker.PrepareAuthorizedRequest(profileEndpoint, accessToken);
            Dictionary <string, string> extraData = new Dictionary <string, string>();

            try
            {
                using (WebResponse profileResponse = request.GetResponse())
                {
                    using (Stream responseStream = profileResponse.GetResponseStream())
                    {
                        XDocument document = LoadXDocumentFromStream(responseStream);
                        userId   = document.Root.Element("id").Value;
                        userName = document.Root.Element("email-address").Value;
                        extraData.Add("firstname", document.Root.Element("first-name").Value);
                        extraData.Add("lastname", document.Root.Element("last-name").Value);
                        extraData.Add("email", document.Root.Element("email-address").Value);
                        extraData.Add("accesstoken", accessToken);
                        return(new AuthenticationResult(
                                   isSuccessful: true,
                                   provider: ProviderName,
                                   providerUserId: userId,
                                   userName: userName,
                                   extraData: extraData));
                    }
                }
            }
            catch (Exception exception)
            {
                LogWritter.LogWritterClass.WriteLog(exception);
                return(new AuthenticationResult(exception));
            }
        }
Пример #16
0
        /// <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);
        }
Пример #17
0
        /// <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.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)
            {
                message = new UnauthorizedTokenResponse(unauthorizedTokenRequest);
            }
            else if (authorizedTokenRequest != null)
            {
                message = new AuthorizedTokenResponse(authorizedTokenRequest);
            }
            else
            {
                Logger.ErrorFormat("Unexpected response message given the request type {0}", request.GetType().Name);
                throw new ProtocolException(OAuthStrings.InvalidIncomingMessage);
            }

            if (message != null)
            {
                message.SetAsIncoming();
            }

            return(message);
        }
        /// <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)
        {
            string userId = null;

            //Two things are necessary for zotero access, the users id and an access
            //token. Here if we don't find the user is, we return a failed
            //authentication result.
            if (response.ExtraData.ContainsKey("userID"))
            {
                userId = response.ExtraData["userID"];
            }
            else
            {
                return(new AuthenticationResult(false));
            }

            //We don't care if this is empty or not.
            string userName = "";

            if (response.ExtraData.ContainsKey("username"))
            {
                userName = response.ExtraData["username"];
            }

            string accessToken = response.AccessToken;

            //Since the access token is the other piece required for zotero api calls
            //if it is not found, return a failed authentication result.
            if (accessToken == null)
            {
                return(new AuthenticationResult(false));
            }

            //Since we want to access the token outside of this client, we need to
            //add it to the authentication results extra data.
            Dictionary <string, string> extraData = new Dictionary <string, string>();

            extraData.Add("accessToken", accessToken);

            return(new AuthenticationResult(true, this.ProviderName, userId, userName, extraData));
        }
Пример #19
0
        /// 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)
        {
            string accessToken  = response.AccessToken;
            string accessSecret = (response as ITokenSecretContainingMessage).TokenSecret;
            string userId       = response.ExtraData["user_id"];
            string userName     = response.ExtraData["screen_name"];

            var extraData = new Dictionary <string, string>()
            {
                { "accesstoken", accessToken },
                { "accesssecret", accessSecret }
            };

            return(new AuthenticationResult(
                       isSuccessful: true,
                       provider: ProviderName,
                       providerUserId: userId,
                       userName: userName,
                       extraData: extraData));
        }
Пример #20
0
        /// <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)
        {
            string userId   = response.ExtraData["user_id"];
            string userName = response.ExtraData["screen_name"];

            var location        = new Uri("https://api.twitter.com/1/users/show.xml?user_id=" + OAuthHelpers.EscapeUriDataStringRfc3986(userId));
            var profileEndpoint = new MessageReceivingEndpoint(location, HttpDeliveryMethods.GetRequest);
            var request         = base.WebWorker.PrepareAuthorizedRequest(profileEndpoint, response.AccessToken);

            var dictionary = new Dictionary <string, string>()
            {
                { "accesstoken", response.AccessToken }
            };

            try
            {
                using (var response2 = request.GetResponse())
                {
                    using (var stream = response2.GetResponseStream())
                    {
                        var document = LoadXDocumentFromStream(stream);
                        var name     = OAuthHelpers.ParseName(GetElementValue(document, "name"));

                        dictionary.Add("name", name.FullName);
                        dictionary.Add("firstName", name.FirstName);
                        dictionary.Add("lastName", name.LastName);
                        dictionary.Add("location", GetElementValue(document, "location"));
                        dictionary.Add("description", GetElementValue(document, "description"));
                        dictionary.Add("url", GetElementValue(document, "url"));
                    }
                }
            }
            catch (Exception)
            {
            }

            return(new AuthenticationResult(true, base.ProviderName, userId, userName, dictionary));
        }
Пример #21
0
        /// <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 <Dictionary <string, object> >(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));
            }
        }
Пример #22
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack && string.Equals(Request.Url.Host, "localhost", StringComparison.OrdinalIgnoreCase))
            {
                // Disable the button since the scenario won't work under localhost,
                // and this will help encourage the user to read the the text above the button.
                this.beginButton.Enabled = false;
            }

            IAuthenticationResponse authResponse = relyingParty.GetResponse();

            if (authResponse != null)
            {
                switch (authResponse.Status)
                {
                case AuthenticationStatus.Authenticated:
                    State.FetchResponse = authResponse.GetExtension <FetchResponse>();
                    AuthorizedTokenResponse accessToken = Global.GoogleWebConsumer.ProcessUserAuthorization(authResponse);
                    if (accessToken != null)
                    {
                        State.GoogleAccessToken = accessToken.AccessToken;
                        FormsAuthentication.SetAuthCookie(authResponse.ClaimedIdentifier, false);
                        Response.Redirect("~/MembersOnly/DisplayGoogleContacts.aspx");
                    }
                    else
                    {
                        MultiView1.SetActiveView(AuthorizationDenied);
                    }
                    break;

                case AuthenticationStatus.Canceled:
                case AuthenticationStatus.Failed:
                default:
                    this.MultiView1.SetActiveView(this.AuthenticationFailed);
                    break;
                }
            }
        }
Пример #23
0
        protected override AuthenticationResult VerifyAuthenticationCore(AuthorizedTokenResponse response)
        {
            // See here for Field Selectors API http://developer.linkedin.com/docs/DOC-1014
            const string ProfileRequestUrl = "https://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 = LoadXDocumentFromStream(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));
            }
        }
Пример #24
0
 /// <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);
Пример #25
0
        protected override void OnLoad(EventArgs e)
        {
            // If we've not yet been supplied a TokenManager then build a session-based one
            if (this.TokenManager == null)
            {
                // First try pulling key and secret information from application settings
                string consumerKey    = ConfigurationManager.AppSettings[MiiCard.ConfigSettingNameMiiCardConsumerKey];
                string consumerSecret = ConfigurationManager.AppSettings[MiiCard.ConfigSettingNameMiiCardConsumerSecret];

                // We require at least a consumer key be available - if it's not, bail out as there's no further
                // we can realistically go
                if (string.IsNullOrWhiteSpace(consumerKey))
                {
                    throw new InvalidOperationException(
                              string.Format(
                                  "The TokenManager was not initialised with suitable consumer key and secret information, and the information could not " +
                                  "be found in web.config. Either explicitly specify an IConsumerTokenManager to be used via the TokenManager property, or " +
                                  "add appropriate entries to your web.config's appSettings section with key names {0} and {1}.",
                                  MiiCard.ConfigSettingNameMiiCardConsumerKey,
                                  MiiCard.ConfigSettingNameMiiCardConsumerSecret)
                              );
                }

                this.TokenManager = new SessionStateConsumerTokenManager(consumerKey, consumerSecret);
            }

            Page.RegisterRequiresViewStateEncryption();

            var consumer = this.GetConsumer();
            AuthorizedTokenResponse authTokenResponse = null;

            try
            {
                authTokenResponse = consumer.ProcessUserAuthorization();
            }
            catch (Exception ex)
            {
                this.AuthorisationFailed(this, new MiiCardAuthorisationFailureEventArgs(ex));
            }

            if (authTokenResponse != null)
            {
                // We've been successfully authenticated - if we've been configured to do so then pull down the
                // user's profile so that it can be made available to the event handler
                MiiApiResponse <MiiUserProfile> response = null;

                if (this.LoadUserProfileOnAuthorise)
                {
                    var service = new MiiCardOAuthClaimsService(this.TokenManager.ConsumerKey, this.TokenManager.ConsumerSecret, authTokenResponse.AccessToken, this.TokenManager.GetTokenSecret(authTokenResponse.AccessToken));
                    response = service.GetClaims();

                    if (response.Status == MiiApiCallStatus.Success)
                    {
                        // User profile will be stored in the correct location based on the setting of the
                        // this.UserProfileStorage property
                        this.UserProfile = response;
                        this.AuthorisationSucceeded(this, new MiiCardAuthorisationSuccessEventArgs(authTokenResponse.AccessToken, this.TokenManager.GetTokenSecret(authTokenResponse.AccessToken), authTokenResponse.ExtraData, response));
                    }
                    else
                    {
                        this.AuthorisationFailed(this, new MiiCardAuthorisationFailureEventArgs(response.ErrorCode, response.ErrorMessage));
                    }
                }
                else
                {
                    this.AuthorisationSucceeded(this, new MiiCardAuthorisationSuccessEventArgs(authTokenResponse.AccessToken, this.TokenManager.GetTokenSecret(authTokenResponse.AccessToken), authTokenResponse.ExtraData, null));
                }
            }

            base.OnLoad(e);
        }
 public TokenResponse(AuthorizedTokenResponse response)
 {
     _response = response;
 }
Пример #27
0
        public XPathNavigator DoRequest(MessageReceivingEndpoint message, List <MultipartPostPart> parameters)
        {
            // Initialize the response XML document
            XDocument responseDocument = null;

            // Perform the request based on the authentication
            if (_oAuthConsumer == null)
            {
                // Multipart requests are only available to authenticated API accesses at the moment
                if (parameters != null)
                {
                    throw new NotImplementedException();
                }

                // Construct the request
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(message.Location);

                if ((message.AllowedMethods & HttpDeliveryMethods.PostRequest) == HttpDeliveryMethods.PostRequest)
                {
                    request.Method = "POST";
                }

                if (_proxy != null)
                {
                    request.Proxy = _proxy;
                }

                // Get and parse the response
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                if (response.StatusCode != HttpStatusCode.OK)
                {
                    throw new MalformedRequest(new StreamReader(response.GetResponseStream()).ReadToEnd());
                }

                responseDocument = XDocument.Load(XmlReader.Create(response.GetResponseStream(), new XmlReaderSettings()));
            }
            else
            {
                // Verify authentication
                if (_accessToken == null)
                {
                    AuthorizedTokenResponse accessTokenResponse = _oAuthConsumer.ProcessUserAuthorization();
                    if (accessTokenResponse != null)
                    {
                        _accessToken = accessTokenResponse.AccessToken;
                    }
                    else if (_accessToken == null)
                    {
                        _oAuthConsumer.Channel.Send(_oAuthConsumer.PrepareRequestUserAuthorization());
                    }
                }

                // Construct the request
                HttpWebRequest request = (parameters == null ? _oAuthConsumer.PrepareAuthorizedRequest(message, _accessToken) : _oAuthConsumer.PrepareAuthorizedRequest(message, _accessToken, parameters));
                if (_proxy != null)
                {
                    request.Proxy = _proxy;
                }

                IncomingWebResponse response = _oAuthConsumer.Channel.WebRequestHandler.GetResponse(request);

                if (response.Status != HttpStatusCode.OK)
                {
                    throw new MalformedRequest(new StreamReader(response.ResponseStream).ReadToEnd());
                }

                // Parse the response
                responseDocument = XDocument.Load(XmlReader.Create(response.GetResponseReader()));
            }

            // Establish navigator and validate response
            XPathNavigator responseNavigation = responseDocument.CreateNavigator();

            XPathNodeIterator responseCheckIterator = responseNavigation.Select("/response");

            if (responseCheckIterator.Count == 0)
            {
                throw new MalformedRequest(responseDocument.ToString());
            }
            while (responseCheckIterator.MoveNext())
            {
                if (responseCheckIterator.Current == null)
                {
                    return(null);
                }

                if (responseCheckIterator.Current.GetAttribute("status", "") != "ok")
                {
                    string code = responseCheckIterator.Current.GetAttribute("code", "");
                    string msg  = responseCheckIterator.Current.GetAttribute("message", "");
                    switch (code)
                    {
                    default:
                        throw new MalformedRequest(msg);

                    case "invalid_oauth_site":
                    case "invalid_oauth_user":
                    case "invalid_signature":
                    case "token_required":
                        throw new InvalidCredentials(msg);

                    case "permission_denied":
                        throw new PermissionDenied(msg);
                    }
                }
            }

            // All should be good, return the document
            return(responseNavigation);
        }
Пример #28
0
        private static HttpMessageHandler OAuthHandler(string requestTokenURL,
                                                       string authorizationTokenURL,
                                                       string accessTokenURL,
                                                       string consumerKey,
                                                       string consumerSecret,
                                                       string user,
                                                       string passwd,
                                                       string authUrl)
        {
            ServiceProviderDescription serviceDescription = new ServiceProviderDescription();

            serviceDescription.AccessTokenEndpoint       = new MessageReceivingEndpoint(new Uri(accessTokenURL), HttpDeliveryMethods.PostRequest);
            serviceDescription.ProtocolVersion           = ProtocolVersion.V10a;
            serviceDescription.RequestTokenEndpoint      = new MessageReceivingEndpoint(new Uri(requestTokenURL), HttpDeliveryMethods.PostRequest);
            serviceDescription.TamperProtectionElements  = new ITamperProtectionChannelBindingElement[] { new HmacSha1SigningBindingElement() };
            serviceDescription.UserAuthorizationEndpoint = new MessageReceivingEndpoint(new Uri(authorizationTokenURL), HttpDeliveryMethods.PostRequest);

            TokenManager tokenManager = new TokenManager(consumerKey, consumerSecret);
            WebConsumer  consumer     = new WebConsumer(serviceDescription, tokenManager);

            // callback is never called by CLM, but needed to do OAuth based forms login
            // XXX - Dns.GetHostName() alway seems to return simple, uppercased hostname
            string callback = "https://" + Dns.GetHostName() + '.' + IPGlobalProperties.GetIPGlobalProperties().DomainName + ":9443/cb";

            callback = callback.ToLower();

            consumer.PrepareRequestUserAuthorization(new Uri(callback), null, null);
            OslcClient oslcClient = new OslcClient();
            HttpClient client     = oslcClient.GetHttpClient();

            HttpStatusCode      statusCode = HttpStatusCode.Unused;
            string              location   = null;
            HttpResponseMessage resp;

            try
            {
                client.DefaultRequestHeaders.Clear();

                resp = client.GetAsync(authorizationTokenURL + "?oauth_token=" + tokenManager.GetRequestToken() +
                                       "&oauth_callback=" + Uri.EscapeUriString(callback).Replace("#", "%23").Replace("/", "%2F").Replace(":", "%3A")).Result;
                statusCode = resp.StatusCode;

                if (statusCode == HttpStatusCode.Found)
                {
                    location = resp.Headers.Location.AbsoluteUri;
                    resp.ConsumeContent();
                    statusCode = FollowRedirects(client, statusCode, location);
                }

                string        securityCheckUrl = "j_username="******"&j_password="******"application/x-www-form-urlencoded");

                mediaTypeValue.CharSet = "utf-8";

                content.Headers.ContentType = mediaTypeValue;

                resp       = client.PostAsync(authUrl + "/j_security_check", content).Result;
                statusCode = resp.StatusCode;

                string jazzAuthMessage      = null;
                IEnumerable <string> values = new List <string>();

                if (resp.Headers.TryGetValues(JAZZ_AUTH_MESSAGE_HEADER, out values))
                {
                    jazzAuthMessage = values.Last();
                }

                if (jazzAuthMessage != null && string.Compare(jazzAuthMessage, JAZZ_AUTH_FAILED, true) == 0)
                {
                    resp.ConsumeContent();
                    throw new JazzAuthFailedException(user, authUrl);
                }
                else if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Found)
                {
                    resp.ConsumeContent();
                    throw new JazzAuthErrorException(statusCode, authUrl);
                }
                else         //success
                {
                    Uri callbackUrl = resp.Headers.Location;

                    resp        = client.GetAsync(callbackUrl.AbsoluteUri).Result;
                    callbackUrl = resp.Headers.Location;
                    resp        = client.GetAsync(callbackUrl.AbsoluteUri).Result;
                    callbackUrl = resp.Headers.Location;

                    NameValueCollection qscoll = callbackUrl.ParseQueryString();

                    if (callbackUrl.OriginalString.StartsWith(callback + '?') && qscoll["oauth_verifier"] != null)
                    {
                        DesktopConsumer         desktopConsumer         = new DesktopConsumer(serviceDescription, tokenManager);
                        AuthorizedTokenResponse authorizedTokenResponse = desktopConsumer.ProcessUserAuthorization(tokenManager.GetRequestToken(), qscoll["oauth_verifier"]);

                        return(consumer.CreateAuthorizingHandler(authorizedTokenResponse.AccessToken, CreateSSLHandler()));
                    }

                    throw new JazzAuthErrorException(statusCode, authUrl);
                }
            } catch (JazzAuthFailedException jfe) {
                throw jfe;
            } catch (JazzAuthErrorException jee) {
                throw jee;
            } catch (Exception e) {
                Console.WriteLine(e.StackTrace);
            }

            // return consumer.CreateAuthorizingHandler(accessToken);
            return(null);
        }
Пример #29
0
 protected override AuthenticationResult VerifyAuthenticationCore(AuthorizedTokenResponse response)
 {
     LOG.Debug("vERITY");
     return(Helper.CreateAuthenticationResult(response, this.ProviderName));
 }