public void GenerateJwtToken_UserName_WithoutException()
        {
            //Act
            var token = _jwtManager.GenerateJwtToken("a.b", DateTime.Now.AddMinutes(5));
            var user  = _jwtManager.ValidateAndGetUserName(token);

            //Assert
            token.ShouldNotBeNullOrEmpty();
            user.ShouldNotBeEmpty();
        }
        public IActionResult GetAccessToken(string code, string state)
        {
            if (!string.IsNullOrEmpty(code) && !string.IsNullOrEmpty(state))
            {
                OAuthManager oauthManager = new OAuthManager(_logger);

                AccessTokenResponse response = oauthManager.GetAccessTokenAsync(
                    new AccessTokenRequest()
                {
                    ClientId     = _configuration.GetValue(ConfigurationKey.CLIENT_ID),
                    ClientSecret = _configuration.GetValue(ConfigurationKey.CLIENT_SECRET),
                    RedirectUri  = state,
                    Code         = code
                })
                                               .Result;

                if (response != null && response.access_token != null)
                {
                    UsersGetResponse userInfo = oauthManager.GetUserInfoAsync(response.access_token).Result;

                    if (userInfo != null && userInfo.response != null)
                    {
                        _logger.LogWarning(JsonConvert.SerializeObject(
                                               new
                        {
                            info = userInfo
                        }
                                               ));

                        HttpContext.Response.Cookies.Append("access_token", _jwtManager.GenerateJwtToken(userInfo));
                        return(Redirect("/"));
                    }

                    _logger.LogError(JsonConvert.SerializeObject(
                                         new
                    {
                        error = "Invalid user info"
                    }
                                         ));
                }

                _logger.LogError(JsonConvert.SerializeObject(
                                     new
                {
                    error = "Can't get access token"
                }
                                     ));
            }

            return(Unauthorized());
        }
Example #3
0
        public async Task CreateRoom(string roomName, string roomPassword)
        {
            var roomInternalModel = new RoomInternalModel
            {
                Name     = roomName,
                Password = roomPassword
            };

            var roomId = _roomRepository.AddRoom(roomInternalModel);

            _logger.LogInformation("Created room {roomId} {roomName}", roomId, roomName);

            var token = _jwtManager.GenerateJwtToken(roomId);
            await Clients.Caller.SendAsync(QuizHubMethods.RoomCreateSuccess, token, roomId);

            await Clients.All.SendAsync(QuizHubMethods.RoomCreated, roomInternalModel.ToDisplayModel());
        }
Example #4
0
            public Task <AuthenticationVm> Handle(AuthenticateCommand request, CancellationToken cancellationToken)
            {
                List <Claim> claims = new List <Claim>();

                //user 1
                string username1 = "user1";
                string password1 = "password1";

                if (request.Username == username1 && request.Password == password1)
                {
                    claims.AddRange(SetUserClaims(username1));
                }

                //user 2
                string username2 = "user2";
                string password2 = "password2";

                if (request.Username == username2 && request.Password == password2)
                {
                    claims.AddRange(SetUserClaims(username2));
                }

                //user 3
                string username3 = "user3";
                string password3 = "password3";

                if (request.Username == username3 && request.Password == password3)
                {
                    claims.AddRange(SetUserClaims(username3));
                }

                if (claims.Count < 1)
                {
                    throw new Exception("Invalid username/password");
                }

                AuthenticationVm vm = new AuthenticationVm
                {
                    Scheme = "Bearer",
                    Token  = _jwtManager.GenerateJwtToken(claims),
                    UserId = claims.Find(x => x.Type == ClaimTypes.NameIdentifier).Value,
                    Name   = claims.Find(x => x.Type == ClaimTypes.Name).Value
                };

                return(Task.FromResult(vm));
            }
Example #5
0
        //[ValidateAntiForgeryToken]
        public async Task <IActionResult> Login(LoginViewModel model, string returnUrl = null, string codeaccess = null)
        {
            ViewData["ReturnUrl"] = returnUrl;
            if (ModelState.IsValid)
            {
                // This doesn't count login failures towards account lockout
                // To enable password failures to trigger account lockout, set lockoutOnFailure: true
                var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure : false);

                if (result.Succeeded)
                {
                    _logger.LogInformation("User logged in.");

                    var appUser = _userManager.Users.SingleOrDefault(r => r.Email == model.Email);

                    var tokenManager             = new JwtManager();
                    var expirationTokenInMinutes = 180;

                    var token = tokenManager.GenerateJwtToken(model.Email, appUser.Id, expirationTokenInMinutes);

                    var todo = _context.BotLogin.ToList();

                    var newBotLogin = new BotLogin();
                    newBotLogin.ExpirationTime = DateTime.UtcNow.AddMinutes(Convert.ToDouble(expirationTokenInMinutes));
                    newBotLogin.Jwt            = token;
                    newBotLogin.UserName       = model.Email;

                    if (model.Email.ToLower() == "*****@*****.**")
                    {
                        newBotLogin.SkypeUserName = "******";
                    }

                    if (model.Email.ToLower() == "*****@*****.**")
                    {
                        newBotLogin.SkypeUserName = "******";
                    }

                    if (model.Email.ToLower() == "*****@*****.**")
                    {
                        newBotLogin.SkypeUserName = "******";
                    }

                    _context.BotLogin.Add(newBotLogin);
                    _context.SaveChanges();

                    var botService = new BotService();

                    var userData = _context.BotProactiveMessage.Where(botProactiveMessage => botProactiveMessage.UserName == newBotLogin.SkypeUserName).FirstOrDefault();

                    var botuserDataDto = new BotUserDataDto {
                        BotConversationId  = userData.FromID,
                        UserConversationId = userData.Conversation,
                        BotName            = userData.FromName,
                        UserName           = userData.UserName,
                        ChannelId          = userData.ChannelId
                    };

                    await botService.SendBotMessage("El usuario ha sido autenticado", botuserDataDto);

                    return(RedirectToAction("LoginSucceded"));
                }
                if (result.RequiresTwoFactor)
                {
                    return(RedirectToAction(nameof(LoginWith2fa), new { returnUrl, model.RememberMe }));
                }
                if (result.IsLockedOut)
                {
                    _logger.LogWarning("User account locked out.");
                    return(RedirectToAction(nameof(Lockout)));
                }
                else
                {
                    ModelState.AddModelError(string.Empty, "Invalid login attempt.");
                    return(View(model));
                }
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
        public async Task <bool> CheckOneTimePassword([FromBody] OtpCodeDto otpCodeDto)
        {
            var secretkey = string.Empty;
            var email     = string.Empty;
            var userId    = string.Empty;


            if (otpCodeDto.ChannelId == "sms")
            {
                var smsUser = this._context.SmsUser.Where(smsuser => smsuser.UserName == otpCodeDto.UserName).FirstOrDefault();

                if (smsUser == null)
                {
                    return(false);
                }

                secretkey = smsUser.SecretKey;
                email     = smsUser.EMail;
                userId    = smsUser.UserId;
            }

            if (otpCodeDto.ChannelId == "directline")
            {
                var directLineUser = this._context.DirectLineUser.Where(smsuser => smsuser.UserName == otpCodeDto.UserName).FirstOrDefault();

                if (directLineUser == null)
                {
                    return(false);
                }

                secretkey = directLineUser.SecretKey;
                email     = directLineUser.EMail;
                userId    = directLineUser.UserId;
            }

            int otpDigits = 6;

            var secretKey = secretkey;

            Key key    = new Key(secretKey);
            var secret = key.Base32;

            TimeBasedOtpGenerator otp = new TimeBasedOtpGenerator(key, otpDigits);
            var time      = GetNistTime();
            var tst       = otp.GenerateOtp(time);
            Key keySecret = new Key(secretKey);

            time = GetNistTime();

            TimeBasedOtpGenerator otp3 = new TimeBasedOtpGenerator(keySecret, otpDigits);

            var valid = otp.ValidateOtp(otpCodeDto.OneTimePasswordCode, time);

            if (valid)
            {
                var jwtoken        = new JwtManager();
                var expirationTime = DateTime.UtcNow.AddMinutes(59);
                var jwt            = jwtoken.GenerateJwtToken(email, userId, 60);

                if (otpCodeDto.ChannelId == "sms")
                {
                    _context.SmsLogin.Add(new Data.Entities.SmsLogin {
                        UserName = otpCodeDto.UserName, ExpirationTime = expirationTime, Jwt = jwt
                    });
                    _context.SaveChanges();
                }

                if (otpCodeDto.ChannelId == "directline")
                {
                    _context.DirectLineLogins.Add(new Data.Entities.DirectLineLogins {
                        UserName = otpCodeDto.UserName, ExpirationTime = expirationTime, Jwt = jwt.ToString()
                    });
                    _context.SaveChanges();
                }
            }

            return(valid);
        }