protected void LogTokenPair(TokenPair tokenPair, string text, LogEventLevel level)
        {
            if (_logger == null)
            {
                return;
            }

            _logger.Write <string, LexicalType, string>(level,
                                                        "{0} *undefined* => {1} ('{2}')",
                                                        text,
                                                        tokenPair.Current.Type,
                                                        tokenPair.Current.Text);

            //else
            //    _logger.Write( level,
            //            "{0} {1} ('{2}') => {3} ('{4}')",
            //            new object[]
            //            {
            //                text,
            //                tokenPair.Previous.Type,
            //                tokenPair.Previous.Text,
            //                tokenPair.Current.Type,
            //                tokenPair.Current.Text
            //            } );
        }
        public async Task <ActionResult <User> > Login(LoginViewModel user)
        {
            if (!ModelState.IsValid)
            {
                return(Ok(new { error_message = "Tai khoan hoac mat khau khong hop le" }));
            }

            User fromDb = await _userServices.DoLogin(user);

            if (fromDb is null)
            {
                return(Ok(new { error_message = "Đăng nhập thất bại, vui lòng thử lại!" }));
            }

            if (!fromDb.IsAccess)
            {
                return(Ok(new { error_message = "Tai khoan cua ban bi khoa. Vui long lien he quan tri vien" }));
            }

            TokenPair tokenPair = new TokenPair()
            {
                Access  = _accessToken.GenerateToken(fromDb),
                Refresh = _refreshToken.GenerateToken()
            };

            await _userServices.createUserTokenAsync(fromDb, tokenPair.Refresh);

            return(Ok(new
            {
                data = tokenPair,
                success = true,
            }));
        }
        /// <summary>
        /// acquires a <see cref="TokenPair"/> from the authority via an interactive user logon 
        /// prompt.
        /// </summary>
        /// <param name="targetUri">
        /// The uniform resource indicator of the resource access tokens are being requested for.
        /// </param>
        /// <param name="clientId">Identifier of the client requesting the token.</param>
        /// <param name="resource">
        /// Identifier of the target resource that is the recipient of the requested token.
        /// </param>
        /// <param name="redirectUri">
        /// Address to return to upon receiving a response from the authority.
        /// </param>
        /// <param name="queryParameters">
        /// Optional: appended as-is to the query string in the HTTP authentication request to the
        /// authority.
        /// </param>
        /// <returns>If successful a <see cref="TokenPair"/>; otherwise <see langword="null"/>.</returns>
        public TokenPair AcquireToken(Uri targetUri, string clientId, string resource, Uri redirectUri, string queryParameters = null)
        {
            Debug.Assert(targetUri != null && targetUri.IsAbsoluteUri, "The targetUri parameter is null or invalid");
            Debug.Assert(!String.IsNullOrWhiteSpace(clientId), "The clientId parameter is null or empty");
            Debug.Assert(!String.IsNullOrWhiteSpace(resource), "The resource parameter is null or empty");
            Debug.Assert(redirectUri != null, "The redirectUri parameter is null");
            Debug.Assert(redirectUri.IsAbsoluteUri, "The redirectUri parameter is not an absolute Uri");

            Trace.WriteLine("AzureAuthority::AcquireToken");

            TokenPair tokens = null;
            queryParameters = queryParameters ?? String.Empty;

            try
            {
                Trace.WriteLine(String.Format("   authority host url = '{0}'.", AuthorityHostUrl));

                AuthenticationContext authCtx = new AuthenticationContext(AuthorityHostUrl, _adalTokenCache);
                AuthenticationResult authResult = authCtx.AcquireToken(resource, clientId, redirectUri, PromptBehavior.Always, UserIdentifier.AnyUser, queryParameters);
                tokens = new TokenPair(authResult);

                Trace.WriteLine("   token acquisition succeeded.");
            }
            catch (AdalException)
            {
                Trace.WriteLine("   token acquisition failed.");
            }

            return tokens;
        }
Beispiel #4
0
        public TokenPair RequestToken()
        {
            try
            {
                WebRequest req       = MakeRequest("POST", "https://api.twitter.com/oauth/request_token");
                Stream     resStream = req.GetResponse().GetResponseStream();
                if (resStream != null)
                {
                    using (StreamReader reader = new StreamReader(resStream))
                    {
                        string str = reader.ReadToEnd();

                        TokenPair token = new TokenPair
                        {
                            Token  = Regex.Match(str, @"oauth_token=([^&]+)").Groups[1].Value,
                            Secret = Regex.Match(str, @"oauth_token_secret=([^&]+)").Groups[1].Value
                        };

                        return(token);
                    }
                }
                return(null);
            }
            catch (WebException ex)
            {
                Stream resStream = ex.Response?.GetResponseStream();
                if (resStream == null)
                {
                    return(null);
                }
                using (StreamReader reader = new StreamReader(resStream))
                    Console.WriteLine(reader.ReadToEnd());
                return(null);
            }
        }
        public async void SavesRefreshTokenReturnsTokenPair(string uid, bool shouldPersist)
        {
            var user = new User {
                Id = uid, UserName = "******"
            };
            var expected = new TokenPair
            {
                AccessToken  = "axessToken" + uid,
                RefreshToken = "refreshToken" + uid,
                User         = user,
                Persistent   = shouldPersist
            };
            var refreshToken = new RefreshToken
            {
                Token      = expected.RefreshToken,
                UID        = uid,
                ExpiresAt  = Now.AddDays(30),
                Persistent = shouldPersist
            };

            tokenService.Setup(x => x.CreateAccessToken(uid)).Returns(expected.AccessToken);
            tokenService.Setup(x => x.CreateRefreshToken()).Returns(expected.RefreshToken);
            refreshTokenRepo.Setup(x => x.Create(refreshToken)).ReturnsAsync(refreshToken);

            var actual = await userService.CreateAuthTokens(user, shouldPersist);

            Assert.Equal(expected, actual);
            refreshTokenRepo.Verify(x => x.Create(It.IsAny <RefreshToken>()), Times.Once);
        }
        public async Task <string> GetTokenAsync()
        {
            TokenPair tokenPair = new TokenPair("", "");

            if (tokens != null)
            {
                tokenPair = tokens;
            }
            else if (tokens == null)
            {
                string accessToken = await _localStorageService.GetItemAsync <string>(_options.Value.AccessTokenName).ConfigureAwait(true);

                string refreshToken = await _localStorageService.GetItemAsync <string>(_options.Value.RefreshTokenName).ConfigureAwait(false);

                tokenPair = new TokenPair(accessToken, refreshToken);
            }

            if (String.IsNullOrWhiteSpace(tokenPair.AccessToken) || String.IsNullOrWhiteSpace(tokenPair.RefreshToken))
            {
                throw new Exception("Invalid token");
            }

            if (!await _tokenProvider.ValidateTokenAsync(tokenPair.AccessToken))
            {
                tokenPair = await _tokenProvider.RenewTokensAsync(tokenPair.RefreshToken);
                await SetTokensAsync(tokenPair);
            }
            tokens = tokenPair;
            return(tokenPair.AccessToken);
        }
Beispiel #7
0
        public TokenPair AccessToken(string verifier)
        {
            try
            {
                var obj  = new { oauth_verifier = verifier };
                var buff = Encoding.UTF8.GetBytes(OAuth.ToString(obj));

                var req = MakeRequest("POST", "https://api.twitter.com/oauth/access_token", obj);
                req.GetRequestStream().Write(buff, 0, buff.Length);

                using (var res = req.GetResponse())
                    using (var reader = new StreamReader(res.GetResponseStream()))
                    {
                        var str = reader.ReadToEnd();

                        var token = new TokenPair();
                        token.Token  = Regex.Match(str, @"oauth_token=([^&]+)").Groups[1].Value;
                        token.Secret = Regex.Match(str, @"oauth_token_secret=([^&]+)").Groups[1].Value;

                        return(token);
                    }
            }
            catch
            {
                return(null);
            }
        }
        public async Task SetTokensAsync(TokenPair tokenPair)
        {
            await _localStorageService.SetItemAsync <string>(_options.Value.AccessTokenName, tokenPair.AccessToken);

            await _localStorageService.SetItemAsync <string>(_options.Value.RefreshTokenName, tokenPair.RefreshToken);

            tokens = new TokenPair(tokenPair.AccessToken, tokenPair.RefreshToken);
        }
        /// <inheritdoc />
        public override IDocumentItem Parse(TokenPair token, ParserOptions options, Stack <DocumentScope> buildStack,
                                            Func <int> getScope, IEnumerable <ITokenOption> tokenOptions)
        {
            var tagKeyword = _tagRegex.Match(token.Value).Value;
            var value      = token.Value?.Trim('{', '}').Remove(0, tagKeyword.Length).Trim();

            return(CreateDocumentItem(tagKeyword, value, token, options, tokenOptions));
        }
        public bool TerminateWithPrejudice(TokenPair tokenPair)
        {
            _current = null;

            LogTokenPair(tokenPair, "terminated with prejudice", LogEventLevel.Error);

            return(false);
        }
Beispiel #11
0
        /// <inheritdoc />
        public override bool ShouldParse(TokenPair token, ParserOptions options, IEnumerable <ITokenOption> tagCreationOptions)
        {
            if (!(token.Type is string blockType))
            {
                return(false);
            }

            return(TagOpen.IsMatch(blockType) || TagClose.IsMatch(blockType));
        }
        public async Task <IActionResult> Login(LoginModel model)
        {
            var jwt = await accountService.AuthAsync(model.Email, model.Password);

            var tokenPair = new TokenPair
            {
                Token     = jwt.Token,
                ExpiredAt = jwt.ExpiredAt
            };

            return(Ok(tokenPair));
        }
Beispiel #13
0
        private void AnalyzeSyntaxNode(SyntaxNodeAnalysisContext context)
        {
            if (GeneratedCodeAnalyzer?.IsGeneratedCode(context) == true)
            {
                return;
            }

            var declaration = (MemberDeclarationSyntax)context.Node;

            if (declaration.Parent?.IsKind(SyntaxKind.CompilationUnit) == false)
            {
                TokenPair tokenPair = GetTokenPair(declaration);

                if (!tokenPair.OpenToken.IsKind(SyntaxKind.None) &&
                    !tokenPair.OpenToken.IsMissing &&
                    !tokenPair.CloseToken.IsKind(SyntaxKind.None) &&
                    !tokenPair.CloseToken.IsMissing)
                {
                    int closeTokenLine = tokenPair.CloseToken.GetSpanEndLine();

                    if (tokenPair.OpenToken.GetSpanEndLine() != closeTokenLine)
                    {
                        MemberDeclarationSyntax nextDeclaration = GetNextDeclaration(declaration);

                        if (nextDeclaration != null)
                        {
                            int diff = nextDeclaration.GetSpanStartLine() - closeTokenLine;

                            if (diff < 2)
                            {
                                SyntaxTrivia trivia = declaration.GetTrailingTrivia().LastOrDefault();

                                if (trivia.IsKind(SyntaxKind.EndOfLineTrivia))
                                {
                                    context.ReportDiagnostic(
                                        DiagnosticDescriptors.AddEmptyLineBetweenDeclarations,
                                        trivia.GetLocation());
                                }
                                else
                                {
                                    context.ReportDiagnostic(
                                        DiagnosticDescriptors.AddEmptyLineBetweenDeclarations,
                                        tokenPair.CloseToken.GetLocation());
                                }
                            }
                        }
                    }
                }
            }
        }
Beispiel #14
0
        public void HandlesNullCorrectly()
        {
            var tokenPair = new TokenPair();

            Assert.False(tokenPair == null);
            Assert.False(null == tokenPair);
            Assert.True(tokenPair != null);
            Assert.True(null != tokenPair);
            tokenPair = null;
            Assert.True(tokenPair == null);
            Assert.True(null == tokenPair);
            Assert.False(tokenPair != null);
            Assert.False(null != tokenPair);
        }
Beispiel #15
0
        public static void AnalyzeMemberDeclaration(SyntaxNodeAnalysisContext context)
        {
            var declaration = (MemberDeclarationSyntax)context.Node;

            if (!declaration.IsParentKind(SyntaxKind.CompilationUnit))
            {
                TokenPair   tokenPair  = GetTokenPair(declaration);
                SyntaxToken openToken  = tokenPair.OpenToken;
                SyntaxToken closeToken = tokenPair.CloseToken;

                if (!openToken.IsKind(SyntaxKind.None) &&
                    !openToken.IsMissing &&
                    !closeToken.IsKind(SyntaxKind.None) &&
                    !closeToken.IsMissing)
                {
                    int closeTokenLine = closeToken.GetSpanEndLine();

                    if (openToken.GetSpanEndLine() != closeTokenLine)
                    {
                        MemberDeclarationSyntax nextDeclaration = GetNextDeclaration(declaration);

                        if (nextDeclaration != null)
                        {
                            int diff = nextDeclaration.GetSpanStartLine() - closeTokenLine;

                            if (diff < 2)
                            {
                                SyntaxTrivia trivia = declaration.GetTrailingTrivia().LastOrDefault();

                                if (trivia.IsEndOfLineTrivia())
                                {
                                    context.ReportDiagnostic(
                                        DiagnosticDescriptors.AddEmptyLineBetweenDeclarations,
                                        trivia);
                                }
                                else
                                {
                                    context.ReportDiagnostic(
                                        DiagnosticDescriptors.AddEmptyLineBetweenDeclarations,
                                        closeToken);
                                }
                            }
                        }
                    }
                }
            }
        }
 /// <inheritdoc />
 public override IDocumentItem Parse(TokenPair token, ParserOptions options, Stack <DocumentScope> buildStack,
                                     Func <int> getScope, IEnumerable <ITokenOption> tagCreationOptions)
 {
     if (Equals(token.Type, TagOpen.Trim()))
     {
         var tagDocumentItem = CreateDocumentItem(TagOpen,
                                                  token.Value?.Remove(0, TagOpen.Length).Trim(),
                                                  token, options, tagCreationOptions);
         buildStack.Push(new DocumentScope(tagDocumentItem, getScope));
         return(tagDocumentItem);
     }
     else if (Equals(token.Type, TagClose))
     {
         buildStack.Pop();
     }
     return(null);
 }
        public bool EndParsing(TokenPair tokenPair)
        {
            if (tokenPair.Current.Type != LexicalType.EndOfInput)
            {
                LogTokenPair(tokenPair,
                             $"{nameof( EndParsing )} called before end of command line text",
                             LogEventLevel.Error);
                return(false);
            }

            if (_current == null)
            {
                _options !.SpuriousValues.Add(tokenPair.Previous.Text);
                return(true);
            }

            return(AssignToOption(tokenPair));
        }
        public async Task <ActionResult <User> > Refresh(TokenPair token)
        {
            bool isValidToken;

            //Validate from client
            if (token.Refresh is null)
            {
                return(Unauthorized(new { error_message = "Refresh token invalid" }));
            }

            isValidToken = _refreshToken.Validate(token.Refresh);
            if (!isValidToken)
            {
                return(Unauthorized(new { error_message = "Refresh token invalid" }));
            }

            //Validate from server
            User user = await _userServices.GetByRefreshToken(token.Refresh);

            if (user is null)
            {
                return(Unauthorized(new { error_message = "Refresh token invalid" }));
            }

            isValidToken = _refreshToken.Validate(user.RefreshToken);
            if (!isValidToken)
            {
                return(Unauthorized(new { error_message = "Refresh token invalid" }));
            }

            //Create new token pair
            TokenPair tokenPair = new TokenPair
            {
                Access  = _accessToken.GenerateToken(user),
                Refresh = _refreshToken.GenerateToken()
            };
            await _userServices.createUserTokenAsync(user, tokenPair.Refresh);

            return(Ok(new
            {
                data = tokenPair,
                success = true,
            }));
        }
        public async void RetriesOnDocumentConflictError(string uid, bool shouldPersist)
        {
            var user = new User {
                Id = uid, UserName = "******"
            };
            var expected = new TokenPair
            {
                AccessToken  = "axessToken" + uid,
                RefreshToken = "refreshToken" + uid,
                User         = user,
                Persistent   = shouldPersist
            };
            var refreshToken = new RefreshToken
            {
                Token      = expected.RefreshToken,
                UID        = uid,
                ExpiresAt  = Now.AddDays(30),
                Persistent = shouldPersist
            };

            var duplicateToken = new RefreshToken
            {
                UID        = uid,
                Token      = "tokenthatsalreadyinuse",
                ExpiresAt  = Now.AddDays(30),
                Persistent = shouldPersist
            };

            tokenService.Setup(x => x.CreateAccessToken(uid)).Returns(expected.AccessToken);
            tokenService.SetupSequence(x => x.CreateRefreshToken())
            .Returns(duplicateToken.Token)
            .Returns(expected.RefreshToken);
            refreshTokenRepo.SetupSequence(x => x.Create(duplicateToken))
            .ThrowsAsync(new DocumentConflictException());
            refreshTokenRepo.SetupSequence(x => x.Create(refreshToken))
            .ReturnsAsync(refreshToken);

            var actual = await userService.CreateAuthTokens(user, shouldPersist);

            Assert.Equal(expected, actual);
            refreshTokenRepo.Verify(x => x.Create(It.IsNotNull <RefreshToken>()), Times.Exactly(2));
        }
Beispiel #20
0
        public static TokenPair Oauth_AccessToken(this OAuth oauth, string verifier)
        {
            try
            {
                var obj = new { oauth_verifier = verifier };
                var str = oauth.GetResponse("POST", new Uri("https://api.twitter.com/oauth/access_token"), obj);

                var token = new TokenPair
                {
                    Token  = Regex.Match(str, @"oauth_token=([^&]+)").Groups[1].Value,
                    Secret = Regex.Match(str, @"oauth_token_secret=([^&]+)").Groups[1].Value
                };

                return(token);
            }
            catch
            {
                return(null);
            }
        }
        public bool ProcessText(TokenPair tokenPair)
        {
            if (_current == null)
            {
                _options !.SpuriousValues.Add(tokenPair.Current.Text);
            }
            else
            {
                if (_current.Key == null)
                {
                    _current.Key = tokenPair.Current.Text;
                }
                else
                {
                    _current.Values.Add(tokenPair.Current.Text);
                }
            }

            return(true);
        }
Beispiel #22
0
        public TokenPair AccessToken(string verifier)
        {
            try
            {
                var    obj  = new { oauth_verifier = verifier };
                byte[] buff = Encoding.UTF8.GetBytes(ToString(obj));

                WebRequest req = MakeRequest("POST", "https://api.twitter.com/oauth/access_token", obj);
                req.GetRequestStream().Write(buff, 0, buff.Length);

                Stream resStream = req.GetResponse().GetResponseStream();
                if (resStream != null)
                {
                    using (StreamReader reader = new StreamReader(resStream))
                    {
                        string str = reader.ReadToEnd();

                        TokenPair token = new TokenPair
                        {
                            Token  = Regex.Match(str, @"oauth_token=([^&]+)").Groups[1].Value,
                            Secret = Regex.Match(str, @"oauth_token_secret=([^&]+)").Groups[1].Value
                        };

                        return(token);
                    }
                }
                return(null);
            }
            catch (WebException ex)
            {
                Stream resStream = ex.Response?.GetResponseStream();
                if (resStream == null)
                {
                    return(null);
                }
                using (StreamReader reader = new StreamReader(resStream))
                    Console.WriteLine(reader.ReadToEnd());
                return(null);
            }
        }
Beispiel #23
0
        public TokenPair RequestToken()
        {
            try
            {
                var req = MakeRequest("POST", "https://api.twitter.com/oauth/request_token");
                using (var res = req.GetResponse())
                    using (var reader = new StreamReader(res.GetResponseStream()))
                    {
                        var str = reader.ReadToEnd();

                        var token = new TokenPair();
                        token.Token  = Regex.Match(str, @"oauth_token=([^&]+)").Groups[1].Value;
                        token.Secret = Regex.Match(str, @"oauth_token_secret=([^&]+)").Groups[1].Value;

                        return(token);
                    }
            }
            catch
            {
                return(null);
            }
        }
        public bool Commit(TokenPair tokenPair)
        {
            if (_current == null)
            {
                switch (tokenPair.Current.Type)
                {
                // if we're not yet building an entry but we received a KeyPrefix token we must be
                // about to start building one
                case LexicalType.Separator
                    when tokenPair.Previous.Type == LexicalType.Separator:
                    return(true);

                case LexicalType.KeyPrefix:
                    return(Create(tokenPair));

                default:
                    LogTokenPair(tokenPair, "invalid token sequence", LogEventLevel.Error);
                    return(false);
                }
            }

            return(AssignToOption(tokenPair) && Create(tokenPair));
        }
        private bool AssignToOption(TokenPair tokenPair)
        {
            if (_current == null)
            {
                return(false);
            }

            // where we add values depends on how many are expected/required
            // by the option and what kind of option it is
            // Switch options should've been committed by this point -- so
            // the "switch" branch should never run -- but just to be safe...
            if (_current.Option != null)
            {
                return(_current.Option.Style == OptionStyle.Switch
                           ? CommitSwitch()
                           : CommitNonSwitch());
            }

            _options !.UnknownKeys.Add(_current);

            LogTokenPair(tokenPair, $"unexpected key '{_current.Key}'", LogEventLevel.Error);

            return(true);
        }
Beispiel #26
0
        public void HandlesNullCorrectly()
        {
            var tokenPair = new TokenPair();

            Assert.False(tokenPair.Equals(null));
        }
Beispiel #27
0
                GetStringToken(string text, TokenPair[] tokenList)
            {
                string s = text.ToLower();

                foreach (TokenPair tp in tokenList)
                {
                    if (tp.Text.Equals(s) == true)
                        return (tp.Token);
                }

                return (FToken.BadToken);
            }
 /// <inheritdoc />
 public override IDocumentItem CreateDocumentItem(string tag, string value, TokenPair token, ParserOptions options)
 {
     return(new MorestachioLocalizationDocumentItem(token.MorestachioExpression));
 }
 /// <inheritdoc />
 public override IDocumentItem CreateDocumentItem(string tag, string value, TokenPair token, ParserOptions options)
 {
     return(new CompileLessDocumentItem());
 }
        /// <summary>
        /// Acquires an access token from the authority using a previously acquired refresh token.
        /// </summary>
        /// <param name="targetUri">
        /// The uniform resource indicator of the resource access tokens are being requested for.
        /// </param>
        /// <param name="clientId">Identifier of the client requesting the token.</param>
        /// <param name="resource">
        /// Identifier of the target resource that is the recipient of the requested token.
        /// </param>
        /// <param name="refreshToken">The <see cref="Token"/> of type <see cref="TokenType.Refresh"/>
        /// to be used to acquire the access token.</param>
        /// <returns>If successful a <see cref="TokenPair"/>; otherwise <see langword="null"/>.</returns>
        public async Task<TokenPair> AcquireTokenByRefreshTokenAsync(Uri targetUri, string clientId, string resource, Token refreshToken)
        {
            Debug.Assert(targetUri != null && targetUri.IsAbsoluteUri, "The targetUri parameter is null or invalid");
            Debug.Assert(!String.IsNullOrWhiteSpace(clientId), "The clientId parameter is null or empty");
            Debug.Assert(!String.IsNullOrWhiteSpace(resource), "The resource parameter is null or empty");
            Debug.Assert(refreshToken != null, "The refreshToken parameter is null");
            Debug.Assert(refreshToken.Type == TokenType.Refresh, "The value of refreshToken parameter is not a refresh token");
            Debug.Assert(!String.IsNullOrWhiteSpace(refreshToken.Value), "The value of refreshToken parameter is null or empty");

            TokenPair tokens = null;

            try
            {
                string authorityHostUrl = AuthorityHostUrl;

                if (refreshToken.TargetIdentity != Guid.Empty)
                {
                    authorityHostUrl = GetAuthorityUrl(refreshToken.TargetIdentity);

                    Trace.WriteLine("   authority host url set by refresh token.");
                }

                Trace.WriteLine(String.Format("   authority host url = '{0}'.", authorityHostUrl));

                AuthenticationContext authCtx = new AuthenticationContext(authorityHostUrl, _adalTokenCache);
                AuthenticationResult authResult = await authCtx.AcquireTokenByRefreshTokenAsync(refreshToken.Value, clientId, resource);
                tokens = new TokenPair(authResult);

                Trace.WriteLine("   token acquisition succeeded.");
            }
            catch (AdalException)
            {
                Trace.WriteLine("   token acquisition failed.");
            }

            return tokens;
        }
Beispiel #31
0
        public TokenPair RequestToken()
        {
            try
            {
                var req = MakeRequest("POST", "https://api.twitter.com/oauth/request_token");
                using (var res = req.GetResponse())
                using (var reader = new StreamReader(res.GetResponseStream()))
                {
                    var str = reader.ReadToEnd();

                    var token = new TokenPair();
                    token.Token  = Regex.Match(str, @"oauth_token=([^&]+)").Groups[1].Value;
                    token.Secret = Regex.Match(str, @"oauth_token_secret=([^&]+)").Groups[1].Value;

                    return token;
                }
            }
            catch
            {
                return null;
            }
        }
Beispiel #32
0
        public TokenPair AccessToken(string verifier)
        {
            try
            {
                var obj = new { oauth_verifier = verifier };
                var buff = Encoding.UTF8.GetBytes(OAuth.ToString(obj));

                var req = MakeRequest("POST", "https://api.twitter.com/oauth/access_token", obj);
                req.GetRequestStream().Write(buff, 0, buff.Length);

                using (var res = req.GetResponse())
                using (var reader = new StreamReader(res.GetResponseStream()))
                {
                    var str = reader.ReadToEnd();

                    var token = new TokenPair();
                    token.Token  = Regex.Match(str, @"oauth_token=([^&]+)").Groups[1].Value;
                    token.Secret = Regex.Match(str, @"oauth_token_secret=([^&]+)").Groups[1].Value;

                    return token;
                }
            }
            catch
            {
                return null;
            }
        }
Beispiel #33
0
 /// <inheritdoc />
 public override IDocumentItem CreateDocumentItem(string tag, string value, TokenPair token, ParserOptions options,
                                                  IEnumerable <ITokenOption> tagCreationOptions)
 {
     return(new BlockDocumentItemProvider.BlockDocumentItem(token.TokenLocation, _action, value,
                                                            tagCreationOptions));
 }
Beispiel #34
0
 public TwitterOAuth(string appToken, string appSecret, string userToken, string userSecret)
 {
     App  = new TokenPair(appToken, appSecret);
     User = new TokenPair(userToken, userSecret);
 }
Beispiel #35
0
 /// <inheritdoc />
 public override IDocumentItem CreateDocumentItem(string tag, string value, TokenPair token,
                                                  ParserOptions options, IEnumerable <ITokenOption> tagCreationOptions)
 {
     return(new MorestachioCustomCultureLocalizationDocumentItem(token.TokenLocation, token.MorestachioExpression, tagCreationOptions));
 }
        /// <summary>
        /// acquires a <see cref="TokenPair"/> from the authority using optionally provided 
        /// credentials or via the current identity.
        /// </summary>
        /// <param name="targetUri">
        /// The uniform resource indicator of the resource access tokens are being requested for.
        /// </param>
        /// <param name="clientId">Identifier of the client requesting the token.</param>
        /// <param name="resource">
        /// Identifier of the target resource that is the recipient of the requested token.
        /// </param>
        /// <param name="credentials">Optional: user credential to use for token acquisition.</param>
        /// <returns>If successful a <see cref="TokenPair"/>; otherwise <see langword="null"/>.</returns>
        public async Task<TokenPair> AcquireTokenAsync(Uri targetUri, string clientId, string resource, Credential credentials = null)
        {
            Debug.Assert(targetUri != null && targetUri.IsAbsoluteUri, "The targetUri parameter is null or invalid");
            Debug.Assert(!String.IsNullOrWhiteSpace(clientId), "The clientId parameter is null or empty");
            Debug.Assert(!String.IsNullOrWhiteSpace(resource), "The resource parameter is null or empty");

            Trace.WriteLine("AzureAuthority::AcquireTokenAsync");

            TokenPair tokens = null;

            try
            {
                Trace.WriteLine(String.Format("   authority host url = '{0}'.", AuthorityHostUrl));

                UserCredential userCredential = credentials == null ? new UserCredential() : new UserCredential(credentials.Username, credentials.Password);
                AuthenticationContext authCtx = new AuthenticationContext(AuthorityHostUrl, _adalTokenCache);
                AuthenticationResult authResult = await authCtx.AcquireTokenAsync(resource, clientId, userCredential);
                tokens = new TokenPair(authResult);

                Trace.WriteLine("   token acquisition succeeded.");
            }
            catch (AdalException)
            {
                Trace.WriteLine("   token acquisition failed.");
            }

            return tokens;
        }