Exemple #1
0
        public void TestIdentifyRequest()
        {
            var request = new IdentityRequest();

            request.ClientSdk            = new ClientSdk();
            request.ClientSdk.Platform   = Platform.Xbox;
            request.ClientSdk.SdkVendor  = "foo vendor";
            request.ClientSdk.SdkVersion = "foo version";
            request.Context         = "foo context";
            request.Environment     = Dto.Identity.Environment.Development;
            request.KnownIdentities = new Identities();
            request.KnownIdentities.Add(IdentityType.DeviceApplicationStamp, Guid.NewGuid().ToString());
            request.RequestId          = "foo request id";
            request.RequestTimestampMs = 1234;
            request.SourceRequestId    = "foo source request id";

            var client = new IdentityApiClient(ApiKey, ApiSecret);
            var task   = client.Identify(request);

            task.Wait();
            var response = task.Result;

            Assert.IsNotNull(response);
            Assert.AreEqual(typeof(IdentityResponse), response.GetType());
            Assert.IsNotNull(((IdentityResponse)response).Mpid);
        }
        public async Task <ClaimsIdentity> GetIdentity(IdentityRequest request)
        {
            try
            {
                var user = await _dataContext.Users.FirstOrDefaultAsync(x => x.Login == request.Login);

                if (user == null)
                {
                    throw new Exception("Пользователь не найден.");
                }

                var password = request.Password.GetSHA256Hash(user.PassKey);

                if (user.Password != password)
                {
                    throw new Exception("Неверный пароль.");
                }

                var claims = new List <Claim>
                {
                    new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
                    new Claim(ClaimsIdentity.DefaultNameClaimType, user.Login),
                    new Claim(ClaimsIdentity.DefaultRoleClaimType, user.Role.ToString())
                };
                ClaimsIdentity claimsIdentity =
                    new ClaimsIdentity(claims, "Token", ClaimsIdentity.DefaultNameClaimType,
                                       ClaimsIdentity.DefaultRoleClaimType);
                return(claimsIdentity);
            }
            catch (Exception exception)
            {
                _logger.LogError(exception.Message);
                throw exception;
            }
        }
Exemple #3
0
        public void TestBadIdentifyRequest()
        {
            var request = new IdentityRequest();

            request.ClientSdk            = new ClientSdk();
            request.ClientSdk.Platform   = Platform.Xbox;
            request.ClientSdk.SdkVendor  = "foo vendor";
            request.ClientSdk.SdkVersion = "foo version";
            request.Context            = "foo context";
            request.Environment        = Dto.Identity.Environment.Production;
            request.KnownIdentities    = new Identities();
            request.RequestId          = "foo request id";
            request.RequestTimestampMs = 1234;
            request.SourceRequestId    = "foo source request id";

            var client = new IdentityApiClient(ApiKey, ApiSecret);
            var task   = client.Identify(request);

            task.Wait();
            var response = task.Result;

            Assert.IsNotNull(response);
            Assert.AreEqual(typeof(ErrorResponse), response.GetType());
            Assert.AreEqual(((ErrorResponse)response).StatusCode, 400);
        }
Exemple #4
0
        public async Task <IdentityResponse> GetAccessTokenAsync(IdentityRequest request)
        {
            var identityTokenRequest = new PasswordTokenRequest
            {
                RequestUri   = new Uri(_environmentManager.IdentityUrl, "connect/token"),
                ClientId     = _identityClientId,
                ClientSecret = _identityClientSecret,
                Scope        = Scopes,

                UserName = request.GetCompositeUsername(),
                Password = request.Password
            };

            var response = await _httpClient.RequestPasswordTokenAsync(identityTokenRequest)
                           .ConfigureAwait(false);

            if (response.IsError)
            {
                return(new IdentityResponse
                {
                    Error = $"{response.Error} {response.ErrorDescription}"
                });
            }

            return(new IdentityResponse
            {
                Token = new IdentityToken(response)
            });
        }
Exemple #5
0
        /// <summary>
        /// Called when the hello response is received.
        /// </summary>
        /// <param name="response">Data associated with response.</param>
        /// <returns>Task.</returns>
        protected virtual async Task OnHelloResponseReceived(HelloResponse response)
        {
            Debug.Assert(response != null && response.Data != null, "Response data is null/missing");

            this.log?.Info($"{RecInd} Hello");
            this.lastSequence      = response.Sequence;
            this.HeartbeatInterval = response.Data is null ? -1 : response.Data.HeartbeatInterval;

            this.SetHeartbeatInterval(this.HeartbeatInterval);

            var ident = new IdentityRequest
            {
                Data = new IdentityRequest.IdentityData()
                {
                    Compress       = false,
                    LargeThreshold = 250,
                    Presence       = new IdentityRequest.StatusUpdate
                    {
                        Afk    = false,
                        Game   = null,
                        Since  = null,
                        Status = "online"
                    },
                    Properties = new IdentityRequest.ConnectionProperties
                    {
                        Browser = "disco",
                        Device  = "disco",
                        Os      = "windows" // Environment.OSVersion.Platform.ToString()
                    },
                    Token = this.Options !.AuthToken
                },
Exemple #6
0
        public void TestIdentityRequestSerialization()
        {
            var request = new IdentityRequest();

            request.ClientSdk            = new ClientSdk();
            request.ClientSdk.Platform   = Platform.Xbox;
            request.ClientSdk.SdkVendor  = "foo vendor";
            request.ClientSdk.SdkVersion = "foo version";
            request.Context         = "foo context";
            request.Environment     = Dto.Identity.Environment.Production;
            request.KnownIdentities = new Identities();
            request.KnownIdentities.Add(IdentityType.MicrosoftPublisherId, "foo ad id");
            request.RequestId          = "foo request id";
            request.RequestTimestampMs = 1234;
            request.SourceRequestId    = "foo source request id";

            var serialized          = JsonConvert.SerializeObject(request);
            var deserializedRequest = JsonConvert.DeserializeObject <IdentityRequest>(serialized);

            Assert.AreEqual(request.ClientSdk.Platform, deserializedRequest.ClientSdk.Platform);
            Assert.AreEqual(request.ClientSdk.SdkVendor, deserializedRequest.ClientSdk.SdkVendor);
            Assert.AreEqual(request.ClientSdk.SdkVersion, deserializedRequest.ClientSdk.SdkVersion);
            Assert.AreEqual(request.Context, deserializedRequest.Context);
            Assert.AreEqual(request.Environment, deserializedRequest.Environment);
            Assert.AreEqual(request.KnownIdentities[IdentityType.MicrosoftPublisherId], deserializedRequest.KnownIdentities[IdentityType.MicrosoftPublisherId]);
            Assert.AreEqual(request.RequestId, deserializedRequest.RequestId);
            Assert.AreEqual(request.RequestTimestampMs, deserializedRequest.RequestTimestampMs);
            Assert.AreEqual(request.SourceRequestId, deserializedRequest.SourceRequestId);
        }
        public async Task <IActionResult> Token(IdentityRequest req)
        {
            var identity = await _authService.GetIdentity(req);

            if (identity == null)
            {
                return(new BadRequestObjectResult(new { errorText = "Неверный логин или пароль." }));
            }

            var now = DateTime.UtcNow;

            var jwt = new JwtSecurityToken(
                issuer: AuthOptions.Issuer,
                audience: AuthOptions.Audience,
                notBefore: now,
                claims: identity.Claims,
                expires: now.Add(TimeSpan.FromMinutes(AuthOptions.Lifetime)),
                signingCredentials: new SigningCredentials(AuthOptions.GetSymmetricSecurityKey(), SecurityAlgorithms.HmacSha256));
            var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);

            var response = new
            {
                access_token = encodedJwt,
                username     = identity.Name
            };

            return(new JsonResult(response));
        }
        public void testEnrollIdentity()
        {
            XooaClient xooaClient = new XooaClient();

            xooaClient.setApiToken(XooaConstants.API_TOKEN);

            try {
                var attrs = new List <attrs>();
                attrs.Add(new attrs("sample", "value", false));

                IdentityRequest request = new IdentityRequest("Kavi", "r", true, attrs);

                IdentityResponse identityResponse = xooaClient.enrollIdentity(request);

                identityResponse.display();

                Assert.IsNotEmpty(identityResponse.getId());

                Assert.IsNotEmpty(identityResponse.getIdentityName());

                Assert.IsNotNull(identityResponse.getCanManageIdentities());

                Assert.IsNotEmpty(identityResponse.getCreatedAt());

                Assert.IsNotEmpty(identityResponse.getAccess());

                Assert.IsNotEmpty(identityResponse.getAttrsList());
            } catch (XooaRequestTimeoutException xrte) {
                Assert.IsNotEmpty(xrte.getResultId());

                Assert.IsNotEmpty(xrte.getResultUrl());
            }
        }
Exemple #9
0
        public ActionResult Login(string userName, string password, string returnUrl = "")
        {
            if (SessionData.CurrentUser != null)
            {
                return(Json(new { redirectTo = SessionData.CurrentUser.DefaultHomePage }));
            }
            string language = AppsCommon.GetCurrentLang();
            var    result   = new ActionBusinessResult();

            try
            {
                var userBL = new UserBL();
                result = userBL.DoLoginAccount(userName, password, language);
                if (result.IsActionSuccess)
                {
                    var ipAddress = HttpHelper.GetClientIPAddress(System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]);
                    FileHelper.WriteFileLogin(CommonVariables.KnFileLogin, userName, ipAddress);
                    userBL.CurrentUserInfo.Language         = language;
                    SessionData.CurrentUser                 = userBL.CurrentUserInfo;
                    SessionData.CurrentUser.DefaultHomePage = IdentityRequest.GetDefaultPageForAccountLogged();
                    SessionData.CurrentUser.CurrentDate     = CommonFuc.TruncDate();

                    var urlContinue = SessionData.CurrentUser.DefaultHomePage;
                    if (!string.IsNullOrEmpty(returnUrl))
                    {
                        urlContinue = returnUrl;
                    }
                    if (userBL.CurrentUserInfo.loginfirst == 0 && userName != "SuperAdmin")
                    {
                        if (WebApps.Session.SessionData.CurrentUser.Type == (int)CommonEnums.UserType.Customer)
                        {
                            urlContinue = "/customer/quan-ly-customer/get-view-to-edit-customer/" + userBL.CurrentUserInfo.Id.ToString();
                        }
                        else if (WebApps.Session.SessionData.CurrentUser.Type == (int)CommonEnums.UserType.Lawer)
                        {
                            urlContinue = "/luat-su/quan-ly-luat-su/get-view-to-edit-lawer/" + userBL.CurrentUserInfo.Id.ToString();
                        }
                        else
                        {
                            urlContinue = "/quan-tri-he-thong/quan-ly-nguoi-dung/get-view-to-edit-user/" + userBL.CurrentUserInfo.Id.ToString();
                        }
                    }

                    if (language != "VI_VN")
                    {
                        result.MessageCode = KnMessageCode.LoginSuccess_En;
                    }

                    return(Json(new { result = result.ToJson(), urlContinue }));
                }
            }
            catch (Exception ex)
            {
                Logger.LogException(ex);
            }

            return(Json(new { result = result.ToJson() }));
        }
Exemple #10
0
        public async Task <IActionResult> CreateNewIdentity([FromBody] IdentityRequest request)
        {
            NewIdentityModel iden = new NewIdentityModel();

            iden.NameSpace  = request.NameSpace;
            iden.Identifier = request.Identifier;
            await _ndid.CreateNewIdentity(iden);

            return(NoContent());
        }
        public async Task <IEnumerable <LuisAppDetail> > LuisDiscoveryAsync(WaterfallStepContext step, string text, string applicationCode, string encryptionKey)
        {
            List <LuisAppDetail> result = new List <LuisAppDetail>();

            int IterationsToRetry   = 3;
            int TimeToSleepForRetry = 100;

            for (int i = 0; i <= IterationsToRetry; i++)
            {
                try
                {
                    byte[] byteData = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(new { Text = text, BingSpellCheckSubscriptionKey = config.BingSpellCheckSubscriptionKey, EnableLuisTelemetry = (botTelemetryClient == null) ? false : true }));
                    using (var content = new ByteArrayContent(byteData))
                    {
                        string token = await this.TokenPreference.GetAsync(step.Context, () => { return(string.Empty); });

                        content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                        httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", $"{token}");
                        var response = await httpClient.PostAsync($"{config.LuisRouterUrl}/luisdiscovery", content);

                        if (response.IsSuccessStatusCode)
                        {
                            var json = await response.Content.ReadAsStringAsync();

                            var res = JsonConvert.DeserializeObject <LuisDiscoveryResponse>(json);
                            result = res.LuisAppDetails;
                            break;
                        }
                        else if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized)
                        {
                            IdentityRequest request = new IdentityRequest()
                            {
                                appcode   = applicationCode,
                                timestamp = DateTime.UtcNow
                            };

                            string json             = JsonConvert.SerializeObject(request);
                            var    encryptedRequest = NETCore.Encrypt.EncryptProvider.AESEncrypt(json, encryptionKey);
                            await GetTokenAsync(step, encryptedRequest);

                            continue;
                        }
                    }
                }
                catch
                {
                    Thread.Sleep(TimeToSleepForRetry);
                    continue;
                }
            }

            return(result);
        }
        private IdentityRequest BuildIdentityRequest(IdentityApiRequest identityApiRequest)
        {
            var identityRequest = new IdentityRequest();

            PopulateBaseIdentityRequest(identityRequest);
            var identities = new Identities();

            AddDeviceIdentities(identities);
            AddUserIdentities(identities, identityApiRequest);
            identityRequest.KnownIdentities = identities;
            return(identityRequest);
        }
Exemple #13
0
        public async void GetCardTokenAsync_ReturnsError_WithFailedHttpStatusCode(HttpStatusCode statusCode, string responseString)
        {
            var sut = GetTestClient("", statusCode);

            var request = new IdentityRequest(0, "", "");
            var actual  = await sut.IdentityApi.GetAccessTokenAsync(request);

            Assert.True(actual.IsError);
            Assert.Null(actual.Token);

            Assert.StartsWith(responseString, actual.Error);
        }
Exemple #14
0
        public ActionResult <UserAuthInfo> Login([FromBody] IdentityRequest request)
        {
            UserAuthInfo _UserAuthInfo = _identityService.LoginAsync(request.Username, request.Password, request.TokenDuration);

            if (!_UserAuthInfo.authInfo.Success)
            {
                //return BadRequest(_UserAuthInfo.authInfo);
                return(NotFound(_UserAuthInfo));
            }

            return(Ok(_UserAuthInfo));
        }
Exemple #15
0
        public async Task <IActionResult> PostLogin([FromBody] IdentityRequest request)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var authResponse = await _identityService.LoginAsync(request.username, request.password);

            if (!authResponse.success)
            {
                return(BadRequest(authResponse));
            }

            return(Ok(authResponse));
        }
Exemple #16
0
        public async Task <ResGetRecentMatches> GetRecentMatches(IdentityRequest identReq, GameMode gameMode, uint startAt, uint count)
        {
            var identity = await _identityClient.GetXboxLiveIdentity(new ReqGetXboxLiveIdentity
            {
                Type  = identReq.Type,
                Value = identReq.Value,
            });

            var response = await _waypointClient.GetRecentMatches(identity.ToIdentity(), gameMode, startAt, count);

            var result = Mapper.Map <ResGetRecentMatches>(response.recentMatches);

            result.CacheInfo = response.cacheInfo;

            return(result);
        }
Exemple #17
0
        public async Task <IActionResult> VerifyResult(IdentityRequest model)
        {
            IdentityVerifyLib.Data.AuthResult result;
            if (!String.IsNullOrEmpty(model.Portrait))
            {
                result = await verifyService.VerifyIdWithImageAsync(model.ID, model.FullName, model.Portrait.Substring(model.Portrait.IndexOf(",") + 1));
            }
            else
            {
                result = await verifyService.VerifyIdAsync(model.ID, model.FullName);
            }



            return(View(IdentityResult.FromAuthResult(result)));
        }
Exemple #18
0
        public async Task <ResGetPlayerOverview> GetPlayerOverview(IdentityRequest identReq)
        {
            var identity = await _identityClient.GetXboxLiveIdentity(new ReqGetXboxLiveIdentity
            {
                Type  = identReq.Type,
                Value = identReq.Value,
            });

            var(resp, cacheInfo) = await _waypointClient.GetServiceRecord(identity.ToIdentity());

            var result = Mapper.Map <ResGetPlayerOverview>(resp);

            result.CacheInfo = cacheInfo;

            return(result);
        }
Exemple #19
0
        public async Task <ResGetServiceRecord> GetServiceRecord(IdentityRequest identReq)
        {
            var identity = await _identityClient.GetXboxLiveIdentity(new ReqGetXboxLiveIdentity
            {
                Type  = identReq.Type,
                Value = identReq.Value,
            });

            var response = await _waypointClient.GetServiceRecord(identity.ToIdentity());

            var result = Mapper.Map <ResGetServiceRecord>(response.serviceRecord);

            result.CacheInfo = response.cacheInfo;

            return(result);
        }
Exemple #20
0
        /// <summary>
        /// Link a new account identity. An identity is a JWT subscriber *sub* and issuer *iss*. Only one account my be linked to a particular JWT combination. Allows calling the API with a federated token directly instead of using a client access key.
        /// </summary>
        /// <param name="body"></param>
        /// <returns>Object</returns>
        public async Task CreateIdentity(IdentityRequest body)
        {
            // verify the required parameter 'body' is set
            if (body == null)
            {
                throw new ArgumentNullException("Missing required parameter 'body'.");
            }

            var path   = "/v1/identities";
            var client = await authressHttpClientProvider.GetHttpClientAsync();

            using (var response = await client.PostAsync(path, body.ToHttpContent()))
            {
                await response.ThrowIfNotSuccessStatusCode();
            }
        }
Exemple #21
0
        protected void btnIdentify_Click(object sender, EventArgs e)
        {

            try
            {
                serverResult.Text = "Start Identify...";
                string images = this.bioImages.Text.ToString();

                if (!string.IsNullOrEmpty(images))
                {
                    string token = SessionManager.CloudABISAPIToken;
                    if (!string.IsNullOrEmpty(token))
                    {
                        CloudABISConnector cloudABISConnector = new CloudABISConnector(SessionManager.CloudABISCredentials.BaseAPIURL);

                        var request = new IdentityRequest
                        {
                            ClientKey = SessionManager.CloudABISCredentials.ClientKey,
                            Images = JsonConvert.DeserializeObject<BiometricImages>(images)
                        };
                        MatchingResult response = Task.Run(() => cloudABISConnector.IdentifyAsync(request, token)).Result;

                        serverResult.Text = JsonConvert.SerializeObject(response, Formatting.Indented);

                    }
                    else
                    {
                        Response.Redirect("AppConfiguration.aspx");
                    }
                }
                else
                {
                    serverResult.Text = "Please biometric capture first";
                }

                //clear captured data
                //templateXML.Text = "";
            }
            catch (Exception ex)
            {
                serverResult.Visible = true;
                serverResult.Text = ex.Message;
            }
        }
        /// <summary>
        /// The Enroll identity endpoint is used to enroll new identities for the smart contract app.
        /// A success response includes the API Token generated for the identity.
        /// This API Token can be used to call API End points on behalf of the enrolled identity.
        ///
        /// This endpoint provides equivalent functionality to adding new identity manually using Xooa console,
        /// and identities added using this endpoint will appear, and can be managed,
        /// using Xooa console under the identities tab of the smart contract app
        ///
        /// Required permission: manage identities (canManageIdentities=true)
        /// </summary>
        /// <exception cref="Xooa.Client.Exception.XooaApiException">Thrown when fails to make API call</exception>
        /// <param name="IdentityRequest">Identity Data to enroll.</param>
        /// <returns>PendingTransactionResponse giving the resultId of the pending transaction.</returns>
        public PendingTransactionResponse enrollIdentityAsync(IdentityRequest identityRequest)
        {
            Log.Info("Invoking URL - " + XooaConstants.IDENTITIES_URL);

            var localVarPath = XooaConstants.IDENTITIES_URL;
            var contentType  = XooaConstants.CONTENT_TYPE;

            var localVarQueryParameters = new List <KeyValuePair <string, string> >();

            localVarQueryParameters.Add(new KeyValuePair <string, string>(XooaConstants.ASYNC, XooaConstants.TRUE));
            localVarQueryParameters.Add(new KeyValuePair <string, string>(XooaConstants.TIMEOUT, "1000"));

            var localVarHeaderParams = new Dictionary <string, string>();

            localVarHeaderParams.Add(XooaConstants.ACCEPT, XooaConstants.CONTENT_TYPE);
            localVarHeaderParams.Add(XooaConstants.AUTHORIZATION, XooaConstants.TOKEN + ApiToken);

            string jsonBody = identityRequest.toString();

            int statusCode = 0;

            try {
                RestRequest request = XooaSDK.Client.Util.Request.PrepareRequest(localVarPath,
                                                                                 RestSharp.Method.POST, localVarQueryParameters, jsonBody, localVarHeaderParams,
                                                                                 null, null, contentType);

                IRestResponse response = RestClient.ExecuteTaskAsync(request).Result;

                JObject details = XooaSDK.Client.Util.Request.getDataAsync(response);

                PendingTransactionResponse pendingTransactionResponse = new PendingTransactionResponse(
                    details["resultId"].ToString(), details["resultURL"].ToString());

                return(pendingTransactionResponse);
            } catch (XooaApiException xae) {
                Log.Error(xae);
                throw xae;
            } catch (System.Exception e) {
                Log.Error(e);
                throw new XooaApiException(statusCode, e.Message);
            }
        }
        public void testEnrollIdentityAsync()
        {
            XooaClient xooaClient = new XooaClient();

            xooaClient.setApiToken(XooaConstants.API_TOKEN);

            var attrs = new List <attrs>();

            attrs.Add(new attrs("sample", "value", false));

            IdentityRequest request = new IdentityRequest("Kavi", "r", true, attrs);

            PendingTransactionResponse response = xooaClient.enrollIdentityAsync(request);

            response.display();

            Assert.IsNotEmpty(response.getResultId());

            Assert.IsNotEmpty(response.getResultUrl());
        }
Exemple #24
0
        public async void GetCardTokenAsync_ReturnsError_WithMalformedJson()
        {
            const string responseBody = @"
                {
                    ""access_token"":""eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ"",
                    ""expires_in"": 3600,
                    ""token_type"": ""Bearer""
                ";

            var sut = GetTestClient(responseBody, HttpStatusCode.OK);

            var request = new IdentityRequest(0, "", "");
            var actual  = await sut.IdentityApi.GetAccessTokenAsync(request);

            Assert.True(actual.IsError);
            Assert.Null(actual.Token);

            // The identity model library handles response parsing, we are just checking that we bubble the error back up
            Assert.StartsWith("Expected depth to be zero at the end of the JSON payload", actual.Error);
        }
Exemple #25
0
        public async void GetAccessTokenAsync_ReturnsSuccessTokenResponse_WithSuccessfulRequest()
        {
            const string responseBody = @"
                {
                    ""access_token"":""eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ"",
                    ""expires_in"": 3600,
                    ""token_type"": ""Bearer""
                }";

            var sut = GetTestClient(responseBody, HttpStatusCode.OK);

            var request = new IdentityRequest(0, "", "");
            var actual  = await sut.IdentityApi.GetAccessTokenAsync(request);

            Assert.False(actual.IsError);
            Assert.NotNull(actual.Token);

            Assert.Equal("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ", actual.Token.AccessToken);
            Assert.Equal(3600, actual.Token.ExpiresIn);
            Assert.Equal("Bearer", actual.Token.TokenType);
        }
Exemple #26
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task <MatchingResult> IdentifyAsync(IdentityRequest request, string token)
        {
            MatchingResult result = new MatchingResult();

            try
            {
                this._httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {token}");

                var response = await this._httpClient.PostAsJsonAsync <IdentityRequest>(AbisConstants.BIOMETRIC_IDENTIFY_API_PATH, request);

                if (response.IsSuccessStatusCode || response.StatusCode.Equals(HttpStatusCode.BadRequest))
                {
                    result = await response.Content.ReadAsAsync <MatchingResult>();
                }
                else if (response.StatusCode.Equals(HttpStatusCode.Unauthorized))
                {
                    result = new MatchingResult {
                        OperationResult = AbisConstants.ABISUnAuthorize
                    };
                }
                else if (response.StatusCode.Equals(HttpStatusCode.ServiceUnavailable))
                {
                    result = new MatchingResult {
                        OperationResult = AbisConstants.ABISUnreachable
                    };
                }
                else if (response.StatusCode.Equals(HttpStatusCode.BadGateway))
                {
                    result = new MatchingResult {
                        OperationResult = AbisConstants.ABISBadGateWay
                    };
                }
            }
            catch (Exception) { throw; }

            return(result);
        }
Exemple #27
0
        static void Main(string[] args)
        {
            //WebSocket socket = new WebSocket();
            //socket.subscribeAllEvents();

            XooaClient client = new XooaClient();

            client.setApiToken("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJBcGlLZXkiOiJIU0E0SkZRLUFHUjQ0NUstSkcwOUMzMi1CUDgyVDRZIiwiQXBpU2VjcmV0IjoiS2JZSzdDVHVaWThZSk9aIiwiUGFzc3BocmFzZSI6IjA1N2M2ODM3NjgyZDBjODBkMTllYTk0NjliYzI0MzczIiwiaWF0IjoxNTQzOTkzNjIzfQ.BkNZ6N5FfjCdYsAOYisFSelUDftDhnY3f8OYf4EgXYc");

            //client.subscribeAllEvents((data) => {
            //    Console.WriteLine("data - ", data.ToString());
            //});

            try {
                Console.WriteLine("----- Start -----");

                Console.WriteLine("----- Validate -----");

                client.validate().display();

                Console.WriteLine();

                Console.WriteLine("----- Current Block -----");

                client.getCurrentBlock().display();

                Console.WriteLine();

                Console.WriteLine("----- Current Block Async -----");

                PendingTransactionResponse currentBlockResponse = client.getCurrentBlockAsync();
                currentBlockResponse.display();

                Console.WriteLine();

                Console.WriteLine("----- Current Block From Result Id -----");

                client.getResultForCurrentBlock(currentBlockResponse.getResultId()).display();

                Console.WriteLine();

                Console.WriteLine("----- Block by Number -----");

                client.getBlockByNumber("10").display();

                Console.WriteLine();

                Console.WriteLine("----- Block by NUmber Async -----");

                PendingTransactionResponse blockByNumber = client.getBlockByNumberAsync("10");
                blockByNumber.display();

                Console.WriteLine();

                Console.WriteLine("----- Block Data from Result Id -----");

                client.getResultForBlockByNumber(blockByNumber.getResultId()).display();

                Console.WriteLine();

                Console.WriteLine("----- Invoke -----");

                string[] invokeargs = { "argsx", "200" };

                client.invoke("set", invokeargs).display();

                Console.WriteLine();

                Console.WriteLine("----- Query -----");

                string[] queryArgs = { "argsx" };

                client.query("get", queryArgs).display();

                Console.WriteLine();

                Console.WriteLine("----- Invoke Async -----");

                string[] invokeargs2 = { "argsx", "400" };

                PendingTransactionResponse invokeResponse = client.invokeAsync("set", invokeargs2);
                invokeResponse.display();
                Thread.Sleep(4000);

                Console.WriteLine();

                Console.WriteLine("----- Invoke from Result Id -----");

                client.getResultForInvoke(invokeResponse.getResultId()).display();

                Console.WriteLine();

                Console.WriteLine("----- Query Async -----");

                PendingTransactionResponse queryResponse = client.queryAsync("get", queryArgs);
                queryResponse.display();

                Console.WriteLine();

                Console.WriteLine("----- Query from Result ID -----");

                client.getResultForQuery(queryResponse.getResultId()).display();

                Console.WriteLine();

                Console.WriteLine("----- Current Identity -----");

                client.currentIdentity().display();

                Console.WriteLine();

                Console.WriteLine("----- Get All Identities -----");

                List <IdentityResponse> identities = client.getIdentities();
                foreach (IdentityResponse identity in identities)
                {
                    identity.display();
                    Console.WriteLine();
                }

                Console.WriteLine("----- Enroll Identity -----");

                attrs Attrib = new attrs("Name", "Value", false);

                List <attrs> attributes = new List <attrs>();
                attributes.Add(Attrib);

                IdentityRequest idReq = new IdentityRequest("Kavi", "r", false, attributes);

                IdentityResponse newIdentity1 = client.enrollIdentity(idReq);
                newIdentity1.display();

                Console.WriteLine();

                Console.WriteLine("----- Enroll Identity Async -----");

                PendingTransactionResponse pendingIdentity = client.enrollIdentityAsync(idReq);
                pendingIdentity.display();

                Console.WriteLine();

                Console.WriteLine("----- New Identity from Result Id -----");

                IdentityResponse newIdentity2 = client.getResultForIdentity(pendingIdentity.getResultId());
                newIdentity2.display();

                Console.WriteLine();

                Console.WriteLine("----- Regenerate New API Token -----");

                IdentityResponse newTokenId = client.regenerateIdentityApiToken(newIdentity1.getId());
                newTokenId.display();

                Console.WriteLine();

                Console.WriteLine("----- Get Identity -----");

                client.getIdentity(newTokenId.getId()).display();

                Console.WriteLine();

                Console.WriteLine("----- Delete Identity -----");

                string deleted1 = client.deleteIdentity(newIdentity2.getId());
                Console.WriteLine(deleted1);
                string deleted2 = client.deleteIdentity(newIdentity1.getId());
                Console.WriteLine(deleted2);

                Console.WriteLine();

                Console.WriteLine("----- End -----");
            } catch (XooaApiException xae) {
                xae.display();
            } catch (XooaRequestTimeoutException xrte) {
                xrte.display();
            }
            //Console.ReadLine();
        }
Exemple #28
0
 /// <summary>
 /// The Enroll identity endpoint is used to enroll new identities for the smart contract app.
 /// A success response includes the API Token generated for the identity.
 /// This API Token can be used to call API End points on behalf of the enrolled identity.
 ///
 /// This endpoint provides equivalent functionality to adding new identity manually using Xooa console,
 /// and identities added using this endpoint will appear, and can be managed,
 /// using Xooa console under the identities tab of the smart contract app.
 ///
 /// Required permission: manage identities (canManageIdentities=true)
 /// </summary>
 /// <exception cref="Xooa.Client.Exception.XooaApiException">Thrown when fails to make API call</exception>
 /// <exception cref="Xooa.Client.Exception.XooaRequestTimeoutException">Thrown when a 202 response is recieved.</exception>
 /// <param name="IdentityRequest">Identity to Enroll.</param>
 /// <param name="timeout">Timeout interval for transaction.</param>
 /// <returns>IdentityResponse giving the data about the new Identity.</returns>
 public IdentityResponse enrollIdentity(IdentityRequest identityRequest, string timeout = "3000")
 {
     return(new IdentitiesApi(restClient, apiToken).enrollIdentity(identityRequest, timeout));
 }
        public async Task <Object> Logout(IdentityRequest identityRequest)
        {
            Uri identifyUri = new Uri(String.Format(IdentityUrlFormat, IdentityPathLogout));

            return(await SendIdentityRequest(identityRequest, identifyUri));
        }
Exemple #30
0
 /// <summary>
 /// The Enroll identity endpoint is used to enroll new identities for the smart contract app.
 /// A success response includes the API Token generated for the identity.
 /// This API Token can be used to call API End points on behalf of the enrolled identity.
 ///
 /// This endpoint provides equivalent functionality to adding new identity manually using Xooa console,
 /// and identities added using this endpoint will appear, and can be managed,
 /// using Xooa console under the identities tab of the smart contract app
 ///
 /// Required permission: manage identities (canManageIdentities=true)
 /// </summary>
 /// <exception cref="Xooa.Client.Exception.XooaApiException">Thrown when fails to make API call</exception>
 /// <param name="IdentityRequest">Identity Data to enroll.</param>
 /// <returns>PendingTransactionResponse giving the resultId of the pending transaction.</returns>
 public PendingTransactionResponse enrollIdentityAsync(IdentityRequest identityRequest)
 {
     return(new IdentitiesApi(restClient, apiToken).enrollIdentityAsync(identityRequest));
 }