Exemplo n.º 1
0
        public void T01_AuthRequestDto()
        {
            AuthRequestDto dto = new AuthRequestDto();

            Assert.IsFalse(dto.IsComplete(), "empty dto");

            dto.ApId = "http://changeme.swisscom.ch";
            Assert.AreEqual("http://changeme.swisscom.ch", dto.ApId, "ApId");
            Assert.IsFalse(dto.IsComplete(), "dto(ApId) incomplete");

            try
            {
                dto.PhoneNumber = "";
                Assert.Fail("PhoneNumber('')");
            }
            catch (Exception e)
            {
                Assert.IsTrue(e.GetType() == typeof(ArgumentNullException), "Expect ArgumentNullException on empty PhoneNumber");
            }

            try
            {
                dto.PhoneNumber = "garbarge";
                Assert.Fail("PhoneNumber('garbarge')");
            }
            catch (Exception e)
            {
                Assert.IsTrue(e.GetType() == typeof(ArgumentException), "Expect ArgumentException on garbarge PhoneNumber");
                Assert.AreEqual("PhoneNumberIsIllFormed: 'garbarge'", e.Message, "Expect PhoneNumberIsIllFormed on garbarge PhoneNumber");
            }

            dto.PhoneNumber = "+41791234567";
            Assert.AreEqual("+41791234567", dto.PhoneNumber, "dto.PhoneNumber");
            Assert.IsFalse(dto.IsComplete(), "dto(ApId,PhoneNumber) incomplete");
        }
Exemplo n.º 2
0
        private async Task <User> GetUserByRefreshToken(AuthRequestDto authRequestDto)
        {
            if (string.IsNullOrWhiteSpace(authRequestDto?.Email) || string.IsNullOrWhiteSpace(authRequestDto?.RefreshToken))
            {
                return(null);
            }

            var storedToken = cache.GetString(authRequestDto.RefreshToken);

            if (string.IsNullOrWhiteSpace(storedToken))
            {
                return(null);
            }

            var refreshTokenDataStored = JsonConvert.DeserializeObject <RefreshTokenData>(storedToken);

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

            if (authRequestDto.Email == refreshTokenDataStored.Email && authRequestDto.RefreshToken == refreshTokenDataStored.RefreshToken)
            {
                return(await GetUserByEmail(authRequestDto));
            }

            return(null);
        }
        public void TestAuthenticate_BadRequest_WhenValidRequest()
        {
            // Arrange
            AuthRequestDto authRequest = new AuthRequestDto()
            {
                UserName = "******",
                Password = "******"
            };
            AuthReponseDto authReponseDto = new AuthReponseDto
            {
                AccessToken = "test",
                ExpireIn    = 10,
                UserName    = "******",
                UserRole    = "Privilaged"
            };
            Mock <IUserService> userServiceMock = new Mock <IUserService>();

            userServiceMock.Setup(x => x.AuthenticateUser(It.IsAny <AuthRequestDto>())).Returns(authReponseDto);
            UserController userController = new UserController(userServiceMock.Object);

            // Act
            var result = userController.Authenticate(authRequest);

            // Assert
            Assert.NotNull(result);
            Assert.IsType <OkObjectResult>(result);
        }
Exemplo n.º 4
0
        public async Task <IActionResult> Auth([FromBody] AuthRequestDto authRequestDto)
        {
            UserTokenDto userToken = await _accountService.Auth(authRequestDto.Login, authRequestDto.Password);

            await _unitOfWork.CommitAsync();

            return(Ok(userToken));
        }
Exemplo n.º 5
0
        public AuthDto AuthenticateUser(AuthRequestDto authRequest)
        {
            /*Validar datos*/
            var user = _dbContext.Users.FirstOrDefault(u => u.Email == authRequest.Email && u.Password == PasswordHelper.GetHashFromString(authRequest.Password));

            if (user == null)
            {
                throw new AuthenticationInvalidException();
            }
            return(new AuthDto {
                Token = TokenHelper.GenerateToken(user.UserId, user.Role)
            });
        }
Exemplo n.º 6
0
        static void Main(string[] args)
        {
            var sessionApi        = new SessionApi();
            var credentials       = new AuthRequestDto("user", 261, "password");
            var sessionId         = sessionApi.Login(credentials).SessionId;
            var synthesizeApi     = new SynthesizeApi();
            var synthesizeText    = new SynthesizeText("text/plain", "Hello world");
            var synthesizeRequest = new SynthesizeRequest(synthesizeText, "Carol", "audio/wav");
            var synthesizedSound  = synthesizeApi.Synthesize(Guid.Parse(sessionId), synthesizeRequest).Data;
            var soundBytes        = Convert.FromBase64String(synthesizedSound);

            File.WriteAllBytes("F:\\Cloud\\tts\\testWav.wav", soundBytes);
        }
Exemplo n.º 7
0
        static void Main(string[] args)
        {
            var sessionApi                 = new SessionApi();
            var startSession               = new AuthRequestDto("user", 261, "password");
            var response                   = sessionApi.Login(startSession);
            var sessionId                  = response.SessionId;
            var recognizeApi               = new RecognizeApi();
            var soundBytes                 = File.ReadAllBytes("F:\\Art\\pcm\\0068_20170407_own_6944_181007-1496930080.wav");
            var audio                      = new AudioFileDto(soundBytes, "audio/x-wav");
            var recognitionRequest         = new RecognitionRequestDto(audio, "FarField");
            var recognitionRequestResponse = recognizeApi.RecognizeWords(Guid.Parse(sessionId), recognitionRequest);

            recognitionRequestResponse.ForEach(Console.WriteLine);
        }
Exemplo n.º 8
0
        public void T02_AuthRequestDto_ToString()
        {
            AuthRequestDto dto = new AuthRequestDto();

            Assert.AreEqual("{ApId:null, Instant:null, MsgToBeSigned:null, PhoneNumber:null, TimeOut:80, TransId:null, TransIdPrefix:\"\", SrvSideValidation:False, UserLanguage:en, UserSerialNumber:}", dto.ToString(), "ToString(empty_dto)");

            dto.ApId           = "http://changeme.swisscom.ch";
            dto.PhoneNumber    = "+41791234567";
            dto.DataToBeSigned = "Hello, Mobile ID";
#if DEBUG
            Console.WriteLine("dto.Length=" + dto.ToString().Length);
#endif
            Assert.AreEqual("{ApId:\"http://changeme.swisscom.ch\", Instant:null, MsgToBeSigned:\"Hello, Mobile ID\", PhoneNumber:\"+41791234567\", TimeOut:80, TransId:null, TransIdPrefix:\"\", SrvSideValidation:False, UserLanguage:en, UserSerialNumber:}", dto.ToString(), "ToString(minimal_valid_dto)");
        }
Exemplo n.º 9
0
        static void Main(string[] args)
        {
            var sessionApi          = new SessionApi();
            var startSession        = new AuthRequestDto("user", 261, "password");
            var response            = sessionApi.Login(startSession);
            var sessionId           = response.SessionId;
            var diarizationApi      = new DiarizationApi();
            var sound               = File.ReadAllBytes("F:\\Cloud\\diarization\\8khz.wav");
            var audio               = new AudioDto(sound);
            var diarizationResponse = diarizationApi.Diarization(Guid.Parse(sessionId), audio);
            var speakers            = diarizationResponse.Speakers;

            speakers.ForEach(Console.WriteLine);
        }
        public async Task <IActionResult> Login([FromBody] AuthRequestDto pUthRequest)
        {
            try
            {
                var response = await _usuarioApplication.Login(pUthRequest);

                _logger.LogInformation(response.Message, response);
                return(Ok(response));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, ex.Message);
                return(BadRequest());
            }
        }
        public void TestAuthenticate_BadRequest_WhenInvalidRequest()
        {
            // Arrange
            AuthRequestDto authRequest = new AuthRequestDto()
            {
                Password = "******",
                UserName = "******"
            };
            Mock <IUserService> userServiceMock = new Mock <IUserService>();

            userServiceMock.Setup(x => x.AuthenticateUser(It.IsAny <AuthRequestDto>())).Throws(new UnauthorizedAccessException("Invalid Username"));
            UserController userController = new UserController(userServiceMock.Object);

            // Act and Assert
            Assert.Throws <UnauthorizedAccessException>(() => userController.Authenticate(authRequest));
        }
Exemplo n.º 12
0
        public AuthResponseDto AuthenticateUser(AuthRequestDto request)
        {
            var user = UsersDataSource.GetUsers.FirstOrDefault(a => a.Username == request.Username && a.Password == request.Password);

            if (user != null)
            {
                return(new AuthResponseDto
                {
                    ClientSecret = user.ClientSecret,
                    IsSuccess = true
                });
            }
            return(new AuthResponseDto {
                IsSuccess = false
            });
        }
Exemplo n.º 13
0
        public AuthReponseDto AuthenticateUser(AuthRequestDto authRequest)
        {
            User user = _userRepository.GetUser(authRequest.UserName);

            if (user == null)
            {
                throw new UnauthorizedAccessException("User doesnt exist");
            }
            else if (!user.IsActive)
            {
                throw new UnauthorizedAccessException("User is not active");
            }
            else if (!user.Password.Equals(authRequest.Password))
            {
                throw new UnauthorizedAccessException("Invalid Username or Password");
            }

            var claims = new List <Claim>()
            {
                new Claim(ClaimTypes.Name, user.Name),
                new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
                new Claim(ClaimTypes.Role, user.UserRole.Id.ToString())
            };

            var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["AuthenticationSetting:SecretKey"]));
            var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);

            var token = new JwtSecurityToken(
                issuer: _configuration["AuthenticationSetting:Issuer"],
                audience: _configuration["AuthenticationSetting:Audience"],
                signingCredentials: credentials,
                claims: claims,
                expires: DateTime.Now.AddMinutes(120)
                );

            return(new AuthReponseDto
            {
                AccessToken = new JwtSecurityTokenHandler().WriteToken(token),
                UserName = user.Name,
                UserRole = user.UserRole.Name
            });
        }
Exemplo n.º 14
0
        public async Task <IActionResult> Post([FromBody] AuthRequestDto authRequestDto)
        {
            var user = await GetUserByEmailAndPassword(authRequestDto);

            if (user == null)
            {
                user = await GetUserByRefreshToken(authRequestDto);
            }

            if (user == null)
            {
                return(StatusCode((int)HttpStatusCode.Forbidden, new AuthResultDto {
                    Authenticated = false, Message = "Authentication failed!"
                }));
            }

            var result = AuthConfigHelper.GenerateToken(user, appSettings, cache, signingConfigurations);

            return(Response(result));
        }
Exemplo n.º 15
0
        public async Task Post_Should_Return_UnAuthorized()
        {
            var            client         = _factory.CreateClient();
            AuthRequestDto authRequestDto = new AuthRequestDto()
            {
                Password = "******",
                UserName = "******"
            };
            string obj = JsonConvert.SerializeObject(authRequestDto);

            var httpRequest = new HttpRequestMessage(HttpMethod.Post, "/api/user/authenticate")
            {
                Content = new StringContent(obj, Encoding.UTF8, "application/json")
            };

            var response = await client.SendAsync(httpRequest);

            Assert.NotNull(response);
            Assert.Equal(System.Net.HttpStatusCode.Unauthorized, response.StatusCode);
        }
Exemplo n.º 16
0
        public void Get_Forbidden_When_User_Not_Active()
        {
            // Arrange
            var configuration = LocalConfiguration.GetConfiguration();
            var repository    = new Mock <IUserRepository>();

            User user = null;

            repository.Setup(x => x.GetUser(It.IsAny <string>())).Returns(user);

            //Act
            AuthRequestDto authRequest = new AuthRequestDto
            {
                Password = "******",
                UserName = "******"
            };
            var target = new UserService(repository.Object, configuration);

            // Assert
            Assert.Throws <UnauthorizedAccessException>(() => target.AuthenticateUser(authRequest));
        }
Exemplo n.º 17
0
        private async Task <User> GetUserByEmailAndPassword(AuthRequestDto authRequestDto)
        {
            if (string.IsNullOrWhiteSpace(authRequestDto?.Email) || string.IsNullOrWhiteSpace(authRequestDto?.Password))
            {
                return(null);
            }

            var user = await GetUserByEmail(authRequestDto);

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

            if (user.CheckPassword(authRequestDto.Password))
            {
                return(user);
            }

            return(null);
        }
Exemplo n.º 18
0
        public void GetUserTest()
        {
            // Arrange
            var      configuration = LocalConfiguration.GetConfiguration();
            var      repository    = new Mock <IUserRepository>();
            UserRole userRole      = new UserRole
            {
                Id        = Guid.NewGuid(),
                Name      = "Privileged",
                IsActive  = true,
                CreatedOn = DateTime.Now
            };

            User user = new User
            {
                CreatedOn  = DateTime.Now,
                Id         = Guid.NewGuid(),
                IsActive   = true,
                Name       = "Mathew",
                Password   = "******",
                UserRole   = userRole,
                UserRoleId = userRole.Id
            };

            repository.Setup(x => x.GetUser(It.IsAny <string>())).Returns(user);

            //Act
            AuthRequestDto authRequest = new AuthRequestDto
            {
                Password = "******",
                UserName = "******"
            };
            var target = new UserService(repository.Object, configuration);
            var result = target.AuthenticateUser(authRequest);

            // Assert
            Assert.NotNull(result);
            Assert.Equal("Mathew", result.UserName);
            Assert.Equal("Privileged", result.UserRole);
        }
Exemplo n.º 19
0
        public void Get_Forbidden_When_User_Password_Not_Same()
        {
            // Arrange
            var configuration = LocalConfiguration.GetConfiguration();
            var repository    = new Mock <IUserRepository>();

            UserRole userRole = new UserRole
            {
                Id        = Guid.NewGuid(),
                Name      = "Privileged",
                IsActive  = true,
                CreatedOn = DateTime.Now
            };

            User user = new User
            {
                CreatedOn  = DateTime.Now,
                Id         = Guid.NewGuid(),
                IsActive   = false,
                Name       = "Mathew",
                Password   = "******",
                UserRole   = userRole,
                UserRoleId = userRole.Id
            };

            repository.Setup(x => x.GetUser(It.IsAny <string>())).Returns(user);

            //Act
            AuthRequestDto authRequest = new AuthRequestDto
            {
                Password = "******",
                UserName = "******"
            };
            var target = new UserService(repository.Object, configuration);

            // Assert
            Assert.Throws <UnauthorizedAccessException>(() => target.AuthenticateUser(authRequest));
        }
Exemplo n.º 20
0
        public AuthResponseDto Authenticate(AuthRequestDto request)
        {
            var user = _db.Users.FirstOrDefault((x => x.Email == request.Email));

            if (user == null)
            {
                throw new ResourceNotFoundException("User");
            }

            if (user.Password != request.Password)
            {
                _mailService.Send(user.Email, "Failed login attempt", "");
                throw new HttpException(HttpStatusCode.Unauthorized, "Wrong credentials");
            }

            // authentication successful so generate jwt token
            var token = generateJwtToken(user);

            return(new AuthResponseDto
            {
                Token = token,
                User = _mapper.Map <UserResponseDto>(user)
            });
        }
Exemplo n.º 21
0
        public async Task <Response <AuthResponseDto> > Login(AuthRequestDto authRequestDto)
        {
            AuthRequestEntities authRequest = _mapper.Map <AuthRequestEntities>(authRequestDto);
            var    response = new Response <AuthResponseDto>();
            string todo     = null;

            try
            {
                if (authRequestDto == null)
                {
                    response.IsSuccess   = false;
                    response.IsWarning   = true;
                    response.CodigoError = "0";
                    response.Message     = "Envio de parametros inválido,intente denuevo.";
                    return(response);
                }
                else if (string.IsNullOrEmpty(authRequestDto.Username) ||
                         string.IsNullOrEmpty(authRequestDto.Password))
                {
                    response.IsSuccess   = false;
                    response.IsWarning   = true;
                    response.CodigoError = "0";
                    response.Message     = "Envio de parametros inválido,intente denuevo.";
                    return(response);
                }

                //valida el usuario y password
                var responseData = await _usuarioDomain.Login(authRequest);

                response.Data = _mapper.Map <AuthResponseDto>(responseData);
                var ver = Convert.ToInt32(todo);

                if (response.Data == null)
                {
                    response.IsSuccess   = false;
                    response.IsWarning   = true;
                    response.CodigoError = "0";
                    response.Message     = "Usuario y/o contraseña incorrecta.";
                    return(response);
                }
                else
                {
                    response.Data.Token = JwtGenerator.CreateToken(_configuration,
                                                                   response.Data.UserName);
                    response.Message = "Inicio de sesión correctamente.";

                    //guardar sesion de usuario
                    var sesion = new SesionUsuarioDto
                    {
                        IdUser    = response.Data.Id,
                        Token     = response.Data.Token,
                        DateStart = DateTime.Now,
                        Status    = 1
                    };
                    var sesionUsuarioEntities = _mapper.Map <SesionUsuarioEntities>(sesion);
                    var responseSesion        = await _usuarioDomain.GuardarSesion(sesionUsuarioEntities);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return(response);
        }
Exemplo n.º 22
0
 public IActionResult Authenticate([FromBody] AuthRequestDto authRequest)
 {
     return(Ok(_userService.AuthenticateUser(authRequest)));
 }
Exemplo n.º 23
0
 public AuthDto Auth([FromBody] AuthRequestDto authRequest)
 {
     return(_authBusiness.AuthenticateUser(authRequest));
 }
Exemplo n.º 24
0
 private async Task <User> GetUserByEmail(AuthRequestDto authRequestDto) => await userRepository.FirstOrDefaultAsync(e => e.Email == authRequestDto.Email);
Exemplo n.º 25
0
 public IActionResult Login(AuthRequestDto requestDto)
 {
     return(Ok(_authService.AuthenticateUser(requestDto)));
 }
Exemplo n.º 26
0
        public async Task <AuthResultDto> Login([FromBody] AuthRequestDto authRequestDto)
        {
            var authResponse = await _securityService.LoginAsync(authRequestDto.UserName, authRequestDto.UserPassword);

            return(authResponse);
        }
Exemplo n.º 27
0
 public AuthResponseDto Post([FromBody] AuthRequestDto request)
 {
     return(_userService.Authenticate(request));
 }
Exemplo n.º 28
0
        // Authentication starts here, UPN of primary login is passed as Claim. Called once per ADFS-login-session.
        public IAdapterPresentation BeginAuthentication(Claim identityClaim, HttpListenerRequest reqHttp, IAuthenticationContext ctx)
        {
            logger.TraceEvent(TraceEventType.Verbose, 0, "BeginAuthentication(claim=" + _str(identityClaim) + ", req=" + _str(reqHttp) + ", ctx=" + _str(ctx) + ")");
            CultureInfo culture = new CultureInfo(ctx.Lcid);
            string      uiTrxId = MobileId.Util.BuildRandomBase64Chars(cfgAdfs.LoginNonceLength);
            bool        needCheckUserSerialNumber =
                !cfgMid.UserSerialNumberPolicy.HasFlag(UserSerialNumberPolicy.allowAbsence) ||
                !cfgMid.UserSerialNumberPolicy.HasFlag(UserSerialNumberPolicy.allowMismatch) ||
                cfgMid.UserSerialNumberPolicy.HasFlag(UserSerialNumberPolicy.warnMismatch);

            // Start the asynchrous login
            AuthRequestDto req = new AuthRequestDto();
            string         upn = identityClaim.Value; // for audit only

            try {
                req.PhoneNumber    = (string)ctx.Data[MSISDN];
                req.UserLanguage   = (UserLanguage)Enum.Parse(typeof(UserLanguage), resMgr.GetString(RES_LANG, culture));
                req.DataToBeSigned = _buildMobileIdLoginPrompt(req.UserLanguage, culture, uiTrxId);
                req.TimeOut        = cfgMid.RequestTimeOutSeconds;
                if (needCheckUserSerialNumber /* cfgMid.UserSerialNumberPolicy != UserSerialNumberPolicy.ignore */ && ctx.Data.ContainsKey(UKEYSN))
                {
                    req.UserSerialNumber = (string)ctx.Data[UKEYSN];
                }
            } catch (Exception e) {
                Logging.Log.ConfigError("upn:\"" + upn + "\", err:\"" + e.Message + "\"");
                throw e;
                // return new AdapterPresentation(AuthView.AuthError, cfgAdfs);
            }
            ctx.Data.Add(AUTHBEGIN, DateTime.UtcNow.Ticks / 10000);
            ctx.Data.Add(SESSBEGIN, DateTime.UtcNow.Ticks / 10000);
            AuthResponseDto rsp;

            try {
                rsp = getWebClient().RequestSignature(req, true /* async */);
            }
            catch (Exception e) {
                Logging.Log.AuthenticationTechnicalError(0, 0, upn, null, null, e.ToString());
                throw e;
                // return new AdapterPresentation(AuthView.AuthError, cfgAdfs);
            };
            ctx.Data.Add(SESSTRIES, 1);
            string logMsg = "svcStatus:" + (int)rsp.Status.Code + ", mssTransId:\"" + rsp.MsspTransId + "\", state:";

            switch (rsp.Status.Code)
            {
            case ServiceStatusCode.VALID_SIGNATURE:
            case ServiceStatusCode.SIGNATURE:
                ctx.Data.Add(STATE, 3);
                ctx.Data.Add(MSSPTRXID, rsp.MsspTransId);
                logger.TraceEvent(TraceEventType.Verbose, 0, logMsg + "3");
                Logging.Log.AuthenticationSuccess(0, 3, upn, rsp.MsspTransId);
                return(new AdapterPresentation(AuthView.TransferCtx, cfgAdfs));

            case ServiceStatusCode.REQUEST_OK:
                ctx.Data.Add(STATE, 1);
                ctx.Data.Add(MSSPTRXID, rsp.MsspTransId);
                ctx.Data.Add(DTBS, req.DataToBeSigned);
                logger.TraceEvent(TraceEventType.Verbose, 0, logMsg + "1");
                Logging.Log.AuthenticationContinue(0, 1, upn, rsp.MsspTransId);
                return(new AdapterPresentation(AuthView.SignRequestSent, cfgAdfs, req.PhoneNumber, uiTrxId, cfgMid.PollResponseDelaySeconds * 1000));

            case ServiceStatusCode.USER_CANCEL:
                ctx.Data.Add(STATE, 4);
                logger.TraceEvent(TraceEventType.Verbose, 0, logMsg + "4");
                Logging.Log.AuthenticationCancel(0, 4, upn, rsp.MsspTransId);
                return(new AdapterPresentation(AuthView.RetryOrCancel, cfgAdfs, rsp));

            case ServiceStatusCode.EXPIRED_TRANSACTION:     // reserved mobileid can return this status immdidately
            case ServiceStatusCode.PB_SIGNATURE_PROCESS:
                ctx.Data.Add(STATE, 5);
                logger.TraceEvent(TraceEventType.Verbose, 0, logMsg + "5");
                Logging.Log.AuthenticationFail(0, 5, upn, rsp.MsspTransId, Enum.GetName(typeof(ServiceStatusCode), rsp.Status.Code));
                return(new AdapterPresentation(AuthView.RetryOrCancel, cfgAdfs, rsp));

            default:
                ctx.Data.Add(STATE, 2);
                logger.TraceEvent((rsp.Status.Color == ServiceStatusColor.Yellow ? TraceEventType.Warning : TraceEventType.Error),
                                  0, logMsg + "2, errMsg:\"" + rsp.Status.Message + "\", errDetail:\"" + rsp.Detail + "\"");
                if (rsp.Status.Color == ServiceStatusColor.Yellow || rsp.Status.Color == ServiceStatusColor.Green)
                {
                    Logging.Log.AuthenticationFail(0, 2, upn, rsp.MsspTransId, Enum.GetName(typeof(ServiceStatusCode), rsp.Status.Code));
                }
                else
                {
                    Logging.Log.AuthenticationTechnicalError(0, 2, upn, rsp.MsspTransId, Enum.GetName(typeof(ServiceStatusCode), rsp.Status.Code), (string)rsp.Detail);
                }
                string s = rsp.Status.GetDisplayMessage(ctx.Lcid);
                if (String.IsNullOrEmpty(s))
                {
                    logger.TraceEvent(TraceEventType.Warning, 0, "resource undef for {mssCode:" + (int)rsp.Status.Code + ", lcid:" + ctx.Lcid + "}");
                    Logging.Log.PresentationWarning("RESOURCE_UNDEF", "{mssCode:" + (int)rsp.Status.Code + ", lcid:" + ctx.Lcid + "}");
                    s = (string)rsp.Detail;
                }
                ;
                return(new AdapterPresentation(AuthView.AuthError, cfgAdfs, rsp));
            }
        }
Exemplo n.º 29
0
        // Authentication should perform the actual authentication and return at least one Claim on success.
        // proofData contains a dictionnary of strings to objects that have been asked in the BeginAuthentication
        public IAdapterPresentation TryEndAuthentication(IAuthenticationContext ctx, IProofData proofData, System.Net.HttpListenerRequest request, out Claim[] claims)
        {
            string formAction, upn, msspTransId, logInfo;
            int    state;

            if (proofData.Properties.ContainsKey("Retry"))
            {
                formAction = "Retry";
            }
            else
            {
                try {
                    formAction = (string)proofData.Properties["Action"];
                } catch (KeyNotFoundException) {
                    formAction = null;
                }
            };
            //if (formAction == null && proofData.Properties.ContainsKey("SignOut")) {
            //    // if user modifies URL manually during a session, the Cancel action is not captured by ADFS but leaks to this method
            //    formAction = "SignOut";
            //};
            logger.TraceEvent(TraceEventType.Verbose, 0, "TryEndAuthentication(act:" + formAction + ", ctx:" + _str(ctx) + ", prf:" + _str(proofData) + ", req:" + _str(request));
            Logging.Log.TryEndAuthenticationStart(formAction, _str(ctx), _str(proofData), _str(request));
            CultureInfo culture = new CultureInfo(ctx.Lcid);

            upn   = (string)ctx.Data[USERUPN];
            state = (int)ctx.Data[STATE];
            try
            {
                // msspTransId is expected to be absent in some error cases, e.g. error 107
                msspTransId = (string)ctx.Data[MSSPTRXID];
            }
            catch (KeyNotFoundException)
            {
                msspTransId = null;
            };
            logInfo = "upn:\"" + upn + "\", msspTransId:\"" + msspTransId + "\"";

            claims = null;
            if (formAction == "Continue")
            {
                switch (state)
                {
                case 3:
                    logger.TraceEvent(TraceEventType.Information, 0, "AUTHN_OK: " + logInfo + ", state:" + state);
                    Logging.Log.AuthenticationSuccess(state, (int)ctx.Data[STATE], upn, msspTransId);
                    claims = ClaimsHwToken;
                    return(null);

                case 1:
                case 31:
                    // fall through for looping below
                    break;

                default:
                    logger.TraceEvent(TraceEventType.Error, 0, "BAD_STATE: " + logInfo + ", state:" + state);
                    Logging.Log.AuthenticationFail(state, (int)ctx.Data[STATE], upn, msspTransId, "BAD_STATE");
                    return(new AdapterPresentation(AuthView.AuthError, cfgAdfs, "action:\"Conitnue\"; state:" + state));
                }

                // check session age, i.e. timespan(Now, authBegin)
                int ageSeconds = (int)((DateTime.UtcNow.Ticks / 10000 - (long)ctx.Data[AUTHBEGIN]) / 1000);
                if (ageSeconds >= cfgMid.RequestTimeOutSeconds)
                {
                    ctx.Data[STATE] = 13;
                    logger.TraceEvent(TraceEventType.Information, 0, "AUTHN_TIMEOUT_CONT: " + logInfo + ", state:" + ctx.Data[STATE] + ", age:" + ageSeconds);
                    Logging.Log.AuthenticationTimeout(state, (int)ctx.Data[STATE], ageSeconds, upn, msspTransId);
                    return
                        (((int)ctx.Data[SESSTRIES] < cfgAdfs.SessionMaxTries) ?
                         new AdapterPresentation(AuthView.RetryOrCancel, cfgAdfs, "Timeout.") : // TODO: construct new ErrorCode for easier I18N
                         new AdapterPresentation(AuthView.AuthError, cfgAdfs, "Timeout."));
                }

                AuthRequestDto req = new AuthRequestDto();
                req.PhoneNumber    = (string)ctx.Data[MSISDN];
                req.DataToBeSigned = (string)ctx.Data[DTBS];
                bool needCheckUserSerialNumber =
                    !cfgMid.UserSerialNumberPolicy.HasFlag(UserSerialNumberPolicy.allowAbsence) ||
                    !cfgMid.UserSerialNumberPolicy.HasFlag(UserSerialNumberPolicy.allowMismatch) ||
                    cfgMid.UserSerialNumberPolicy.HasFlag(UserSerialNumberPolicy.warnMismatch);

                if (needCheckUserSerialNumber /* cfgMid.UserSerialNumberPolicy != UserSerialNumberPolicy.ignore */ && ctx.Data.ContainsKey(UKEYSN))
                {
                    req.UserSerialNumber = (string)ctx.Data[UKEYSN];
                }
                AuthResponseDto rsp;
                for (int i = ageSeconds; i <= cfgMid.RequestTimeOutSeconds; i += cfgMid.PollResponseIntervalSeconds)
                {
                    rsp = getWebClient().PollSignature(req, msspTransId);
                    switch (rsp.Status.Code)
                    {
                    case ServiceStatusCode.SIGNATURE:
                    case ServiceStatusCode.VALID_SIGNATURE:
                        ctx.Data[STATE] = 10;
                        logger.TraceEvent(TraceEventType.Information, 0, "AUTHN_OK: " + logInfo + ", state:" + ctx.Data[STATE] + ", i:" + i);
                        Logging.Log.AuthenticationSuccess(state, (int)ctx.Data[STATE], upn, msspTransId);
                        // EventLog.WriteEntry(EVENTLOGSource, "Authentication success for " + upn, EventLogEntryType.SuccessAudit, 100);
                        claims = ClaimsHwToken;
                        return(null);

                    case ServiceStatusCode.OUSTANDING_TRANSACTION:
                        ctx.Data[STATE] = 11;
                        logger.TraceEvent(TraceEventType.Verbose, 0, "AUTHN_PENDING: " + logInfo + ", state:" + ctx.Data[STATE] + ", i:" + i);
                        Logging.Log.AuthenticationPending(state, (int)ctx.Data[STATE], upn, msspTransId);
                        System.Threading.Thread.Sleep(1000);
                        break;

                    case ServiceStatusCode.EXPIRED_TRANSACTION:
                        ctx.Data[STATE] = 13;
                        logger.TraceEvent(TraceEventType.Information, 0, "AUTHN_TIMEOUT_MID: " + logInfo + ", state:" + ctx.Data[STATE] + ", i:" + i);
                        Logging.Log.AuthenticationFail(state, (int)ctx.Data[STATE], upn, msspTransId, Enum.GetName(typeof(ServiceStatusCode), rsp.Status.Code));
                        return(new AdapterPresentation(AuthView.RetryOrCancel, cfgAdfs, rsp));

                    case ServiceStatusCode.PB_SIGNATURE_PROCESS:
                        ctx.Data[STATE] = 13;
                        logger.TraceEvent(TraceEventType.Information, 0, "AUTHN_SIGN_PROCESS: " + logInfo + ", state:" + ctx.Data[STATE] + ", i:" + i);
                        Logging.Log.AuthenticationFail(state, (int)ctx.Data[STATE], upn, msspTransId, Enum.GetName(typeof(ServiceStatusCode), rsp.Status.Code));
                        return(new AdapterPresentation(AuthView.RetryOrCancel, cfgAdfs, rsp));

                    case ServiceStatusCode.USER_CANCEL:
                        ctx.Data[STATE] = 14;
                        logger.TraceEvent(TraceEventType.Information, 0, "AUTHN_CANCEL: " + logInfo + ", state:" + ctx.Data[STATE] + ", i:" + i);
                        Logging.Log.AuthenticationCancel(state, (int)ctx.Data[STATE], upn, msspTransId);
                        return(new AdapterPresentation(AuthView.RetryOrCancel, cfgAdfs, rsp));

                    default:
                        ctx.Data[STATE] = 12;
                        logger.TraceEvent(TraceEventType.Error, 0, "TECH_ERROR: " + logInfo + ", state:" + ctx.Data[STATE] + ", srvStatusCode:" + (int)rsp.Status.Code
                                          + ", srvStatusMsg:\"" + rsp.Status.Message + "\", srvStatusDetail:\"" + (string)rsp.Detail + "\"");
                        if (rsp.Status.Color == ServiceStatusColor.Yellow || rsp.Status.Color == ServiceStatusColor.Green)
                        {
                            Logging.Log.AuthenticationFail(state, (int)ctx.Data[STATE], upn, msspTransId, Enum.GetName(typeof(ServiceStatusCode), rsp.Status.Code));
                        }
                        else
                        {
                            Logging.Log.AuthenticationTechnicalError(state, (int)ctx.Data[STATE], upn, msspTransId, Enum.GetName(typeof(ServiceStatusCode), rsp.Status.Code), (string)rsp.Detail);
                        };
                        return(new AdapterPresentation(AuthView.AuthError, cfgAdfs, rsp));
                    }
                }
                ;  // for-loop

                ctx.Data[STATE] = 13;
                logger.TraceEvent(TraceEventType.Information, 0, "AUTHN_TIMEOUT_ADFS: " + logInfo + ", state:" + ctx.Data[STATE]);
                Logging.Log.AuthenticationTimeout(state, (int)ctx.Data[STATE], cfgMid.RequestTimeOutSeconds, upn, msspTransId);
                return(new AdapterPresentation(AuthView.RetryOrCancel, cfgAdfs, "Timeout."));
            }
            else if (formAction == "Retry")
            {
                switch (state)
                {
                case 13:
                case 5:
                case 35:
                case 4:
                case 14:
                case 34:
                {           // check session age and number of retries
                    int ageSeconds = (int)((DateTime.UtcNow.Ticks / 10000 - (long)ctx.Data[SESSBEGIN]) / 1000);
                    if (ageSeconds >= cfgAdfs.SessionTimeoutSeconds)
                    {
                        logger.TraceEvent(TraceEventType.Information, 0, "AUTHN_SESSION_TIMEOUT: " + logInfo + ", state:" + ctx.Data[STATE] + ", age:" + ageSeconds);
                        Logging.Log.SessionTimeout(state, (int)ctx.Data[STATE], ageSeconds, upn, msspTransId);
                        ctx.Data[STATE] = 22;
                    }
                    else if ((int)ctx.Data[SESSTRIES] >= cfgAdfs.SessionMaxTries)
                    {
                        logger.TraceEvent(TraceEventType.Information, 0, "AUTHN_SESSION_OVERTRIES: " + logInfo + ", state:" + ctx.Data[STATE]);
                        Logging.Log.SessionTooMuchRetries(state, (int)ctx.Data[STATE], (int)ctx.Data[SESSTRIES], upn, msspTransId);
                        ctx.Data[STATE] = 22;
                    }
                    ;
                    if ((int)ctx.Data[STATE] == 22)
                    {
                        return(new AdapterPresentation(AuthView.AutoLogout, cfgAdfs));
                    }
                }
                    // start a new asynchronous RequestSignature
                    AuthRequestDto req = new AuthRequestDto();
                    req.PhoneNumber  = (string)ctx.Data[MSISDN];
                    req.UserLanguage = (UserLanguage)Enum.Parse(typeof(UserLanguage), resMgr.GetString(RES_LANG, culture));
                    string uiTrxId = Util.BuildRandomBase64Chars(cfgAdfs.LoginNonceLength);
                    req.DataToBeSigned = _buildMobileIdLoginPrompt(req.UserLanguage, culture, uiTrxId);
                    req.TimeOut        = cfgMid.RequestTimeOutSeconds;
                    bool needCheckUserSerialNumber =
                        !cfgMid.UserSerialNumberPolicy.HasFlag(UserSerialNumberPolicy.allowAbsence) ||
                        !cfgMid.UserSerialNumberPolicy.HasFlag(UserSerialNumberPolicy.allowMismatch) ||
                        cfgMid.UserSerialNumberPolicy.HasFlag(UserSerialNumberPolicy.warnMismatch);
                    if (needCheckUserSerialNumber /* cfgMid.UserSerialNumberPolicy != UserSerialNumberPolicy.ignore */ && ctx.Data.ContainsKey(UKEYSN))
                    {
                        req.UserSerialNumber = (string)ctx.Data[UKEYSN];
                    }
                    ctx.Data[AUTHBEGIN] = DateTime.UtcNow.Ticks / 10000;
                    AuthResponseDto rsp = getWebClient().RequestSignature(req, true /* async */);
                    ctx.Data[SESSTRIES] = (int)ctx.Data[SESSTRIES] + 1;
                    string logMsg = "svcStatus:" + (int)rsp.Status.Code + ", mssTransId:\"" + rsp.MsspTransId + "\", state:";

                    switch (rsp.Status.Code)
                    {
                    case ServiceStatusCode.VALID_SIGNATURE:
                    case ServiceStatusCode.SIGNATURE:
                        ctx.Data[STATE]     = 33;
                        ctx.Data[MSSPTRXID] = rsp.MsspTransId;
                        logger.TraceEvent(TraceEventType.Verbose, 0, logMsg + ctx.Data[STATE]);
                        Logging.Log.AuthenticationSuccess(state, (int)ctx.Data[STATE], upn, msspTransId);
                        return(new AdapterPresentation(AuthView.TransferCtx, cfgAdfs));

                    case ServiceStatusCode.REQUEST_OK:
                        ctx.Data[STATE]     = 31;
                        ctx.Data[MSSPTRXID] = rsp.MsspTransId;
                        ctx.Data[DTBS]      = req.DataToBeSigned;
                        logger.TraceEvent(TraceEventType.Verbose, 0, logMsg + ctx.Data[STATE]);
                        Logging.Log.AuthenticationContinue(state, (int)ctx.Data[STATE], upn, msspTransId);
                        return(new AdapterPresentation(AuthView.SignRequestSent, cfgAdfs, req.PhoneNumber, uiTrxId, cfgMid.PollResponseDelaySeconds * 1000));

                    case ServiceStatusCode.USER_CANCEL:
                        ctx.Data[STATE] = 34;
                        logger.TraceEvent(TraceEventType.Verbose, 0, logMsg + ctx.Data[STATE]);
                        Logging.Log.AuthenticationCancel(state, (int)ctx.Data[STATE], upn, msspTransId);
                        return(new AdapterPresentation(AuthView.RetryOrCancel, cfgAdfs, rsp));

                    case ServiceStatusCode.EXPIRED_TRANSACTION:
                    case ServiceStatusCode.PB_SIGNATURE_PROCESS:
                        ctx.Data[STATE] = 35;
                        logger.TraceEvent(TraceEventType.Verbose, 0, logMsg + ctx.Data[STATE]);
                        Logging.Log.AuthenticationFail(state, (int)ctx.Data[STATE], upn, msspTransId, Enum.GetName(typeof(ServiceStatusCode), rsp.Status.Code));
                        return(new AdapterPresentation(AuthView.RetryOrCancel, cfgAdfs, rsp));

                    default:
                        ctx.Data[STATE] = 32;
                        logger.TraceEvent((rsp.Status.Color == ServiceStatusColor.Yellow ? TraceEventType.Warning : TraceEventType.Error),
                                          0, logMsg + ctx.Data[STATE] + ", errMsg:\"" + rsp.Status.Message + "\", errDetail:\"" + rsp.Detail + "\"");
                        Logging.Log.AuthenticationTechnicalError(state, (int)ctx.Data[STATE], upn, msspTransId, Enum.GetName(typeof(ServiceStatusCode), rsp.Status.Code), rsp.Detail.ToString());
                        return(new AdapterPresentation(AuthView.AuthError, cfgAdfs, rsp));
                    }
                    ;

                default:
                    logger.TraceEvent(TraceEventType.Error, 0, "BAD_STATE: " + logInfo + ", state:" + state);
                    Logging.Log.AuthenticationFail(state, (int)ctx.Data[STATE], upn, msspTransId, "BAD_STATE");
                    return(new AdapterPresentation(AuthView.AuthError, cfgAdfs, "action:\"Retry\"; state:" + state));
                }
            }
            //else if (formAction == "SignOut")
            //{
            //    logger.TraceEvent(TraceEventType.Verbose, 0, "SIGNOUT: " + logInfo + "; state:" + state);
            //    return new AdapterPresentation(AuthView.AutoLogout, cfgAdfs); // could lead to endless-loop
            //}
            else
            {
                logger.TraceEvent(TraceEventType.Error, 0, "Unsupported formAction: " + formAction);
                Logging.Log.AuthenticationBadForm(state, (int)ctx.Data[STATE], upn, msspTransId, formAction);
                return(new AdapterPresentation(AuthView.AuthError, cfgAdfs, new AuthResponseDto(ServiceStatusCode.GeneralClientError)));
            }
        }