/// <summary>
        /// run step 123.
        /// </summary>
        /// <returns></returns>
        public override Token[] Parse()
        {
            // Last token: number
            var takeoverToken = _lexer.LastTokenData;
            var line          = _lexer.State.Line;
            var pos           = _lexer.State.LineCharPosition;

            // Current char is "-"
            var letter = _lexer.State.CurrentChar;

            // Get next 8 chars
            // TODO: Optimize here ( although after move to metacompiler lexical plugins optimizations may not be needed )
            var phoneText = _lexer.Scanner.PeekMaxChars(8);

            _lexer.Scanner.MoveChars(9);

            var finalText = takeoverToken.Token.Text + letter + phoneText;
            var lineToken = TokenBuilder.ToLiteralString(finalText);
            var t         = new TokenData()
            {
                Token = lineToken, Line = line, LineCharPos = pos
            };

            _lexer.ParsedTokens.Add(t);
            return(new Token[] { lineToken });
        }
Example #2
0
        /// <summary>
        /// 获取登录结果
        /// </summary>
        /// <param name="user">用户</param>
        /// <param name="signInResult">登录结果</param>
        /// <param name="applicationCode">应用程序编码</param>
        private async Task <SignInWithTokenResult> GetLoginResultAsync(User user, SignInResult signInResult, string applicationCode)
        {
            if (signInResult.State == SignInState.Failed)
            {
                return new SignInWithTokenResult {
                           UserId = signInResult.UserId, State = signInResult.State, Message = signInResult.Message
                }
            }
            ;
            await MessageEventBus.PublishAsync(new UserLoginMessageEvent(new UserLoginMessage
            {
                UserId = user.Id,
                Name = user.Nickname,
                Ip = Web.IP,
                UserAgent = Web.Browser
            }));

            var result = await TokenBuilder.CreateAsync(user.GetClaims().ToDictionary(x => x.Type, x => x.Value));

            return(new SignInWithTokenResult
            {
                UserId = signInResult.UserId,
                State = signInResult.State,
                Message = signInResult.Message,
                Token = result
            });
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="UserManager"/> class
 /// </summary>
 /// <param name="userManager">Identity framework user manager</param>
 /// <param name="tokenBuilder">JWT token builder</param>
 public UserManager(
     Identity.UserManager <User> userManager,
     TokenBuilder tokenBuilder)
 {
     IdentityUserManager = userManager;
     TokenBuilder        = tokenBuilder;
 }
Example #4
0
        public IActionResult Login([FromBody] InterfaceLogin content)
        {
            var user = _db.Pessoas.Find(w => w.Usuario == content.login && w.Senha == Functions.GetHash(content.senha))?.FirstOrDefault();

            if (user == null)
            {
                return(StatusCode(400, "Não encontrado"));
            }

            var payload = new PayloadJwt
            {
                subId = user.Usuario,
                sub   = user.Email,
                name  = user.Nome,
                roles = new List <string>
                {
                    "logger",
                    "admin"
                }
            };

            var token = new TokenBuilder(_configuration).Build(payload);

            return(StatusCode(200, new
            {
                user.Nome,
                id = user._id.ToString(),
                token,
                payload.roles
            }));
        }
Example #5
0
        public void ValidateClaimsTest()
        {
            // Arrange.
            var expires      = DateTime.UtcNow.AddHours(3);
            var tokenBuilder = new TokenBuilder()
                               .AddIssuer(TestIssuer)
                               .AddAudience(TestAudience)
                               .AddClaims(_claimCollection)
                               .AddSecret(TestSecret)
                               .Expires(expires);

            // Act.
            var token      = tokenBuilder.Build();
            var validToken = token.Validate(TestIssuer, TestAudience, TestSecret);
            var claims1    = token.Claims;
            var claims2    = validToken.Claims;

            // Assert.
            claims1.ForEach((x, i) =>
            {
                var(key, value) = x;
                Assert.Equal(key, claims2.ElementAt(i).Key);
                Assert.Equal(value, claims2.ElementAt(i).Value);
            });

            Assert.Equal("Batman", validToken.Claims.Single(x => x.Key == ClaimTypes.Name).Value);
        }
        public async Task <HttpRequestMessage> Map(HttpContext context, ReRoute route)
        {
            var downstreamUri = route.GetDownstreamUri(context);

            var requestMessage = new HttpRequestMessage(route.DownstreamMethod, downstreamUri);

            requestMessage.Content = MapContent(context, route);

            foreach (var header in context.Request.Headers.Where(x => !x.Key.StartsWith("Content-")))
            {
                requestMessage.Headers.Add(header.Key, header.Value.ToArray());
            }


            var headerModifications = route.GetRequestHeaderModifications();

            foreach (var headerAction in headerModifications)
            {
                headerAction(requestMessage.Headers);
            }


            // This could be also done in the startup in headerModifications, but I leave it here for clarity

            TokenBuilder tokenBuilder = TokenBuilder.Instance;
            string       XCToken      = await tokenBuilder.GetXCAccessToken(route.TokenUserId());

            requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", XCToken);

            return(requestMessage);
        }
        public async Task Invoke(HttpContext httpContext)
        {
            string authoriztionHeader = httpContext.Request.Headers["Authorization"];

            if (authoriztionHeader != null && authoriztionHeader.StartsWith("Bearer"))
            {
                var currentToken = authoriztionHeader.Substring("Bearer ".Length).Trim();

                var securityToken = TokenBuilder.GetValidSecurityToken(currentToken);

                if (securityToken != null)
                {
                    // your additional logic here...
                    await _requestDelegate.Invoke(httpContext);
                }
                else
                {
                    httpContext.Response.StatusCode = 401;
                }
            }
            else
            {
                await _requestDelegate.Invoke(httpContext);
            }
        }
Example #8
0
        public static BracketNode BuildWhitespaceNode()
        {
            var space = BuildLiteralNode(TokenBuilder.BuildLiteralToken((char)32));
            var t     = BuildLiteralNode(TokenBuilder.BuildLiteralToken((char)9));

            /*
             * var cr = BuildLiteralNode(TokenBuilder.BuildLiteralToken((char)13));
             * var nl = BuildLiteralNode(TokenBuilder.BuildLiteralToken((char)10));
             * var vt = BuildLiteralNode(TokenBuilder.BuildLiteralToken((char)11));
             * var ff = BuildLiteralNode(TokenBuilder.BuildLiteralToken((char)12));
             */

            var set = new BracketNode(new BracketRightToken());

            set.ChildNodes.Add(space);
            set.ChildNodes.Add(t);

            /*
             * set.ChildNodes.Add(cr);
             * set.ChildNodes.Add(nl);
             * set.ChildNodes.Add(vt);
             * set.ChildNodes.Add(ff);
             */
            return(set);
        }
Example #9
0
        // </fs:plugin-autogenerate>

        /// <summary>
        /// Parses the alias statement.
        /// </summary>
        /// <returns></returns>
        public override Expr Parse()
        {
            _tokenIt.ExpectIdText("alias");
            var aliasName = _tokenIt.ExpectId(true, true);

            _tokenIt.ExpectIdText("to");
            var   actualName = _tokenIt.ExpectId(true, true);
            Token actual     = null;

            if (Tokens.AllTokens.ContainsKey(actualName))
            {
                actual = Tokens.AllTokens[actualName];
            }
            else
            {
                actual = TokenBuilder.ToIdentifier(actualName);
            }

            var stmt = new AliasStmt()
            {
                Alias = aliasName, Actual = actual
            };

            return(stmt);
        }
Example #10
0
        /// <summary>
        /// run step 123.
        /// </summary>
        /// <returns></returns>
        public override Token[] Parse()
        {
            var lastToken = _lexer.LastTokenData;

            // Case 1: noon, afternoon, midnight
            if (_endPos == -1)
            {
                var aliasToken = new Token(TokenKind.LiteralTime, TokenTypes.LiteralTime, lastToken.Token.Text, _time);
                lastToken.Token = aliasToken;
                _lexer.ParsedTokens.Add(lastToken);
                return(new Token[] { aliasToken });
            }

            // Case 2: 8:30:45 pm
            var line      = _lexer.State.Line;
            var pos       = _lexer.State.LineCharPosition;
            var separator = _lexer.State.CurrentChar;
            var textToken = _lexer.ReadToPosition(_endPos);
            var timeText  = lastToken.Token.Text + separator + textToken.Text;
            var timeToken = TokenBuilder.ToLiteralTime(timeText, _time);

            var t = new TokenData()
            {
                Token = timeToken, Line = line, LineCharPos = pos
            };

            _lexer.ParsedTokens.Add(t);
            return(new Token[] { timeToken });
        }
Example #11
0
        /// <summary>
        /// Reads string upto end of line.
        /// </summary>
        /// <returns></returns>
        public Token ReadLineRaw(bool includeNewLine)
        {
            var result = _scanner.ScanToNewLine(false, true);
            var token  = TokenBuilder.ToLiteralString(result.Text);

            return(token);
        }
Example #12
0
        /// <summary>
        /// run step 123.
        /// </summary>
        /// <returns></returns>
        public override Token[] Parse()
        {
            // *.xml .xml .doc *.doc
            var takeoverToken = _lexer.LastTokenData;
            var pretext       = takeoverToken.Token.Text;
            var line          = _lexer.State.Line;
            var pos           = _lexer.State.LineCharPosition;

            // 1. Check if starts with "*" in which case its really "*."
            if (_lexer.State.CurrentChar == '.')
            {
                _lexer.Scanner.ReadChar();
                pretext += ".";
            }

            // 2. Get the file extension name.
            var lineTokenPart = _lexer.ReadWord();
            var finalText     = pretext + lineTokenPart.Text;
            var token         = TokenBuilder.ToLiteralString(finalText);
            var t             = new TokenData()
            {
                Token = token, Line = line, LineCharPos = pos
            };

            _lexer.ParsedTokens.Add(t);
            return(new Token[] { token });
        }
Example #13
0
        protected SyntaxList <SyntaxToken> Output()
        {
            var list = TokenBuilder.ToList();

            TokenBuilder.Clear();
            return(list);
        }
Example #14
0
 public Token SwitchState(TokenType tokenType, ParserState parserState)
 {
     Token token = TokenBuilder.Create();
     handler = parserState;
     TokenBuilder = new TokenBuilder(tokenType);
     return token;
 }
Example #15
0
        public void ClaimsIncluded()
        {
            var kp        = new KeyPair();
            var parameter = new Parameter("user-id", Parameter.Op.Equal, "1234");

            var token = new TokenBuilder(kp.AccessKey)
                        .AddViewIdentifier("SecUr3View1D")
                        .SetAttribute("user-id", 1234)
                        .SetAttribute("user-name", "Billy Bob")
                        .AddParameter(parameter)
                        .Build(kp.SecretKey);

            var headers = Jose.JWT.Headers(token);

            Assert.Equal(kp.AccessKey, headers["kid"]);

            var payload = Jose.JWT.Decode <Dictionary <string, object> >(token, kp.SecretKeyBytes);

            Assert.Equal(new string[] { "SecUr3View1D" }, payload[TokenBuilder.ViewIdentifiersClaimName]);
            Assert.Collection(
                (payload[TokenBuilder.ParametersClaimName] as ArrayList).Cast <object>().ToList(),
                p1 => Assert.Equal(new JavaScriptSerializer().Deserialize <Dictionary <string, object> >(JsonConvert.SerializeObject(parameter)), p1));
            Assert.Equal(new Dictionary <string, object>()
            {
                { "user-id", 1234 },
                { "user-name", "Billy Bob" },
            }, payload[TokenBuilder.AttributesClaimName]);
        }
Example #16
0
 public IActionResult Login([FromBody] LoginModel loginModel)
 {
     _logger.LogInformation($"{loginModel.UserName} login!");
     if (loginModel.UserName == "gsw" && loginModel.Password == "111111")
     {
         var claims = new Claim[] {
             new Claim(ClaimTypes.Name, "gsw"),
             new Claim(ClaimTypes.Role, "admin"),
             new Claim(ClaimTypes.Expiration, DateTime.Now.AddSeconds(_jwtAuthorizationRequirement.Expiration.TotalSeconds).ToString())
         };
         var identity = new ClaimsIdentity(JwtBearerDefaults.AuthenticationScheme);
         identity.AddClaims(claims);
         var token = TokenBuilder.BuildJwtToken(claims, _jwtAuthorizationRequirement);
         _logger.LogInformation($"{loginModel.UserName} login success,and generate token return");
         return(new JsonResult(new { Result = true, Data = token }));
     }
     else
     {
         _logger.LogInformation($"{loginModel.UserName} login faile");
         return(new JsonResult(new
         {
             Result = false,
             Message = "Authentication Failure"
         }));
     }
 }
Example #17
0
        private AuthenticationToken GetToken(string cpf, string qrCode)
        {
            int expirationMinutes = int.Parse(_configuration["Jwt:ExpirationMinutes"]);

            var token =
                new TokenBuilder(
                    _configuration["Jwt:Issuer"],
                    _configuration["Jwt:Key"])
                .WithUsername(cpf)
                .WithClaims(new List <Claim>
            {
                new Claim("qr-code", qrCode)
            })
                .WithExpirationMinutes(expirationMinutes)
                .Build();

            return(new AuthenticationToken
            {
                Cpf = cpf,
                QrCode = qrCode,
                Token = token,
                Created = DateTime.Now,
                Expiration = DateTime.Now.AddMinutes(expirationMinutes),
            });
        }
Example #18
0
        public IActionResult Login([FromBody] LoginModel user)
        // public IActionResult Login(string username)
        {
            if (user == null)
            {
                return(BadRequest("Invalid client request"));
            }

            try
            {
                if (ValidateUser(user))
                {
                    var model = TokenBuilder.CreateJsonWebToken(user.UserName, null, null, user.Issuer, user.ApplicationID, DateTime.UtcNow.AddDays(1));
                    return(Ok(model));
                }
                else
                {
                    return(Unauthorized());
                }
            }
            catch (Exception ex)
            {
                _logger.LogError($"Something went wrong inside the LocationTracking action: {ex}");
                return(StatusCode(500, "Internal server error"));
            }
        }
Example #19
0
 private Token(TokenBuilder builder)
 {
     Issued  = builder.Issued;
     Expires = builder.Expires;
     Type    = builder.Type;
     Value   = builder.Value;
 }
        public async Task <IActionResult> Token(StringModel <LoginDto> StringModel)
        {
            try
            {
                LoginDto model = AESEncryptDecrypt <LoginDto> .DecryptStringAES(StringModel.Model);

                byte[] ecodedString = Convert.FromBase64String(model.Password);
                string password     = Encoding.UTF8.GetString(ecodedString);

                Microsoft.AspNetCore.Identity.SignInResult result = await _signInManager.PasswordSignInAsync(model.Username, password, false, false);

                if (result.Succeeded)
                {
                    AppIdentityUser appUser = _userManager.Users.SingleOrDefault(r => r.UserName == model.Username);
                    if (appUser == null)
                    {
                        return(Ok(new APIResult <Guid> {
                            Message = Messages.NoRecord, IsSuccess = false
                        }));
                    }

                    IList <string> appUserRoles;
                    appUserRoles = await _userManager.GetRolesAsync(appUser);

                    Service.DTOs.UserCardDto user = await _userService.GetUserByIdentityID(Guid.Parse(appUser.Id));

                    string token = TokenBuilder.CreateJsonWebToken(appUser.UserName, appUserRoles, "https://www.tulparyazilim.com.tr", "https://www.tulparyazilim.com.tr", Guid.NewGuid(), DateTime.UtcNow.AddDays(30));

                    var data = new TokenDto
                    {
                        ValidTo  = DateTime.UtcNow.AddDays(30),
                        Value    = token,
                        Roles    = string.Join(',', appUserRoles),
                        Username = appUser.UserName,
                        Email    = appUser.Email
                    };

                    string str            = Newtonsoft.Json.JsonConvert.SerializeObject(data);
                    string base64Data     = Convert.ToBase64String(Encoding.Default.GetBytes(str));
                    string encryptredData = AESEncryptDecrypt <string> .EncryptStringAES(base64Data);

                    return(Ok(new APIResult <string>
                    {
                        Message = Messages.Ok,
                        Data = encryptredData,
                        IsSuccess = true
                    }));
                }
                return(Ok(new APIResult <Guid> {
                    Message = Messages.NoRecord, IsSuccess = false
                }));
            }
            catch (Exception ex)
            {
                return(Ok(new APIResult <Guid> {
                    Message = ex.ToString(), IsSuccess = false
                }));
            }
        }
 public UserController(UserFinder userFinder,
                       TokenBuilder tokenBuilder,
                       RegistrationService registrationService)
 {
     _userFinder          = userFinder;
     _tokenBuilder        = tokenBuilder;
     _registrationService = registrationService;
 }
        private Uri GetTokenUri(string realm, string redirect_uri, bool deflate, string wrap_name, string sf_persistent)
        {
            string issuer = Request.Url.AbsoluteUri;
            //string issuer = "http://localhost";
            var tokenBuilder = new TokenBuilder();

            return(tokenBuilder.ProcessRequest(realm, redirect_uri, deflate, wrap_name, sf_persistent));
        }
Example #23
0
 public TokensController(ILogger <TokensController> logger, IOptions <InDirectLineSettings> opt, DirectLineHelper helper, IDirectLineConnectionManager connectionManager, TokenBuilder tokenBuilder)
 {
     this._logger               = logger;
     this._helper               = helper;
     this._connectionManager    = connectionManager;
     this._tokenBuilder         = tokenBuilder;
     this._inDirectlineSettings = opt.Value;
 }
Example #24
0
        public void TryMatchString_DoesNotStartWithMatchingString_False(string data, string token)
        {
            //set up
            using var builder = new TokenBuilder(data.GetEnumerator());

            //test
            Assert.IsFalse(builder.TryMatch(token));
        }
Example #25
0
        public void TryMatchNextChar_NextCharMatches_True()
        {
            //set up
            using var builder = new TokenBuilder("x".GetEnumerator());

            //test
            Assert.IsTrue(builder.TryMatchNext('x'));
        }
Example #26
0
        public void TryMatchNextChar_NoCurrent_False()
        {
            //set up
            using var builder = new TokenBuilder("".GetEnumerator());

            //test
            Assert.IsFalse(builder.TryMatchCurrent('x'));
        }
Example #27
0
        public void NextChar_ReturnsEachCharThenNull(string testString)
        {
            //set up
            using var builder = new TokenBuilder(testString.GetEnumerator());

            //test
            CustomAssert.ProduceEqualValues(testString.GetEnumerator(), builder);
        }
Example #28
0
        public void TryMatchNextChar_NextCharDoesNotMatch_False()
        {
            //set up
            using var builder = new TokenBuilder("x".GetEnumerator());

            //test
            Assert.IsFalse(builder.TryMatchNext('y'));
        }
Example #29
0
        public static RangeNode BuildRangeNode(LiteralToken from, LiteralToken to)
        {
            var rangeNode = new RangeNode(TokenBuilder.BuildRangeToken());

            rangeNode.ChildNodes.Add(BuildLiteralNode(from));
            rangeNode.ChildNodes.Add(BuildLiteralNode(to));
            return(rangeNode);
        }
 static LinqPlugin()
 {
     _terminators = new Dictionary <Token, bool>();
     _terminators[TokenBuilder.ToIdentifier("order")] = true;
     _terminators[Tokens.Semicolon]        = true;
     _terminators[Tokens.NewLine]          = true;
     _terminators[Tokens.Comma]            = true;
     _terminators[Tokens.RightParenthesis] = true;
 }
Example #31
0
        public void Current_AfterPastEnd_ThrowsOutOfRangeException()
        {
            //set up
            using var builder = new TokenBuilder("".GetEnumerator());
            builder.MoveNext();

            //test
            Assert.ThrowsException <ArgumentOutOfRangeException>(() => builder.Current);
        }
Example #32
0
 /// <summary>
 ///  Initializes a new instance of the <see cref="RightBracketToken"/> class.
 /// </summary>
 /// <param name="builder">Token builder</param>
 public RightBracketToken(TokenBuilder builder)
     : base(builder)
 {
 }
Example #33
0
 public TokenParser()
 {
     TokenBuilder = new TokenBuilder(TokenType.Text);
     handler = new TextHandler();
 }
Example #34
0
 /// <summary>
 ///  Initializes a new instance of the <see cref="SeparatorToken"/> class.
 /// </summary>
 /// <param name="builder">Token builder</param>
 public SeparatorToken(TokenBuilder builder)
     : base(builder)
 {
 }
Example #35
0
 /// <summary>
 ///  Initializes a new instance of the <see cref="IdentifierToken"/> class.
 /// </summary>
 /// <param name="builder">Token builder</param>
 public IdentifierToken(TokenBuilder builder)
     : base(builder)
 {
 }
 /// <summary>
 ///  Initializes a new instance of the <see cref="BinaryOperatorToken"/> class.
 /// </summary>
 /// <param name="builder">Token builder</param>
 public BinaryOperatorToken(TokenBuilder builder)
     : base(builder)
 {
 }
Example #37
0
 /// <summary>
 ///  Initializes a new instance of the <see cref="NumberToken"/> class.
 /// </summary>
 /// <param name="builder">Token builder</param>
 public NumberToken(TokenBuilder builder)
     : base(builder)
 {
 }
Example #38
0
 /// <summary>
 ///  Initializes a new instance of the <see cref="LeftBracketToken"/> class.
 /// </summary>
 /// <param name="builder">Token builder</param>
 public LeftBracketToken(TokenBuilder builder)
     : base(builder)
 {
 }
Example #39
0
 /// <summary>
 ///  Initializes a new instance of the <see cref="OperatorToken"/> class.
 /// </summary>
 /// <param name="builder">Token builder</param>
 public OperatorToken(TokenBuilder builder)
     : base(builder)
 {
 }
 private Uri GetTokenUri(string realm, string redirect_uri, bool deflate, string wrap_name, string sf_persistent)
 {
     string issuer = Request.Url.AbsoluteUri;
     //string issuer = "http://localhost";
     var tokenBuilder = new TokenBuilder();
     return tokenBuilder.ProcessRequest(realm, redirect_uri, deflate, wrap_name, sf_persistent);
 }