Пример #1
0
        public IActionResult Create(TokenRequest request)
        {
            if (string.IsNullOrWhiteSpace(request.Email) || string.IsNullOrWhiteSpace(request.Password))
            {
                return(BadRequest(_localizer["InvalidLoginCredentials"].Value));
            }

            var user = _unitOfWork.UsersRepository.Get(x => x.Email == request.Email).FirstOrDefault();

            if (user == null)
            {
                return(BadRequest(_localizer["InvalidLoginCredentials"].Value));
            }

            try
            {
                return(new ObjectResult(TokenHandler.GenerateToken(_localizer, _unitOfWork, user, request.Password)));
            }
            catch (MissingFieldException mfe)
            {
                return(BadRequest(mfe.Message));
            }
            catch (InvalidCastException ice)
            {
                return(BadRequest(ice.Message));
            }
        }
Пример #2
0
        public JsonResult RefreshToken()
        {
            var userRefreshToken = HttpContext.User.Claims.Where(c => c.Type == ClaimTypes.NameIdentifier)
                                   .Select(c => c.Value).SingleOrDefault();

            var userLogin = UserLoginRepo.NewInstance.Filter.RefreshToken(userRefreshToken).Get.FirstOrDefault();

            if (userLogin != null)/*&& user?.RefreshTokenEndDate > DateTime.Now*/
            {
                TokenHandler tokenHandler = new TokenHandler(configuration);
                Token.Token  token        = tokenHandler.CreateAccessToken(userLogin);
                userLogin.RefreshToken        = token.RefreshToken;
                userLogin.RefreshTokenEndDate = token.Expiration.AddMinutes(3);

                var updateRefresh = UserLoginRepo.NewInstance.Do.Update(userLogin);

                var claims = new List <Claim>
                {
                    new Claim(ClaimTypes.Sid, userLogin.UserId.ToString()),
                    new Claim(ClaimTypes.NameIdentifier, userLogin.RefreshToken),
                    new Claim(ClaimTypes.Name, userLogin.Name + " " + userLogin.Surname),
                    new Claim(ClaimTypes.Email, userLogin.Email),
                };
                var identity  = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
                var principal = new ClaimsPrincipal(identity);
                var props     = new AuthenticationProperties();
                HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal, props);
                return(Json(new { result = true }));
            }
            return(Json(new { result = false }));
        }
        public static IServiceCollection AddJwtBearerAuthentication(this IServiceCollection services, Action <JwtSecurityOptions> configureOptions)
        {
            if (services == null)
            {
                throw new ArgumentNullException(nameof(services));
            }

            var jwtSecurityOptions = new JwtSecurityOptions();

            configureOptions(jwtSecurityOptions);

            var tokenHandler = new TokenHandler(jwtSecurityOptions);

            services.AddAuthentication(
                options => {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultScheme             = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = tokenHandler.TokenValidationParameters;
            });

            return(services);
        }
Пример #4
0
        public ActionResult Put(int Id, User Model)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return(BadRequest("Data can not be updated"));
                }

                if (Id != Model.Id)
                {
                    return(BadRequest("Invalid Data"));
                }

                //Allow accesss to Admin and Client(only his details)
                string Token = Request.Headers["Authorization"].ToString().Replace("Bearer ", "");
                if (!TokenHandler.IsUserAllowed(Id, Token))
                {
                    return(Unauthorized());
                }

                string Message;
                if (!UserRepository.ValidateInput(Model, out Message))
                {
                    return(BadRequest(Message));
                }

                UserRepository.Update(Model, Id);
                UserRepository.Save();

                return(Ok("Record Updated"));
            }
            catch (Exception) { return(BadRequest("Record can not be updated, please check your input data")); }
        }
Пример #5
0
        static void Main(string[] args)
        {
            string programAsText = "";
            string fileName      = "";

            Console.WriteLine("Please Enter absolute path for the text file(sorry): \n");
            fileName = Console.ReadLine();

            Console.WriteLine("The html will be generated with name semi_pretty.html");

            using (var reader = new StreamReader(fileName))
            {
                while (!reader.EndOfStream)
                {
                    programAsText += reader.ReadLine();
                    programAsText += "\n";
                }
            }

            var tokenizer = new Lexer(programAsText, fileName);
            var tokens    = tokenizer.GenerateTokens();

            var printToPath  = "semi_pretty.html";
            var tokenHandler = new TokenHandler(tokens, printToPath);

            //tokenHandler.PrintTokens();
            tokenHandler.PrettyPrint(printToPath);
        }
Пример #6
0
        private bool Getemail(out string email)
        {
            var currentUserClaims = HttpContext.User;

            email = TokenHandler.GetEmailFromClaims(currentUserClaims);
            return(!string.IsNullOrEmpty(email));
        }
        public async Task <Response <bool> > DeleteUserById([FromRoute] string id)
        {
            Response <bool> response = new Response <bool>();

            // Get user email from the token, so we can be sure that the user deleting the entry is himself
            // This is a protection so the one user can't tamper or delete other users data with his token provided
            // If your application has role policy, you can create Authorization middleware, so that only admins can delete users
            // Then you can put [Authorize(Policy = "AdminOnly")] to this endpoint
            string requesterEmail = TokenHandler.GetClaimFromToken("Email", Request.Headers["Authorization"].ToString().Split(' ')[1]);

            User checkingUser = await _userRepository.GetUserById(ObjectId.Parse(id));

            if (checkingUser == null)
            {
                return(response.Failed("User does not exist.", false));
            }

            if (requesterEmail != checkingUser.Email)
            {
                return(response.Failed("Unauthorized", false));
            }

            bool result = await _userRepository.DeleteUserById(ObjectId.Parse(id));

            if (result)
            {
                return(response.Success("Success", result));
            }
            else
            {
                return(response.Failed("User does not exist.", result));
            }
        }
Пример #8
0
        private void InitHandler(TokenizerContext context)
        {
            var parsingContext = ParsingContext.Create();
            var tokenFactory   = new TokenFactory(parsingContext.Configuration.FunctionRepository, null);

            _handler = new TokenHandler(_tokenizerContext, tokenFactory, new TokenSeparatorProvider());
        }
        /// <summary>
        ///Admin Login Async
        /// </summary>
        /// <param name="AdminLoginDTO"></param>
        /// <returns>bool</returns>
        public async Task <UserDTO> AdminLoginAsync(UserLoginDTO adminLoginDTO)
        {
            #region Declare a return type with initial value.
            UserDTO AdminReturn = new UserDTO();
            #endregion
            try
            {
                Admin admin = null;
                if (adminLoginDTO != null)
                {
                    admin = await UnitOfWork.AdminRepository.GetWhere(x => x.Email.Trim().ToLower().Equals(adminLoginDTO.Email.Trim().ToLower()) &&
                                                                      x.IsDeleted == (byte)DeleteStatusEnum.NotDeleted).FirstOrDefaultAsync();

                    if (admin != null)
                    {
                        if (!VerifyPasswordHash(adminLoginDTO.Password, admin.PasswordHash, admin.PasswordSalt))
                        {
                            AdminReturn = AdminMapping.MappingAdminToUserDTO(admin);
                        }

                        AdminReturn.Token = TokenHandler.CreateToken(AdminReturn).Token;
                    }
                }
            }
            catch (Exception exception)
            {
                // Logger.Instance.LogException(exception, LogLevel.Medium);
            }
            return(AdminReturn);
        }
Пример #10
0
        public ActionResult <String> GetCSRFToken()
        {
            var value = HttpContext.Session.GetString(Properties.Values.SESSION_KEY);

            token = new TokenHandler();
            return(token.GetCSRFToken(HttpContext.Session.Id));
        }
Пример #11
0
 private async Task AssignCart()
 {
     TokenHandler.Logout();
     CreatedResource = ResourcesHolder.Create <CartResource>().Value;
     TokenHandler.LoginWithNewUser();
     await GetClient <ICartsControllClient>().Assign(CreatedResource.Id);
 }
 public SecurityToken Validate(string token)
 {
     var secKey = new SymmetricSecurityKey(
         Encoding.ASCII.GetBytes(_config["Auth:SecretKey"]));
     var validationParams = new TokenValidationParameters()
     {
         ValidateLifetime = true,
         ValidateAudience = true,
         ValidIssuer = _config["Auth:Issuer"],
         ValidAudience = _config["Auth:Audience"],
         IssuerSigningKey = secKey
     };
     SecurityToken validatedToken;
     try
     {
         TokenHandler.ValidateToken(token, validationParams, out validatedToken);
     }
     catch(SecurityTokenException)
     {
         return null;
     }
     catch(Exception e)
     {
         _logger.LogInformation(
             "damn boy where'd you find dis\n"
             + e.ToString()
         );
         return null;
     }
     return validatedToken;
 }
Пример #13
0
        public IActionResult Login([FromBody] AgentLoginInputViewModel loginViewModel)
        {
            var agent = _agentRepository
                        .Find(a => a.BusinessId == loginViewModel.BusinessId && a.Password == loginViewModel.EncryptedPassword)
                        .FirstOrDefault();

            if (agent is null)
            {
                HandleError("Agent", "Invalid Business ID/password");
                return(Response(loginViewModel));
            }

            var userViewModel = new UserViewModel
            {
                Id       = agent.Id,
                UserType = UserType.Agent
            };
            var authResponse = new
            {
                token = TokenHandler.CreateToken(userViewModel, _configuration),
                agent = _mapper.Map <AgentViewModel>(agent)
            };

            return(Response(authResponse));
        }
Пример #14
0
        public ActionResult <DtoUser> Post(Refresh refresh)
        {
            try
            {
                var redisManager = new RedisCacheManager();

                _logger.LogInformation("refresh istegi geldi...");

                var tokens = new JwtSecurityToken(jwtEncodedString: refresh.authToken);

                var userId = tokens.Claims.First(c => c.Type == "unique_name").Value;

                var session = redisManager.Get(userId);

                if (session == null)
                {
                    return(BadRequest());
                }

                if (!refresh.authToken.Equals(session))
                {
                    return(Forbid());
                }

                var user = _userContext.users.FirstOrDefault(u => u.id.Equals(long.Parse(userId)) && u.refreshtoken.Equals(refresh.refreshToken));

                if (user == null)
                {
                    return(Forbid());
                }

                if (user.refreshtokenexpirationdate > DateTime.Now)
                {
                    TokenHandler tokenHandler = new TokenHandler();
                    Token        token        = tokenHandler.CreateAccessToken(user.id);

                    user.refreshtoken = token.RefreshToken;

                    _userContext.SaveChanges();

                    redisManager.Remove(user.id.ToString());
                    redisManager.Set(user.id.ToString(), token.AccessToken, 300);

                    return(Ok(new DtoUser
                    {
                        authToken = token.AccessToken,
                        name = user.name,
                        surname = user.surname,
                        refreshToken = token.RefreshToken
                    }));
                }

                return(Forbid());
            }
            catch (Exception e)
            {
                _logger.LogError(e.ToString());
                return(BadRequest());
            }
        }
Пример #15
0
        static void Main(string[] args)
        {
            Console.WriteLine("Please enter a directory relative to this program:");
            var inputDirectory = Console.ReadLine();
            var directory      = Environment.CurrentDirectory + inputDirectory;

            Console.WriteLine(directory);

            if (!CheckDirectory(directory))
            {
                return;
            }

            //Initialize DB
            using (var connection = new SqlConnection())
            {
                var client = new DBClient(connection);
                client.Initialize();
            }

            //Gather a list of file paths from directory.
            documents = Directory.EnumerateFiles(directory, "*.txt").ToList();

            Console.WriteLine("Using {0} threads to process {1} files", threads, documents.Count);
            var stopwatch = Stopwatch.StartNew();

            var handler = new TokenHandler(documents, threads);

            handler.Run();

            stopwatch.Stop();
            Console.WriteLine($"Elapsed time: {stopwatch.ElapsedMilliseconds}ms");
        }
Пример #16
0
        public ActionResult Delete(int Id)
        {
            try
            {
                Order Order = OrderRepository.Get(Id);
                if (Order == null)
                {
                    return(NotFound());
                }

                Event Event = EventRepository.Get(Id);
                if (Event == null)
                {
                    return(BadRequest("Event not found."));
                }

                //Event Owner / Admin allowed to update order
                string Token = Request.Headers["Authorization"].ToString().Replace("Bearer ", "");
                if (!TokenHandler.IsUserAllowed(Event.UserId, Token))
                {
                    return(Unauthorized());
                }

                OrderRepository.Delete(Id);
                OrderRepository.Save();

                return(Ok("Record Deleted"));
            }
            catch (Exception) { return(BadRequest("Record can not be deleted")); }
        }
        public virtual JwtToken Create(BaseValidatingContext baseValidatingContext, JwtServerOptions jwtServerOptions)
        {
            if (baseValidatingContext == null)
            {
                throw new ArgumentNullException(nameof(baseValidatingContext));
            }
            if (jwtServerOptions == null)
            {
                throw new ArgumentNullException(nameof(jwtServerOptions));
            }

            var tokenHadler  = new TokenHandler(jwtServerOptions);
            var startingDate = DateTime.UtcNow;
            var expiresDate  = DateTime.UtcNow.Add(jwtServerOptions.AccessTokenExpireTimeSpan);

            var token = tokenHadler.GenerateToken(
                claims: baseValidatingContext.Claims,
                notBefore: startingDate,
                expires: expiresDate);

            var result = new JwtToken
            {
                AccessToken = token,
                ExpiresIn   = this.GetTokenExpiral(startingDate, expiresDate),
                TokenType   = JwtBearerDefaults.AuthenticationScheme
            };

            return(result);
        }
        private async void GetLogonDetailsFromRemoteDBAsync()
        {
            try
            {
                CreateNewHandledTokenSource("NativeFacebookPageViewModel.GetLogonDetailsFromRemoteDBAsync", 20);

                var clientFromRemote = await Task.Run(async() =>
                {
                    var _clientFromRemote = await _userManager.GetContact(this.FacebookEmail, this.FacebookId, true);
                    return(_clientFromRemote);
                }, TokenHandler.Token);

                if (clientFromRemote != null)
                {
                    GetLogonDetailsFromRemoteDBResult(clientFromRemote, TokenHandler.IsTokenSourceCompleted());
                }
                else
                {
                    await GetLogonDetailsFromRemoteDBWrongResult(TokenHandler.IsTokenSourceCompleted());
                }
            }
            catch (Exception ex)
            {
                ProcessErrorReportingForHockeyApp(ex);
                await GetLogonDetailsFromRemoteDBWrongResult(true);
            }
        }
Пример #19
0
        private async void DeviceIdButton_OnClicked(object sender, EventArgs e)
        {
            TokenHandler th       = new TokenHandler();
            string       deviceId = await th.GetDeviceId();

            TextBox.Text = deviceId;
        }
Пример #20
0
        public void TakeRefreshToken_ReturnsRefreshTokenAfterRemovingIt_WhenTokenExists()
        {
            //Arrange
            mockPasswordHasher = new Mock <IPasswordHasher>();
            mockPasswordHasher.Setup(s => s.HashPassword(It.IsAny <string>())).Returns("test");
            TokenHandler tokenHandler = new TokenHandler(GetFakeConfigs(), new SigningConfigurations(), mockPasswordHasher.Object);
            User         user         = new User
            {
                Email     = "[email protected]",
                Password  = "******",
                UserRoles = new List <UserRole> {
                    new UserRole()
                    {
                        Role = new Role()
                        {
                            Name = "Common"
                        }
                    }
                }
            };
            var accessToken = tokenHandler.CreateAccessToken(user);

            //Act
            var result = tokenHandler.TakeRefreshToken("test");

            //Assert
            var refreshToken = Assert.IsAssignableFrom <RefreshToken>(result);

            Assert.NotNull(refreshToken);
            Assert.Equal(refreshToken, accessToken.RefreshToken);
        }
Пример #21
0
        private async void TokenButton_OnClicked(object sender, EventArgs e)
        {
            TokenHandler th    = new TokenHandler();
            string       token = await th.GetToken();

            TextBox.Text = token;
        }
        private List <OperatingState> GetOperatingStates()
        {
            Console.WriteLine("Welcome to the get all operating states example!" + Environment.NewLine);

            Console.WriteLine("Determine token ..." + Environment.NewLine);

            TokenHandler tokenHandler = new TokenHandler(_user, _password, _urlForTokenGeneration);
            Token        token        = tokenHandler.GetAccessToken();

            Console.WriteLine("Token: " + token.Access_token + Environment.NewLine);

            Console.WriteLine("Determine operating states ..." + Environment.NewLine);

            FORCEBridgeConnector connector = new FORCEBridgeConnector(_urlToBridgeAPI, token);
            var states = connector.GetOperatingStates();

            var result = new List <OperatingState>();

            foreach (var item in states)
            {
                result.Add(new OperatingState()
                {
                    Code = item.Code, Description = item.Description, Color = item.Color, ShortDescription = item.ShortDescription
                });
            }
            return(result);
        }
Пример #23
0
        public void CreateAccessToken_ReturnsAccessToken_WhenTokenCreated()
        {
            //Arrange
            mockPasswordHasher = new Mock <IPasswordHasher>();
            mockPasswordHasher.Setup(a => a.HashPassword(It.IsAny <string>())).Returns("test");
            TokenHandler tokenHandler = new TokenHandler(GetFakeConfigs(), new SigningConfigurations(), mockPasswordHasher.Object);
            User         user         = new User
            {
                Email     = "[email protected]",
                Password  = "******",
                UserRoles = new List <UserRole> {
                    new UserRole()
                    {
                        Role = new Role()
                        {
                            Name = "Common"
                        }
                    }
                }
            };

            //Act
            var result = tokenHandler.CreateAccessToken(user);

            //Assert
            var accessToken = Assert.IsAssignableFrom <AccessToken>(result);
        }
Пример #24
0
        public IHttpActionResult GetUser(int id)
        {
            var    r    = Request;
            var    th   = new TokenHandler();
            string key  = r.Headers.Contains("key") ? r.Headers.GetValues("key").First() : "";
            User   user = db.Users.Find(id);

            if (string.IsNullOrEmpty(key))
            {
                return(BadRequest("Access key is required!"));
            }

            var token = th.GetValidToken(key);

            if (user == null)
            {
                if (th.IsTokenValidAdmin(key))
                {
                    return(NotFound());
                }
            }
            else if (th.IsTokenValidAdmin(key) || (token != null && token.User.Id == user.Id))
            {
                return(Ok(user));
            }

            return(Unauthorized());
        }
        private List <Workplace> GetWorkplaces()
        {
            Console.WriteLine("Welcome to the get all available workplaces sample!" + Environment.NewLine);

            Console.WriteLine("Determine token ..." + Environment.NewLine);

            TokenHandler tokenHandler = new TokenHandler(_user, _password, _urlForTokenGeneration);
            Token        token        = tokenHandler.GetAccessToken();

            Console.WriteLine("Token: " + token.Access_token + Environment.NewLine);

            Console.WriteLine("Determine workplaces ..." + Environment.NewLine);

            FORCEBridgeConnector connector = new FORCEBridgeConnector(_urlToBridgeAPI, token);
            var workplaces = connector.GetWorkplaces();

            var result = new List <Workplace>();

            foreach (var item in workplaces)
            {
                result.Add(new Workplace()
                {
                    Id = item.Id, Number = item.Number, Description = item.Description, OperatingStateCode = item.OperatingState.Code, OperatingStateDescription = item.OperatingState.Description
                });
            }
            return(result);
        }
Пример #26
0
        protected override void DoExecute()
        {
            TokenHandler tokenHandler = LegacyLogic.Instance.WorldManager.Party.TokenHandler;

            tokenHandler.RemoveToken(m_tokenID);
            FinishExecution();
        }
        public async Task <IActionResult> Index(LoginModel model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var userControl = await _userManager.FindByEmailAsync(model.Email);

                    if (userControl == null)
                    {
                        return(NotFound(new { Message = "Böyle bir kullanıcı bulunamadı!", IsSuccess = false }));
                    }

                    var result = await _signInManager.PasswordSignInAsync(userControl, model.Password, false, false);

                    if (result.Succeeded)
                    {
                        var tokenHandler = new TokenHandler(_configuration);
                        var user         = tokenHandler.CreateToken(model);
                        if (user != null)
                        {
                            return(Ok(user));
                        }
                        return(BadRequest(new { Message = "Token oluşturulamadı!", IsSuccess = false }));
                    }

                    return(BadRequest(new { Message = "Kullanıcı adı veya şifre hatalı!", IsSuccess = false }));
                }
                return(BadRequest(new { Message = "Hata oluştu!", IsSuccess = false }));
            }
            catch (Exception ex)
            {
                return(Ok(new { Message = $"Hata: {ex.Message}", IsSuccess = false }));
            }
        }
Пример #28
0
        public IActionResult Token([FromBody] LoginDTO login)
        {
            string token;
            object response;

            CreateDefaults();



            try
            {
                User u = _users.GetAll().Where(p => p.Mail.Equals(login.Mail) && p.Password.Equals(Cryptography.Hash(login.Password))).FirstOrDefault();
                if (u == null)
                {
                    throw new InvalidCredentialException();
                }



                token    = TokenHandler.GenerateToken(u);
                response = new { authenticated = true, token = token, id = u.Id.ToString() };
            }
            catch (InvalidCredentialException)
            {
                response = new { authenticated = false };

                HttpContext.Response.StatusCode = 401;
                return(new ObjectResult(response));
            }



            return(Ok(response));
        }
Пример #29
0
        private void CheckForQuestProgress()
        {
            TokenHandler tokenHandler = LegacyLogic.Instance.WorldManager.Party.TokenHandler;

            if (m_killedCoreMonsters >= 10 && tokenHandler.GetTokens(557) == 0)
            {
                tokenHandler.AddToken(557);
            }
            else if (m_killedCoreMonsters >= 20 && tokenHandler.GetTokens(558) == 0)
            {
                tokenHandler.AddToken(558);
            }
            else if (m_killedCoreMonsters >= 30 && tokenHandler.GetTokens(559) == 0)
            {
                tokenHandler.AddToken(559);
            }
            else if (m_killedCoreMonsters >= 40 && tokenHandler.GetTokens(560) == 0)
            {
                tokenHandler.AddToken(560);
            }
            else if (m_killedCoreMonsters >= 50 && tokenHandler.GetTokens(561) == 0)
            {
                tokenHandler.AddToken(561);
            }
        }
Пример #30
0
        public IEnumerable <Claim> GetClaimsFromToken(string token)
        {
            var jwtToken = TokenHandler.ReadJwtToken(token);

            // Check validity

            return(jwtToken.Claims);
        }
Пример #31
0
 /**
  * @param tokenHandler
  * @param newAttributesEachTime
  */
 public ErrorReportingTokenizer(TokenHandler tokenHandler, bool newAttributesEachTime)
     : base(tokenHandler, newAttributesEachTime)
 {
 }
Пример #32
0
 public static TokenHandler GetInstance()
 {
     if (instance == null) { instance = new TokenHandler(); }
     return instance;
 }
Пример #33
0
 /**
  * @param tokenHandler
  */
 public ErrorReportingTokenizer(TokenHandler tokenHandler)
     : base(tokenHandler)
 {
 }