Exemple #1
0
        public ITwitterCredentials GenerateToken(IAuthenticationToken authToken)
        {
            var callbackParameter = _oAuthWebRequestGenerator.GenerateParameter("oauth_verifier", authToken.VerifierCode, true, true, false);

            try
            {
                var authHandler = new AuthHttpHandler(callbackParameter, authToken);
                var response    = _twitterRequestHandler.ExecuteQuery(Resources.OAuthRequestAccessToken, HttpMethod.POST, authHandler,
                                                                      new TwitterCredentials(authToken.ConsumerCredentials));

                if (response == null)
                {
                    return(null);
                }

                Match responseInformation = Regex.Match(response, "oauth_token=(?<oauth_token>(?:\\w|\\-)*)&oauth_token_secret=(?<oauth_token_secret>(?:\\w)*)&user_id=(?<user_id>(?:\\d)*)&screen_name=(?<screen_name>(?:\\w)*)");

                var credentials = new TwitterCredentials();
                credentials.AccessToken       = responseInformation.Groups["oauth_token"].Value;
                credentials.AccessTokenSecret = responseInformation.Groups["oauth_token_secret"].Value;
                credentials.ConsumerKey       = authToken.ConsumerKey;
                credentials.ConsumerSecret    = authToken.ConsumerSecret;

                return(credentials);
            }
            catch (TwitterException ex)
            {
                LogExceptionOrThrow(ex);
            }

            return(null);
        }
Exemple #2
0
 protected void NotifyFailure(IAuthenticationToken token, AuthenticationException exception)
 {
     if (LoginFailed != null)
     {
         LoginFailed(this, new FailedLoginEventArgs(token, exception));
     }
 }
Exemple #3
0
 protected void NotifySuccess(IAuthenticationToken token, IAuthenticationInfo info)
 {
     if (LoginSuccessful != null)
     {
         LoginSuccessful(this, new SuccessfulLoginEventArgs(token, info));
     }
 }
        public async Task GivenAnAssetHasBeenCreated_WhenTheAssetIsReadFromTheGateway_ThenItIsTheSame(string email,
                                                                                                      string token,
                                                                                                      int seconds)
        {
            //arrange
            using (var trans = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                Faker faker = new Faker();
                IAuthenticationToken authenticationToken = new AuthenticationToken
                {
                    Expiry          = DateTime.UtcNow.AddSeconds(seconds),
                    ReferenceNumber = faker.UniqueIndex.ToString(),
                    Token           = token,
                    EmailAddress    = email
                };

                //act
                IAuthenticationToken createdAuthenticationToken = await _classUnderTest
                                                                  .CreateAsync(authenticationToken, CancellationToken.None).ConfigureAwait(false);

                IAuthenticationToken readAuthenticationToken = await _classUnderTest
                                                               .ReadAsync(createdAuthenticationToken.Token, CancellationToken.None).ConfigureAwait(false);

                //assert
                readAuthenticationToken.EmailAddress.Should().BeEquivalentTo(email);
                readAuthenticationToken.Token.Should().BeEquivalentTo(authenticationToken.Token);
                readAuthenticationToken.Expiry.Should().BeCloseTo(authenticationToken.Expiry);
                readAuthenticationToken.ReferenceNumber.Should().Be(authenticationToken.ReferenceNumber);
            }
        }
        /// <summary>
        /// Saves token to storage.
        /// </summary>
        /// <param name="token">Token to save.</param>
        /// <returns>True if token has been saved, false otherwise.</returns>
        public virtual bool Save(IAuthenticationToken token)
        {
            if (rwl.TryEnterWriteLock(Timeout.Infinite))
            {
                var result = false;
                try
                {
                    if (System.Web.HttpContext.Current != null && System.Web.HttpContext.Current.Response != null)
                    {
                        HttpContext.Current.Response.Cookies.Remove(HeaderKey);

                        var cookie = new HttpCookie(HeaderKey, SerializeToken(token));
                        cookie.HttpOnly = true;
                        cookie.Expires  = DateTime.Now.AddSeconds((token.ExpiresIn.HasValue && token.ExpiresIn.Value > 0) ? token.ExpiresIn.Value : ((token.SlidingWindow.HasValue && token.SlidingWindow.Value > 0) ? token.SlidingWindow.Value : 7200));
                        cookie.Path     = "/";
                        HttpContext.Current.Response.Cookies.Add(cookie);
                        result = true;
                    }
                }
                finally
                {
                    rwl.ExitWriteLock();
                }
                return(result);
            }
            return(false);
        }
        public IEnumerable <IOAuthQueryParameter> GenerateApplicationParameters(
            IConsumerCredentials temporaryCredentials,
            IAuthenticationToken authenticationToken = null,
            IEnumerable <IOAuthQueryParameter> additionalParameters = null)
        {
            var headers = GenerateConsumerParameters(temporaryCredentials).ToList();

            // Add Header for authenticated connection to a Twitter Application
            if (authenticationToken != null &&
                !string.IsNullOrEmpty(authenticationToken.AuthorizationKey) &&
                !string.IsNullOrEmpty(authenticationToken.AuthorizationSecret))
            {
                headers.Add(new OAuthQueryParameter("oauth_token", StringFormater.UrlEncode(authenticationToken.AuthorizationKey), true, true, false));
                headers.Add(new OAuthQueryParameter("oauth_token_secret", StringFormater.UrlEncode(authenticationToken.AuthorizationSecret), false, false, true));
            }
            else
            {
                headers.Add(new OAuthQueryParameter("oauth_token", "", false, false, true));
            }

            if (additionalParameters != null)
            {
                headers.AddRange(additionalParameters);
            }

            return(headers);
        }
Exemple #7
0
        public IEnumerable<IOAuthQueryParameter> GenerateApplicationParameters(
            IConsumerCredentials temporaryCredentials,
            IAuthenticationToken authenticationToken = null,
            IEnumerable<IOAuthQueryParameter> additionalParameters = null)
        {
            var headers = GenerateConsumerParameters(temporaryCredentials).ToList();

            // Add Header for authenticated connection to a Twitter Application
            if (authenticationToken != null &&
                !string.IsNullOrEmpty(authenticationToken.AuthorizationKey) &&
                !string.IsNullOrEmpty(authenticationToken.AuthorizationSecret))
            {
                headers.Add(new OAuthQueryParameter("oauth_token", StringFormater.UrlEncode(authenticationToken.AuthorizationKey), true, true, false));
                headers.Add(new OAuthQueryParameter("oauth_token_secret", StringFormater.UrlEncode(authenticationToken.AuthorizationSecret), false, false, true));
            }
            else
            {
                headers.Add(new OAuthQueryParameter("oauth_token", "", false, false, true));
            }

            if (additionalParameters != null)
            {
                headers.AddRange(additionalParameters);
            }

            return headers;
        }
        public void AuthenticateAdmin_AdminFoundInRepository_ReturnsCorrectAuthenticationToken()
        {
            // prepare
            string validEmail     = "*****@*****.**";
            string validPassword  = "******";
            string validFirstName = "Jalal";
            string validLastName  = "Uddin";

            var adminRepositoryMock = _kernel.GetMock <IMembershipRepository>();

            adminRepositoryMock.Setup(x => x.Get(validEmail)).Returns(new Admin()
            {
                EmailAddress = validEmail,
                FirstName    = validFirstName,
                LastName     = validLastName
            });

            var repositoryFactoryMock = _kernel.GetMock <IMembershipRepositoryFactory>();

            repositoryFactoryMock.Setup(x => x.CreateMembershipRepository(UserTypeOptions.Admin)).Returns(adminRepositoryMock.Object);
            IAuthenticator authenticator = _kernel.Get <IAuthenticator>();

            // act
            IAuthenticationToken token = authenticator.AuthenticateAdmin(validEmail, validPassword);

            // assert
            Assert.IsNotNull(token);
            Assert.AreEqual(validEmail, token.EmailAddress);
            Assert.AreEqual(validFirstName, token.FirstName);
            Assert.AreEqual(validLastName, token.LastName);
            Assert.AreEqual(UserTypeOptions.Admin, token.UserType);
        }
Exemple #9
0
 public LoginEventArgs(IAuthenticationToken token)
 {
     if (token == null)
     {
         throw new ArgumentNullException("token");
     }
     _token = token;
 }
 public static AuthenticationTokenReset Create(IAuthenticationToken token)
 {
     return new AuthenticationTokenReset
     {
         Username = token.Username,
         Token = token.Token,
     };
 }
Exemple #11
0
 public LoginEventArgs(IAuthenticationToken token)
 {
     if (token == null)
     {
         throw new ArgumentNullException("token");
     }
     _token = token;
 }
Exemple #12
0
 public static AuthenticationTokenRequest Create(IAuthenticationToken token)
 {
     return(new AuthenticationTokenRequest
     {
         Username = token.Username,
         Token = token.Token,
     });
 }
Exemple #13
0
 public Task <IAuthenticationToken> ReadAsync(string token, CancellationToken cancellationToken)
 {
     using (var context = new AssetRegisterContext(_databaseUrl))
     {
         IAuthenticationToken foundToken = context.AuthenticationTokens.FirstOrDefault(t => t.Token == token);
         return(Task.FromResult(foundToken));
     }
 }
Exemple #14
0
 public async Task InvalidateAuthenticationTokenAsync(IAuthenticationToken token)
 {
     if (!(token is AuthenticationToken))
     {
         throw new InvalidOperationException("Token is no AuthenticationToken");
     }
     ((AuthenticationToken)token).IsActive = false;
     AuthenticationTokens.First(s => s.Token == token.Token).IsActive = false;
 }
Exemple #15
0
 public SuccessfulLoginEventArgs(IAuthenticationToken token, IAuthenticationInfo info)
     : base(token)
 {
     if (info == null)
     {
         throw new ArgumentNullException("info");
     }
     _info = info;
 }
 public SuccessfulLoginEventArgs(IAuthenticationToken token, IAuthenticationInfo info)
     : base(token)
 {
     if (info == null)
     {
         throw new ArgumentNullException("info");
     }
     _info = info;
 }
Exemple #17
0
 public FailedLoginEventArgs(IAuthenticationToken token, AuthenticationException exception)
     : base(token)
 {
     if (exception == null)
     {
         throw new ArgumentNullException("exception");
     }
     _exception = exception;
 }
        async Task <bool> IsAuthorized()
        {
            if ((AuthenticationToken == null) || AuthenticationToken.IsExpired)
            {
                AuthenticationToken = await GetAuthToken();
            }

            return(AuthenticationToken != null);
        }
Exemple #19
0
        /// <summary>
        /// Creates the asynchronous.
        /// </summary>
        /// <param name="username">The username.</param>
        /// <param name="password">The password.</param>
        /// <param name="tokenOptions">The token options.</param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public virtual async Task <IAuthenticationToken> CreateAsync(string username, string password, TokenOptions tokenOptions = null)
        {
            using (var client = BaasicPlatformClientFactory.Create(Configuration))
            {
                if (tokenOptions == null)
                {
                    tokenOptions = new TokenOptions();
                }

                var request = new HttpRequestMessage(HttpMethod.Post, client.GetApiUrl(string.Format("{0}?{1}", this.ModuleRelativePath, tokenOptions.GetOptionsCSV())))
                {
                    Content = new FormUrlEncodedContent(new KeyValuePair <string, string>[] {
                        new KeyValuePair <string, string>("grant_type", "password"),
                        new KeyValuePair <string, string>("username", username),
                        new KeyValuePair <string, string>("password", password)
                    })
                };

                IAuthenticationToken token    = null;
                IAuthenticationToken oldToken = this.Configuration.TokenHandler.Get();
                this.Configuration.TokenHandler.Clear();

                try
                {
                    var response = await client.SendAsync(request);

                    var responseContent = await response.Content.ReadAsStringAsync();

                    BaasicErrorResponse responseObject = null;
                    try
                    {
                        responseObject = await client.ReadContentAsync <BaasicErrorResponse>(response);
                    }
                    catch { }

                    if (response.StatusCode.Equals(HttpStatusCode.OK) ||
                        response.StatusCode.Equals(HttpStatusCode.Created))
                    {
                        token = this.ReadToken(JsonFormatter.Deserialize <Newtonsoft.Json.Linq.JObject>(responseContent));
                    }
                    else
                    {
                        throw new BaasicClientException((int)response.StatusCode, "Unable to create new token.", responseObject?.Error, responseObject?.ErrorCode ?? 0, new Exception(responseContent));
                    }
                }
                catch (Exception ex)
                {
                    this.SaveToken(oldToken);
                    throw ex;
                }

                this.SaveToken(token);

                return(token);
            }
        }
        public void AuthenticateShopOwner_EmptyEmailAddress_ThrowsException()
        {
            // prepare
            IAuthenticator authenticator = _kernel.Get <IAuthenticator>();
            string         emptyEmail    = string.Empty;
            string         validPassword = "******";

            // act
            IAuthenticationToken token = authenticator.AuthenticateShopOwner(emptyEmail, validPassword);
        }
Exemple #21
0
 private async Task SendOneTimeLink(string email, IAuthenticationToken createdToken, string originUrl,
                                    CancellationToken cancellationToken)
 {
     await _oneTimeLinkNotifier.SendOneTimeLinkAsync(new OneTimeLinkNotification
     {
         Email = email,
         Token = createdToken.Token,
         Url   = originUrl
     }, cancellationToken).ConfigureAwait(false);
 }
        public void AuthenticateShopOwner_EmptyPassword_ThrowsException()
        {
            // prepare
            IAuthenticator authenticator = _kernel.Get <IAuthenticator>();
            string         validEmail    = "*****@*****.**";
            string         emptyPassword = string.Empty;

            // act
            IAuthenticationToken token = authenticator.AuthenticateShopOwner(validEmail, emptyPassword);
        }
        public void AuthenticateAdmin_NullEmailAddress_ThrowsException()
        {
            // prepare
            IAuthenticator authenticator = _kernel.Get <IAuthenticator>();
            string         nullEmail     = null;
            string         validPassword = "******";

            // act
            IAuthenticationToken token = authenticator.AuthenticateAdmin(nullEmail, validPassword);
        }
        public void AuthenticateAdmin_NullPassword_ThrowsException()
        {
            // prepare
            IAuthenticator authenticator = _kernel.Get <IAuthenticator>();
            string         validEmail    = "*****@*****.**";
            string         nullPassword  = string.Empty;

            // act
            IAuthenticationToken token = authenticator.AuthenticateAdmin(validEmail, nullPassword);
        }
Exemple #25
0
        // Step 2 - Generate User Credentials
        public ITwitterCredentials GetCredentialsFromVerifierCode(string verifierCode, IAuthenticationToken authToken)
        {
            try
            {
                if (authToken == null)
                {
                    throw new ArgumentNullException("Authentication Token cannot be null.");
                }

                if (verifierCode == null)
                {
                    throw new ArgumentNullException("VerifierCode", "If you've received a verifier code that is null, " +
                                                                    "it means that authentication has failed!");
                }

                var callbackParameter = _oAuthWebRequestGenerator.GenerateParameter("oauth_verifier", verifierCode, true, true, false);

                var authHandler = new AuthHttpHandler(callbackParameter, authToken);
                var response = _twitterRequestHandler.ExecuteQuery(Resources.OAuthRequestAccessToken, HttpMethod.POST, authHandler,
                    new TwitterCredentials(authToken.ConsumerCredentials));

                if (response == null)
                {
                    return null;
                }

                var responseInformation = Regex.Match(response, Resources.OAuthTokenAccessRegex);
                if (responseInformation.Groups["oauth_token"] == null || responseInformation.Groups["oauth_token_secret"] == null)
                {
                    return null;
                }

                var credentials = new TwitterCredentials(
                    authToken.ConsumerKey,
                    authToken.ConsumerSecret,
                    responseInformation.Groups["oauth_token"].Value,
                    responseInformation.Groups["oauth_token_secret"].Value);

                return credentials;
            }
            catch (TwitterException ex)
            {
                if (_exceptionHandler.LogExceptions)
                {
                    _exceptionHandler.AddTwitterException(ex);
                }

                if (!_exceptionHandler.SwallowWebExceptions)
                {
                    throw;
                }
            }

            return null;
        }
 public AuthenticationTokenEntity(IAuthenticationToken authenticationToken)
 {
     if (authenticationToken == null)
     {
         return;
     }
     Id = authenticationToken.Id;
     ReferenceNumber  = authenticationToken.ReferenceNumber;
     Expiry           = authenticationToken.Expiry;
     Token            = authenticationToken.Token;
     ModifiedDateTime = authenticationToken.Expiry;
     EmailAddress     = authenticationToken.EmailAddress;
 }
Exemple #27
0
        public Task <IAuthenticationToken> CreateAsync(IAuthenticationToken token, CancellationToken cancellationToken)
        {
            var tokenEntity = new AuthenticationTokenEntity(token);

            using (var context = new AssetRegisterContext(_databaseUrl))
            {
                context.Add(tokenEntity);
                context.SaveChanges();
                token.Id = tokenEntity.Id;
                IAuthenticationToken foundAsset = context.AuthenticationTokens.Find(tokenEntity.Id);
                return(Task.FromResult(foundAsset));
            }
        }
Exemple #28
0
        protected virtual bool SaveToken(IAuthenticationToken token)
        {
            if (token != null)
            {
                var tokenHandler = this.Configuration.TokenHandler;
                if (tokenHandler != null)
                {
                    return(tokenHandler.Save(token));
                }
            }

            return(false);
        }
        public void PreTestInitialize()
        {
            Username = ConfigurationManager.AppSettings["TestJiraUsername"];
            Password = ConfigurationManager.AppSettings["TestJiraPassword"];

            using (IUnityContainer container = new UnityContainer()
                .LoadConfiguration())
            {
                _service = container.Resolve<IProjectsService>();
            }

            _token = _service.Login(Username, Password);
        }
        public void AuthenticateAdmin_ValidEmailAddressAndPassword_ReturnsValidAuthenticationToken()
        {
            // prepare
            IAuthenticator authenticator = _kernel.Get <IAuthenticator>();
            string         validEmail    = "*****@*****.**";
            string         validPassword = "******";

            // act
            IAuthenticationToken token = authenticator.AuthenticateAdmin(validEmail, validPassword);

            // assert
            Assert.IsNotNull(token);
            Assert.AreEqual(validEmail, token.EmailAddress);
        }
Exemple #31
0
        private async Task <IAuthenticationToken> CreateAuthenticationTokenForEmail(AuthenticateUserRequest request,
                                                                                    CancellationToken cancellationToken)
        {
            AuthenticationToken authenticationToken = new AuthenticationToken
            {
                EmailAddress    = request.Email,
                Expiry          = DateTime.UtcNow.AddHours(8),
                Token           = Guid.NewGuid().ToString(),
                ReferenceNumber = Guid.NewGuid().ToString()
            };
            IAuthenticationToken createdToken = await _authenticationTokenCreator
                                                .CreateAsync(authenticationToken, cancellationToken).ConfigureAwait(false);

            return(createdToken);
        }
Exemple #32
0
        public async Task <AuthenticateUserResponse> ExecuteAsync(AuthenticateUserRequest requests,
                                                                  CancellationToken cancellationToken)
        {
            if (!UserIsAuthorised(requests.Email))
            {
                return(UnauthorisedResponse());
            }

            IAuthenticationToken createdToken =
                await CreateAuthenticationTokenForEmail(requests, cancellationToken).ConfigureAwait(false);

            await SendOneTimeLink(requests.Email, createdToken, requests.Url, cancellationToken).ConfigureAwait(false);

            return(AuthorisedResponse());
        }
Exemple #33
0
        public ITwitterCredentials GetCredentialsFromCallbackURL(string callbackURL, IAuthenticationToken authToken)
        {
            Match urlInformation = Regex.Match(callbackURL, Resources.OAuthToken_GetVerifierCode_Regex);

            var responseOAuthToken = urlInformation.Groups["oauth_token"].Value;
            var verifierCode       = urlInformation.Groups["oauth_verifier"].Value;

            // Check that the callback URL response passed in is for our current credentials....
            if (string.Equals(responseOAuthToken, authToken.AuthorizationKey))
            {
                GetCredentialsFromVerifierCode(verifierCode, authToken);
            }

            return(null);
        }
Exemple #34
0
        public async Task <GetAccessTokenResponse> ExecuteAsync(GetAccessTokenRequest tokenRequest,
                                                                CancellationToken cancellationToken)
        {
            IAuthenticationToken token = await _tokenReader.ReadAsync(tokenRequest.Token, cancellationToken);

            if (NoMatchingTokenIsFound(token) || TokenHasExpired(token))
            {
                return(UnauthorisedResponse());
            }

            IAccessToken accessToken = await _accessTokenCreator.CreateAsync(token.EmailAddress, cancellationToken);

            await _tokenDeleter.DeleteAsync(tokenRequest.Token, cancellationToken);

            return(AuthorisedResponse(accessToken));
        }
Exemple #35
0
 /// <summary>
 /// Clear token storage.
 /// </summary>
 /// <returns>True if token has been cleared, false otherwise.</returns>
 public virtual bool Clear()
 {
     if (rwl.TryEnterWriteLock(Timeout.Infinite))
     {
         try
         {
             DefaultPlatformTokenHandler.token = null;
         }
         finally
         {
             rwl.ExitWriteLock();
         }
         return(true);
     }
     return(false);
 }
Exemple #36
0
 /// <summary>
 /// Saves token to storage.
 /// </summary>
 /// <param name="token">Token to save.</param>
 /// <returns>True if token has been saved, false otherwise.</returns>
 public virtual bool Save(IAuthenticationToken token)
 {
     if (rwl.TryEnterWriteLock(Timeout.Infinite))
     {
         try
         {
             DefaultPlatformTokenHandler.token = token;
         }
         finally
         {
             rwl.ExitWriteLock();
         }
         return(true);
     }
     return(false);
 }
        public IAuthenticationToken GetUser(IAuthenticationToken token, string username)
        {
            IAuthenticationToken user = null;
            var jiraUser = _soapServiceClient.getUser(token.Token, username);
            
            using(IUnityContainer container = new UnityContainer()
                .LoadConfiguration())
            {
                user = container.Resolve<IAuthenticationToken>();

                user.Email = jiraUser.email;
                user.FullName = jiraUser.fullname;
                user.Username = jiraUser.name;
            }

            return user;
        }
 public IEnumerable<RemoteProject> GetProjects(IAuthenticationToken token)
 {
     return _soapServiceClient.getProjectsNoSchemes(token.Token).ToList<RemoteProject>();
 }
Exemple #39
0
 private static ITwitterCredentials CreateCredentialsFromVerifierCode(string verifierCode, IAuthenticationToken authToken)
 {
     return _authFactory.GetCredentialsFromVerifierCode(verifierCode, authToken);
 }
Exemple #40
0
        private static IAuthenticationToken CreateCrentialsFromId(string identifier, IAuthenticationToken authToken)
        {
            if (authToken == null ||
                string.IsNullOrEmpty(authToken.AuthorizationKey) ||
                string.IsNullOrEmpty(authToken.AuthorizationSecret))
            {
                IAuthenticationContext authContext;
                if (_credentialsStore.TryGetValue(identifier, out authContext))
                {
                    authToken = authContext.Token;
                }
                else
                {
                    if (authToken == null)
                    {
                        throw new ArgumentException("The credentials are required as the URL does not contain the credentials identifier.");
                    }

                    throw new ArgumentException("The credentials needs the AuthorizationKey and AuthorizationSecret to be set up as the URL does not contain the credentials identifier.");
                }
            }

            return authToken;
        }
 public bool Logout(IAuthenticationToken authenticationToken)
 {
     return _soapServiceClient.logout(authenticationToken.Token);
 }
 public RemoteProject GetProject(IAuthenticationToken token, string key)
 {
     return _soapServiceClient.getProjectByKey(token.Token, key);
 }
 public AuthHttpHandler(IOAuthQueryParameter queryParameter, IAuthenticationToken authenticationToken)
 {
     _queryParameter = queryParameter;
     _authenticationToken = authenticationToken;
 }
Exemple #44
0
 /// <summary>
 /// Authenticates the specified token.
 /// </summary>
 /// <param name="token">The token.</param>
 /// <returns></returns>
 public abstract bool Authenticate(IAuthenticationToken token);
        public ITwitterCredentials GenerateToken(IAuthenticationToken authToken)
        {
            var callbackParameter = _oAuthWebRequestGenerator.GenerateParameter("oauth_verifier", authToken.VerifierCode, true, true, false);

            try
            {
                var authHandler = new AuthHttpHandler(callbackParameter, authToken);
                var response = _twitterRequestHandler.ExecuteQuery(Resources.OAuthRequestAccessToken, HttpMethod.POST, authHandler, 
                    new TwitterCredentials(authToken.ConsumerCredentials));

                if (response == null)
                {
                    return null;
                }

                Match responseInformation = Regex.Match(response, "oauth_token=(?<oauth_token>(?:\\w|\\-)*)&oauth_token_secret=(?<oauth_token_secret>(?:\\w)*)&user_id=(?<user_id>(?:\\d)*)&screen_name=(?<screen_name>(?:\\w)*)");

                var credentials = new TwitterCredentials();
                credentials.AccessToken = responseInformation.Groups["oauth_token"].Value;
                credentials.AccessTokenSecret = responseInformation.Groups["oauth_token_secret"].Value;
                credentials.ConsumerKey = authToken.ConsumerKey;
                credentials.ConsumerSecret = authToken.ConsumerSecret;

                return credentials;
            }
            catch (TwitterException ex)
            {
                LogExceptionOrThrow(ex);
            }

            return null;
        }
        public ITwitterCredentials GetCredentialsFromCallbackURL(string callbackURL, IAuthenticationToken authToken)
        {
            Match urlInformation = Regex.Match(callbackURL, Resources.OAuthToken_GetVerifierCode_Regex);

            var responseOAuthToken = urlInformation.Groups["oauth_token"].Value;
            var verifierCode = urlInformation.Groups["oauth_verifier"].Value;

            // Check that the callback URL response passed in is for our current credentials....
            if (string.Equals(responseOAuthToken, authToken.AuthorizationKey))
            {
                GetCredentialsFromVerifierCode(verifierCode, authToken);
            }

            return null;
        }
Exemple #47
0
 /// <summary>
 /// Authenticates the specified token.
 /// </summary>
 /// <param name="token">The token.</param>
 /// <returns></returns>
 public override bool Authenticate(IAuthenticationToken token)
 {
     return true;
 }
        public void Login(IAuthenticationToken token)
        {
            var subject = SecurityManager.Login(this, token);

            string host = null;
            IPrincipalCollection principals;
            if (subject is DelegatingSubject)
            {
                DelegatingSubject delegating = (DelegatingSubject) subject;
                host = delegating.Host;
                principals = delegating.Principals;
            }
            else
            {
                principals = subject.Principals;
            }

            if (principals == null || principals.Count == 0)
            {
                throw new InvalidSubjectException(Properties.Resources.NullOrEmptyPrincipalsAfterLoginMessage);
            }

            Principals = principals;
            Authenticated = true;
            if (token is IHostAuthenticationToken)
            {
                host = ((IHostAuthenticationToken) token).Host;
            }
            if (host != null)
            {
                Host = host;
            }

            var session = subject.GetSession(false);
            if (session == null)
            {
                _session = null;
            }
            else
            {
                _session = Decorate(session);

            }

            ThreadContext.Subject = this;
        }
 public ITwitterCredentials GetCredentialsFromVerifierCode(string verifierCode, IAuthenticationToken authToken)
 {
     authToken.VerifierCode = verifierCode;
     return GenerateToken(authToken);
 }
 public RemoteIssue CreateIssue(IAuthenticationToken token, RemoteIssue issue)
 {
     return _soapServiceClient.createIssue(token.Token, issue);
 }