Example #1
0
 public AuthenticateResponse ValidateUser(AuthenticateRequest userReq)
 {
     try {
         AuthenticateResponse result = null;
         Users user = _context.Users.Include(x => x.Role).Include(x => x.Project).Where(x => x.PsNo == userReq.Username && x.Password == userReq.Password && x.IsActive == true && x.IsDelete == false).FirstOrDefault();
         if (user == null)
         {
             throw new ValueNotFoundException("Username or password is incorrect");
         }
         Project project = _context.Project.Where(x => x.Id == user.ProjectId).FirstOrDefault();
         result = new AuthenticateResponse {
             FirstName            = user.FirstName,
             Id                   = user.Id,
             LastName             = user.LastName,
             Email                = user.Email,
             IsActive             = Convert.ToBoolean(user.IsActive),
             PhoneNumber          = user.Phoneno,
             RoleId               = Convert.ToInt32(user.RoleId),
             ProjectId            = Convert.ToInt32(user.ProjectId),
             BusinessUnitId       = Convert.ToInt32(user.BuId),
             IndependentCompanyId = Convert.ToInt32(user.IcId),
             ProjectName          = user.Project.Name,
             ProjectCode          = user.Project.ProjCode,
             RoleName             = user.Role.Name,
             VendorId             = user.VendorId
         };
         return(result);
     } catch (Exception ex) {
         throw ex;
     }
 }
Example #2
0
        public override void Authenticate(RequestContext <AuthenticateRequest, AuthenticateResponse> requestContext)
        {
            SslConnection connection = _context.Connection as SslConnection;

            X509Certificate cert           = connection.ClientCertificate;
            string          certHashString = cert.GetCertHashString();

            foreach (User user in ServerContext.AccessControlList.Users)
            {
                SslAuthenticationParameters auth = (SslAuthenticationParameters)user.GetAuthentication("ssl_auth");


                if (auth != null && auth.CertificateHash.Equals(certHashString))
                {
                    ServerContext.ServerAuthenticationContext.AuthenticatedPermissionMember = user;

                    AuthenticateResponse response = requestContext.CreateResponse();
                    response.Succeeded = true;
                    response.Execute();
                    return;
                }
            }

            _log.WarnFormat("Could not find user associated with certificate '{0}'", certHashString);

            AuthenticateResponse errorResponse = requestContext.CreateResponse();

            errorResponse.Succeeded          = false;
            errorResponse.CustomErrorMessage = "No client associated with specified certificate!";
            errorResponse.Execute();
        }
Example #3
0
        public static SiteSession Create(SiteAuthenticate request, AuthenticateResponse user)
        {
            var to = new SiteSession {
                Slug = request.Slug,
                User = user,
            };

            if (user != null && request.provider != "authsecret")
            {
                if (!string.IsNullOrEmpty(user.BearerToken))
                {
                    to.BearerToken = user.BearerToken;
                }
                else if (!string.IsNullOrEmpty(user.SessionId))
                {
                    to.SessionId = user.SessionId;
                }
            }
            if (request.AccessToken != null)
            {
                if (request.provider == "bearer")
                {
                    to.BearerToken = request.AccessToken;
                }
                else if (request.provider == "session")
                {
                    to.SessionId = request.AccessToken;
                }
                else if (request.provider == "authsecret")
                {
                    to.AuthSecret = request.AccessToken;
                }
            }
            return(to);
        }
        public async Task <AuthenticateResponse> SignIn(AuthenticateRequest model, string ipAddress)
        {
            var account = await _userRepository.GetByEmail(model.Email);

            if (account == null || !account.EmailConfirmed || !BC.Verify(model.Password, account.PasswordHash))
            {
                throw new Exception("Email or password is incorrect");
            }

            // authentication successful so generate jwt and refresh tokens
            var jwtToken     = generateJwtToken(account);
            var refreshToken = generateRefreshToken(ipAddress);

            // save refresh token
            account.RefreshTokens.Add(refreshToken);
            _userRepository.Update(account);

            //var response = _mapper.Map<AuthenticateResponse>(account);

            var response = new AuthenticateResponse()
            {
                FirstName  = account.FirstName,
                LastName   = account.LastName,
                Email      = account.Email,
                IsVerified = account.EmailConfirmed,
                Created    = refreshToken.Created,
                Id         = refreshToken.Id
            };

            response.JwtToken     = jwtToken;
            response.RefreshToken = refreshToken.Token;
            return(response);
        }
Example #5
0
        public void AuthenticateResponse_FromJson()
        {
            AuthenticateResponse authenticateResponse = AuthenticateResponse.FromJson(JsonData);

            Assert.IsNotNull(authenticateResponse);
            Assert.AreEqual(authenticateResponse.GetType(), typeof(AuthenticateResponse));
        }
Example #6
0
        public void U2F_FinishAuthentication()
        {
            StartedAuthentication startedAuthentication = new StartedAuthentication(
                TestConts.SERVER_CHALLENGE_SIGN_BASE64,
                TestConts.APP_SIGN_ID,
                TestConts.KEY_HANDLE_BASE64);

            AuthenticateResponse authenticateResponse = new AuthenticateResponse(
                TestConts.CLIENT_DATA_AUTHENTICATE_BASE64,
                TestConts.SIGN_RESPONSE_DATA_BASE64,
                TestConts.KEY_HANDLE_BASE64);


            DeviceRegistration deviceRegistration = new DeviceRegistration(TestConts.KEY_HANDLE_BASE64_BYTE,
                                                                           TestConts.USER_PUBLIC_KEY_AUTHENTICATE_HEX,
                                                                           TestConts.ATTESTATION_CERTIFICATE.Base64StringToByteArray(),
                                                                           0);

            uint orginalValue = deviceRegistration.Counter;

            U2F.Core.Crypto.U2F.FinishAuthentication(startedAuthentication, authenticateResponse, deviceRegistration);

            Assert.True(deviceRegistration.Counter != 0);
            Assert.NotEqual(orginalValue, deviceRegistration.Counter);
            Assert.Equal(orginalValue + 1, deviceRegistration.Counter);
        }
        public async Task <AuthenticateResponse> SignInAsync(AuthenticateRequest request)
        {
            if (string.IsNullOrWhiteSpace(request.Password) ||
                string.IsNullOrWhiteSpace(request.Email))
            {
                throw new ServerException(HttpStatusCode.BadRequest,
                                          ExceptionMessage.INVALID_CREDENTIALS);
            }

            var user = await _userManager.FindByEmailAsync(request.Email);

            if (user is null)
            {
                throw new ServerException(HttpStatusCode.NotFound,
                                          ExceptionMessage.USER_NOT_FOUND);
            }

            var roles = await _userManager.GetRolesAsync(user);

            if (!await _userManager.CheckPasswordAsync(user, request.Password))
            {
                throw new ServerException(HttpStatusCode.BadRequest,
                                          ExceptionMessage.INVALID_CREDENTIALS);
            }

            var accessToken  = _jwtProvider.GenerateAccessToken(_mapper.Map <UserModel>(user), roles);
            var refreshToken = _jwtProvider.GenerateRefreshToken();

            await SetRefreshTokenAsync(user, refreshToken);

            var response = new AuthenticateResponse(accessToken, refreshToken);

            return(response);
        }
        public void ValidateLoginTest()
        {
            AgentCircuitManager agentCircuitManager = new AgentCircuitManager();

            agentCircuitManager.AddNewCircuit(circuitcode1, m_agentCircuitData1);
            agentCircuitManager.AddNewCircuit(circuitcode2, m_agentCircuitData2);

            // should be authorized
            AuthenticateResponse resp = agentCircuitManager.AuthenticateSession(SessionId1, AgentId1, circuitcode1);

            Assert.That(resp.Authorised);


            //should not be authorized
            resp = agentCircuitManager.AuthenticateSession(SessionId1, UUID.Random(), circuitcode1);
            Assert.That(!resp.Authorised);

            resp = agentCircuitManager.AuthenticateSession(UUID.Random(), AgentId1, circuitcode1);
            Assert.That(!resp.Authorised);

            resp = agentCircuitManager.AuthenticateSession(SessionId1, AgentId1, circuitcode2);
            Assert.That(!resp.Authorised);

            resp = agentCircuitManager.AuthenticateSession(SessionId2, AgentId1, circuitcode2);
            Assert.That(!resp.Authorised);

            agentCircuitManager.RemoveCircuit(circuitcode2);

            resp = agentCircuitManager.AuthenticateSession(SessionId2, AgentId2, circuitcode2);
            Assert.That(!resp.Authorised);
        }
Example #9
0
        public object Execute(AuthenticateRequest request)
        {
            AuthenticateResponse response;

            try
            {
                var user = DALAdapter.Convert(TestServiceDAL.User.Authenticate(request.Username, request.Password));
                response = new AuthenticateResponse()
                {
                    User    = user,
                    Success = true,
                    Message = "Authentication Succeeded"
                };
            }
            catch (Exception ex)
            {
                response = new AuthenticateResponse()
                {
                    Success = false,
                    Message = ex.Message
                };
            }

            return(response);
        }
        public async Task <AuthenticateResponse> RefreshTokenAsync(string accessToken, string refreshToken)
        {
            var validatedToken = _jwtProvider.ValidateToken(accessToken);

            var user = await _userManager.FindByEmailAsync(validatedToken.Payload.Sub);

            if (user is null)
            {
                throw new ServerException(HttpStatusCode.NotFound,
                                          ExceptionMessage.USER_NOT_FOUND);
            }

            var roles = await _userManager.GetRolesAsync(user);

            await CheckRefreshTokenAsync(user, refreshToken);

            accessToken  = _jwtProvider.GenerateAccessToken(_mapper.Map <UserModel>(user), roles);
            refreshToken = _jwtProvider.GenerateRefreshToken();

            await SetRefreshTokenAsync(user, refreshToken);

            var response = new AuthenticateResponse(accessToken, refreshToken);

            return(response);
        }
        public static void Main(string[] args)
        {
            client = new JsonServiceClient(BASE_URL);
            credentials = client.Post(new Authenticate { UserName = USERNAME, Password = PASSWORD, RememberMe = true });

            getInstallationDetails();

            uploadSensorValues();

            uploadSensorStatuses();

            getSensorValues();

            getSensorStatuses();

            getSensorsForInstallation();

            getNotificationsByType();

            uploadPicture();

            downloadPicture();

            createCustomNotification();

            Console.ReadKey();
        }
        public async Task <IActionResult> AuthenticateAsync(AuthenticateRequest model)
        {
            try
            {
                var             response = new AuthenticateResponse();
                AuthenticateJWT auth     = await userService.AuthAsync(model.Name, model.LastName, model.Email, ipAddress());

                response.Authenticate = auth;
                if (auth == null)
                {
                    return(BadRequest(new { message = "The Name, LastName or Email is wrong" }));
                }

                setTokenCookie(auth.RefreshToken);

                response.Authenticate = auth;
                response.Code         = 200;
                response.Success      = true;


                _logger.LogInformation("User is logued:" + response);
                return(Ok(response));
            }
            catch (Exception ex)
            {
                _logger.LogError("An error has occurred on " + ex);
                throw;
            }
        }
Example #13
0
        public async Task <AuthenticateResponse> CredentialSignOn(string UserName, string password, bool rememberLogin = true)
        {
            InnerCredentials credentials = new InnerCredentials()
            {
                Username = UserName, Password = password
            };

            if (!credentials.IsValid)
            {
                credentials = DecodeUserCredentials();
            }

            AuthenticateResponse authRes = null;

            if (credentials.IsValid)
            {
                authRes = await AuthClient.PostAsync(new Authenticate { provider = "credentials", UserName = credentials.Username, Password = credentials.Password, RememberMe = rememberLogin });
            }

            if (authRes != null)
            {
                EncodeUserCredentials(credentials);
            }
            return(authRes);
        }
Example #14
0
        /// <summary>
        /// The concrete method that authenticate a user request
        /// </summary>
        /// <param name="request">holding the username, account an the password</param>
        /// <returns>Object AuthenticateResponse</returns>
        public AuthenticateResponse Authenticate(AuthenticateRequest request)
        {
            //Building the WebService request
            //First Step Request by Account >> Defining Header
            AuthenticateResponse response = new AuthenticateResponse();


            Dictionary <string, string> headers = SessionHelper.GetAuthorizationHeadersForUser();


            RecordWebServiceResponse <UserInfo> userRecord = childRepo.Authenticate(headers, request.Parameters);

            response = CreateServiceResponse <AuthenticateResponse>(userRecord);
            if (userRecord == null)
            {
                response.Success = false;
                response.Message = "RequestError"; //This message have to be read from resource, it indicate that there was a problem in the connection.
                return(response);
            }
            if (userRecord.record == null)
            {
                response.Success = false;
                response.Message = "InvalidCredentials";
                return(response);
            }
            //authentication Valid, set the session then return the response back


            SessionHelper.Set("UserId", userRecord.record.recordId);
            SessionHelper.Set("key", SessionHelper.GetToken(SessionHelper.Get("AccountId").ToString(), userRecord.record.recordId));
            response.User    = userRecord.record;
            response.Success = true;
            return(response);
        }
        public AuthenticateResponse AuthenticateUser(string Username, string Password)
        {
            AuthenticateResponse authResponse = new AuthenticateResponse();

            try
            {
                AuthenticateCL auth = new AuthenticateCL();
                auth.ClientId  = apiClientId;
                auth.EndUserIp = IPAddress;
                auth.UserName  = Username;
                auth.Password  = Password;
                var    jsonStringObject = JsonConvert.SerializeObject(auth);
                String Qualifiedurl     = Baseurl + "SharedServices/SharedData.svc/rest/Authenticate";
                var    result           = APIHotel.Instance().GetResponse(Qualifiedurl, Verbs.POST, jsonStringObject);
                if (result != null)
                {
                    authResponse = JsonConvert.DeserializeObject <AuthenticateResponse>(result);
                }
                return(authResponse);
            }
            catch (Exception ex)
            {
                authResponse.Error.ErrorMessage = ex.Message;
                return(authResponse);
            }
        }
Example #16
0
        private AuthenticateResponse SetAuthenticationResponse(AuthenticationResult authRes)
        {
            AuthenticateResponse response;

            if (authRes == null)
            {
                response = new AuthenticateResponse()
                {
                    BearerToken  = null,
                    RefreshToken = null,
                };
            }
            else
            {
                response = new AuthenticateResponse()
                {
                    BearerToken  = authRes.IdToken,
                    RefreshToken = authRes.AccessToken,
                };
                if (authRes.Account != null)
                {
                    response.DisplayName = authRes.Account.Username;
                    response.UserName    = authRes.Account.Username;
                }
            }
            return(response);
        }
        public async Task <AuthenticateResponse> AuthenticateAsync(AuthenticateRequest model)
        {
            Account account = await _context.Accounts.SingleOrDefaultAsync(a => a.Email == model.Email);

            if (account == null ||
                !account.IsVerified ||
                !BC.Verify(model.Password, account.PasswordHash))
            {
                throw new AppException("Email or password is incorrect");
            }

            string jwtToken = await GenerateJwtTokenAsync(account);

            RefreshToken refreshToken = await GenerateRefreshTokenAsync();

            account.RefreshTokens.Add(refreshToken);
            _context.Update(account);
            await _context.SaveChangesAsync();

            AuthenticateResponse response = _mapper.Map <AuthenticateResponse>(account);

            response.JwtToken     = jwtToken;
            response.RefreshToken = refreshToken.Token;

            return(response);
        }
Example #18
0
        /// <summary>
        /// Login command
        /// </summary>
        /// <param name="loginrequest"></param>
        public void LoginCom(AuthenticateRequest loginrequest)
        {
            //serialized input
            string sinput = JsonSerializer.Serialize(loginrequest);

            Task <HttpResponseMessage> loginresponse = APIHelper.ApiCall("Accounts/authenticate", HttpMethod.Post, sinput);

            HttpResponseMessage response = loginresponse.Result;

            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                AuthenticateResponse authresp = response.Content.ReadAsAsync <AuthenticateResponse>().Result;

                if (authresp.IsVerified)
                {
                    //User is authenticated


                    //close login window
                    Application.Current.MainWindow.Close();
                }
                else
                {
                    LoginMessage = $"The account was registered {Environment.NewLine} but never verified";
                    //Resend verification email?
                }
            }
            else
            {
                LoginMessage = $"Review username and password {Environment.NewLine} account was not found";
            }
        }
Example #19
0
        // add validation checks
        public static AuthenticateResponse ValidateCredentials(string token, string securityToken, string apiKey, string productName)
        {
            try
            {
                //First, call the C3UserRepository class to get the user information based on the token
                //Next, call the APIRepository class to identify if the apiKey/productName combination is valid
                //create AuthenticationResponse object and populate
                //write APISession object, with TTL information

                ISecurityRepository <AuthenticateResponse> userRepo = SecurityRepositoryFactory <AuthenticateResponse> .GetUserRepository(productName);

                ISecurityRepository <AuthenticateResponse> securityRepo = SecurityRepositoryFactory <AuthenticateResponse> .GetSecurityRepository(productName);

                AuthenticateResponse userResponse = userRepo.LoginUser(token, securityToken);
                if (string.IsNullOrEmpty(userResponse.SQLUserID) == false)
                {
                    userResponse = securityRepo.LoginUser(userResponse, securityToken, apiKey, productName);
                }
                else
                {
                    throw new UnauthorizedAccessException("Login Failed! Unknown token and security token.");
                }

                return(userResponse);
            }
            catch (Exception)
            {
                throw;
            }
        }
Example #20
0
        /// <summary>
        /// Add a new client circuit.  We assume that is has already passed an authorization check
        /// </summary>
        /// <param name="epSender"></param>
        /// <param name="useCircuit"></param>
        /// <param name="assetCache"></param>
        /// <param name="sessionInfo"></param>
        /// <param name="proxyEP"></param>
        /// <returns>
        /// true if a new circuit was created, false if a circuit with the given circuit code already existed
        /// </returns>
        public virtual bool AddNewClient(
            EndPoint epSender, UseCircuitCodePacket useCircuit, IAssetCache assetCache,
            AuthenticateResponse sessionInfo, EndPoint proxyEP)
        {
            IClientAPI newuser;
            uint       circuitCode = useCircuit.CircuitCode.Code;

            if (m_scene.ClientManager.TryGetClient(circuitCode, out newuser))
            {
                // The circuit is already known to the scene.  This not actually a problem since this will currently
                // occur if a client is crossing borders (hence upgrading its circuit).  However, we shouldn't
                // really by trying to add a new client if this is the case.
                return(false);
            }

            UUID agentId   = useCircuit.CircuitCode.ID;
            UUID sessionId = useCircuit.CircuitCode.SessionID;

            newuser
                = CreateNewCircuit(
                      epSender, m_scene, assetCache, this, sessionInfo, agentId, sessionId, circuitCode, proxyEP);

            m_scene.ClientManager.Add(circuitCode, newuser);

            newuser.OnViewerEffect     += m_scene.ClientManager.ViewerEffectHandler;
            newuser.OnLogout           += LogoutHandler;
            newuser.OnConnectionClosed += CloseClient;

            newuser.Start();

            return(true);
        }
        public AuthenticateResponse GetLoggedUser()
        {
            var token = HttpContext.Request.Headers["Authorization"].FirstOrDefault()?.Split(" ").Last();

            try {
                var tokenHandler = new JwtSecurityTokenHandler();
                var key          = Encoding.ASCII.GetBytes("8Zz5tw0Ionm3XPZZfN0NOml3z9FMfmpgXwovR9fp6ryDIoGRM8EPHAB6iHsc0fb");
                tokenHandler.ValidateToken(token, new TokenValidationParameters {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(key),
                    ValidateIssuer           = false,
                    ValidateAudience         = false,
                    // set clockskew to zero so tokens expire exactly at token expiration time (instead of 5 minutes later)
                    ClockSkew = TimeSpan.Zero
                }, out SecurityToken validatedToken);

                var jwtToken = (JwtSecurityToken)validatedToken;
                AuthenticateResponse authRes = new AuthenticateResponse();
                authRes.Id        = int.Parse(jwtToken.Claims.First(x => x.Type == "UserId").Value);
                authRes.ProjectId = int.Parse(jwtToken.Claims.First(x => x.Type == "ProjectId").Value);
                authRes.RoleId    = int.Parse(jwtToken.Claims.First(x => x.Type == "RoleId").Value);
                authRes.RoleName  = jwtToken.Claims.First(x => x.Type == "RoleName").Value;

                return(authRes);
                //  var userId = int.Parse (jwtToken.Claims.First (x => x.Type == "UserId").Value);
            } catch (Exception ex) {
                Log.Logger.Error("Error in validation : " + ex.Message);
                throw ex;
            }
        }
Example #22
0
        public async Task Logout()
        {
            User = null;
            await _localStorageService.RemoveItemAsync("user");

            _navigationManager.NavigateTo("login");
        }
Example #23
0
        public async Task <AuthenticateResponse> AuthenticateAsync(AuthenticateRequest model, string ipAddress)
        {
            var account = await jwtUserService.GetByEmailAsync(model.Email);

            if (account == null || !account.IsVerified || !passwordService.Verify(model.Password, account.PasswordHash))
            {
                throw new JwtAppException("Email or password is incorrect");
            }

            // authentication successful so generate JWT and refresh tokens
            var jwtToken     = tokenService.GenerateJwtToken(account);
            var refreshToken = tokenService.GenerateRefreshToken(ipAddress);


            if (account.RefreshTokens == null)
            {
                account.RefreshTokens = new List <RefreshToken>();
            }

            // save refresh token
            account.RefreshTokens.Add(refreshToken);
            await jwtUserService.UpdateAsync(account.Id, account);

            AuthenticateResponse response = convertService.UserToAuthenticateResponse(account);

            response.JwtToken     = jwtToken;
            response.RefreshToken = refreshToken.Token;
            return(response);
        }
        public async Task AuthenticateServiceReturnedToken()
        {
            var request = new AuthenticateRequestDto
            {
                Password = "******",
                Username = "******"
            };

            const string expectedResponseToken = "someJwt";
            var          expectedResponse      = new AuthenticateResponse
            {
                Token = expectedResponseToken
            };

            _mockAuthenticationService.Setup(service => service.Authenticate(request))
            .Returns(Task.FromResult(expectedResponse));

            var actualResult = await _usersController.Authenticate(request);

            Assert.IsType <OkObjectResult>(actualResult);

            var okResult = (OkObjectResult)actualResult;

            Assert.IsType <AuthenticateResponse>(okResult.Value);

            var okResultObject = (AuthenticateResponse)okResult.Value;

            Assert.Equal(expectedResponseToken, okResultObject.Token);
        }
        public AuthenticateResponse Authenticate(AuthenticateRequest request,
                                                 string connectionId)
        {
            // To DO: Call External service or DB service to validate the user
            // We need o initialize _signOnUser object.
            // For now we are setting alaways true here.

            var isValidUser = true;

            if (isValidUser)
            {
                _signOnUser.UserId = request.UserName;
            }

            AuthenticateResponse response = null;

            if (_signOnUser != null)
            {
                var channelsecureIdentity = GetSignOnUserIdentity();
                var authToken             = CreateJwtToken(_config, channelsecureIdentity);
                response = new AuthenticateResponse()
                {
                    UserId       = _signOnUser.UserId,
                    Groups       = _signOnUser.UserRoleGroups,
                    DisplayName  = _signOnUser.DisplayName,
                    JwtToken     = authToken,
                    ConnectionId = connectionId
                };
            }

            return(response);
        }
        public AuthenticateResponse RefreshToken(string token, string ipAddress)
        {
            var(refreshToken, account) = getRefreshToken(token);

            // replace old refresh token with a new one and save
            var newRefreshToken = generateRefreshToken(ipAddress);

            refreshToken.Revoked         = DateTime.UtcNow;
            refreshToken.RevokedByIp     = ipAddress;
            refreshToken.ReplacedByToken = newRefreshToken.Token;
            account.RefreshTokens.Add(newRefreshToken);
            _userRepository.Update(account);

            // generate new jwt
            var jwtToken = generateJwtToken(account);

            //var response = _mapper.Map<AuthenticateResponse>(account);


            var response = new AuthenticateResponse()
            {
                FirstName = account.FirstName,
                LastName  = account.LastName,
                Email     = account.Email,
            };

            response.JwtToken     = jwtToken;
            response.RefreshToken = newRefreshToken.Token;
            return(response);
        }
Example #27
0
        public async Task <ResponseBase <AuthenticateResponse> > Authenticate(AuthenticateModel data)
        {
            IRepository <SqlParameterCollection> repository = new SqlServerRepository(connString);
            var response = new ResponseBase <AuthenticateResponse>();
            var user     = new AuthenticateResponse();

            repository.Parameters.Add("@username", SqlDbType.NVarChar, 50).Value  = data.UserName;
            repository.Parameters.Add("@password", SqlDbType.NVarChar, 200).Value = data.Password;

            var result = repository.Get("usp_toures_authenticate");

            if (repository.Status.Code == Status.Ok)
            {
                foreach (var item in result)
                {
                    //user.Id = (long)result[0]["IdUser"];
                    //user.Names = (string)result[0]["Names"];
                    //user.Surnames = (string)result[0]["Surnames"];
                    //user.BirthDate = (DateTime)result[0]["BirthDate"];
                    //user.Age = (int)result[0]["Age"];
                }
                response.Data = user;
            }
            else
            {
                response.Message = repository.Status.Message;
            }
            response.Code = repository.Status.Code;

            return(await Task.Run(() => response));
        }
Example #28
0
        public ActionResult <AuthenticateResponse> Authenticate([FromBody] User data)
        {
            try
            {
                data.Email = data.Email.ToLower();

                AuthenticateResponse response = new AuthenticateResponse();
                //check for email and password emptiness
                if (string.IsNullOrWhiteSpace(data.Email))
                {
                    return(BadRequest(new { message = Constants.Provide_Email }));
                }
                if (string.IsNullOrWhiteSpace(data.Password))
                {
                    return(BadRequest(new { message = Constants.Provide_Password }));
                }

                //check if user is in the database
                bool IsUserExist = UserService.CheckUserExistence(u => u.Email, data.Email);
                if (!IsUserExist)
                {
                    return(NotFound(new { message = Constants.Non_Exist }));
                }

                //verify Password match
                User user = UserService.FetchOneUser(h => h.Email, data.Email);

                if (!data.Password.Equals(user.Password))
                {
                    return(BadRequest(new { message = Constants.Invalid_Password }));
                }

                //generate jwt token
                JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();
                byte[] key = Encoding.ASCII.GetBytes(UserService._appSettings.Secret);
                SecurityTokenDescriptor tokenDescriptor = new SecurityTokenDescriptor
                {
                    Subject = new ClaimsIdentity(new Claim[]
                    {
                        new Claim(ClaimTypes.Name, user.Guid)
                    }),
                    Expires            = DateTime.UtcNow.AddDays(7),
                    SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
                };
                SecurityToken token = tokenHandler.CreateToken(tokenDescriptor);

                //fill data
                response.Token  = tokenHandler.WriteToken(token);
                response.Status = true;
                user.Password   = string.Empty;
                response.Data   = user;

                return(Ok(response));
            }
            catch (Exception ex)
            {
                Log.LogError(ex);
                return(StatusCode(500, ex.ToString()));
            }
        }
        //public async Task<TransactionResult> CreateRole(string name)
        //{
        //    var role = new Role()
        //    {
        //        Name = name,
        //        NormalizedName = name.ToUpper(),
        //        ConcurrencyStamp = Guid.NewGuid().ToString(),
        //        Description = null
        //    };
        //    var result = await this._roleManager.CreateAsync(role);
        //    if (result.Succeeded)
        //    {
        //        return new TransactionResult();
        //    }
        //    else
        //    {
        //        return new TransactionResult(new CustomException(Constant.Exception_RoleCreationFailed));
        //    }
        //}

        public async Task <TransactionResult> GetAuthenticationToken(string email, string password) // (UserCredential request)
        {
            try
            {
                var user = await this._userManager.FindByEmailAsync(email);

                if (user == null || !await this._userManager.CheckPasswordAsync(user, password))
                {
                    throw new CustomException(ExceptionKey.AuthenticationFailed);
                }
                //var claims = await this._userManager.GetClaimsAsync(user);
                //if (claims == null)
                //{
                //    throw new CustomException(ExceptionKey.UserNotAccess);
                //}
                //var subSystems = claims.SingleOrDefault(q => q.Type == ClaimTypes.System);
                //if (subSystems == null)
                //{
                //    throw new CustomException(ExceptionKey.UserNotAccess);
                //}

                DateTime expirationTime = DateTime.UtcNow.AddMinutes(double.Parse(this._appSettings.AccessExpiration));
                string   token          = GenerateJwtToken(expirationTime);
                var      response       = new AuthenticateResponse(user, token, expirationTime);
                return(new TransactionResult(response));
            }
            catch (Exception ex)
            {
                return(GetTransactionException(ex));
            }
        }
Example #30
0
        private async void LoginButton_Click(object sender, RoutedEventArgs e)
        {
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            AuthenticateRequest user = new AuthenticateRequest();

            user.Username = UsernameTextBox.Text;
            user.Password = PasswordBox.Password;

            var json    = JsonConvert.SerializeObject(user);
            var content = new StringContent(json, Encoding.UTF8, "application/json");

            var responseMessage = await client.PostAsync("api/user", content);

            if (responseMessage.StatusCode == System.Net.HttpStatusCode.Created)
            {
                AuthenticateResponse response = JsonConvert.DeserializeObject <AuthenticateResponse>(await responseMessage.Content.ReadAsStringAsync());
                token = response.Token;
                MessageBox.Show("Pomyślnie zalogowano \n" + "Witaj " + response.Username, "", MessageBoxButton.OK, MessageBoxImage.Information);
            }
            else
            {
                MessageBox.Show(await responseMessage.Content.ReadAsStringAsync(), "", MessageBoxButton.OK, MessageBoxImage.Information);
            }
        }
        public async Task AndUserDoesNotExist_NullIsReturnedAsync()
        {
            var loggerMock        = Mock.Of <ILogger <AccountManagerService> >();
            var clientFactoryMock = new Mock <IClientFactory>();
            var clientMock        = new Moq.Mock <ResourceAccess.ResourceAccessClient>();
            var expectedResponse  = new GetUserOnUserNameResponse
            {
                User = null
            };

            var fakeCall = TestCalls.AsyncUnaryCall <GetUserOnUserNameResponse>(Task.FromResult(new GetUserOnUserNameResponse()), Task.FromResult(new Metadata()), () => Status.DefaultSuccess, () => new Metadata(), () => { });

            clientMock.Setup(m => m.GetUserOnUserNameAsync(Moq.It.IsAny <GetUserOnUserNameRequest>(), null, null, CancellationToken.None)).Returns(fakeCall);
            clientFactoryMock.Setup(c => c.AccountResourceAccessClient()).Returns(clientMock.Object);

            var appConfig = Mock.Of <IOptions <AppSettings> >();
            var service   = new AccountManagerService(loggerMock, clientFactoryMock.Object, appConfig);

            AuthenticateResponse authResponse = await service.Authenticate(new AuthenticateRequest { HashedPassword = "******", IpAddress = "123", UserName = "******" }, null);

            Assert.True(string.IsNullOrEmpty(authResponse.JwtToken));
            Assert.True(string.IsNullOrEmpty(authResponse.RefreshToken));
            Assert.True(string.IsNullOrEmpty(authResponse.Role));
            Assert.True(string.IsNullOrEmpty(authResponse.UserId));
            Assert.True(string.IsNullOrEmpty(authResponse.UserName));
        }
Example #32
0
        public AuthenticateResponse Execute(IServiceBase authService, IAuthProvider authProvider, IAuthSession session, AuthenticateResponse response)
        {
            if (SetBearerTokenOnAuthenticateResponse && response.BearerToken == null && session.IsAuthenticated)
            {
                if (!RequireSecureConnection || authService.Request.IsSecureConnection)
                {
                    IEnumerable<string> roles = null, perms = null;
                    var authRepo = HostContext.AppHost.GetAuthRepository(authService.Request) as IManageRoles;
                    if (authRepo != null)
                    {
                        roles = authRepo.GetRoles(session.UserAuthId);
                        perms = authRepo.GetPermissions(session.UserAuthId);
                    }

                    response.BearerToken = CreateJwtBearerToken(session, roles, perms);
                }
            }

            return response;
        }
        public object AuthenticateResponseDecorator(IServiceBase authService, Authenticate request, AuthenticateResponse authResponse)
        {
            if (authResponse.BearerToken == null || request.UseTokenCookie != true)
                return authResponse;

            authService.Request.RemoveSession(authService.GetSessionId());

            return new HttpResult(authResponse)
            {
                Cookies = {
                    new Cookie(Keywords.TokenCookie, authResponse.BearerToken, Cookies.RootPath) {
                        HttpOnly = true,
                        Secure = authService.Request.IsSecureConnection,
                        Expires = DateTime.UtcNow.Add(ExpireTokensIn),
                    }
                }
            };
        }