public static IEnumerable <object[]> TicketValidationTests()
        {
            yield return(new object[]
            {
                PermissionTicket.Create().ForPrincipal(Identities.DanielB)
                .WithExpiry(DateTimeOffset.UtcNow.AddMinutes(1))
                .WithResources(PermissionTicketResource.ForResource(Resources.FarmTwo.Identifier).WithActions(ResourceActions.Iam.Owner).ForSchema(Schemas.MilkPickup)),
                true
            });

            yield return(new object[]
            {
                PermissionTicket.Create().ForPrincipal(Identities.DanielB)
                .WithExpiry(DateTimeOffset.UtcNow.AddMinutes(1))
                .WithResources(PermissionTicketResource.ForResource(Resources.FarmTwo.Identifier).WithActions(ResourceActions.Iam.Owner)),
                false
            });

            yield return(new object[]
            {
                PermissionTicket.Create().ForPrincipal(Identities.DanielB)
                .WithExpiry(DateTimeOffset.UtcNow.AddMinutes(1)),
                false
            });
        }
예제 #2
0
        public void Add(string requestHash, PermissionTicket ticket)
        {
            var hash = ticket.GetHash();

            this.tickets.Add(hash, ticket);
            this.requestMap.Add(requestHash, hash);
        }
예제 #3
0
        public bool Validate(string input, string secret = null)
        {
            if (string.IsNullOrWhiteSpace(input))
            {
                return(false);
            }

            PermissionTicket ticket;

            try
            {
                ticket = JsonConvert.DeserializeObject <PermissionTicket>(input);
            }
            catch
            {
                try
                {
                    if (string.IsNullOrWhiteSpace(secret))
                    {
                        return(false);
                    }
                    ticket = PermissionTicket.FromJwt(input, secret);
                }
                catch
                {
                    return(false);
                }
            }

            return(Validate(ticket));
        }
예제 #4
0
        /// <inheritdoc/>
        public async Task <bool> Update(PermissionTicket ticket, string token)
        {
            HttpClient client = this.httpClientService.CreateDefaultHttpClient();

            client.DefaultRequestHeaders.Accept.Clear();

            client.BearerTokenAuthorization(token);
            string requestUrl = this.serverConfigurationDelegate.ServerConfiguration.PermissionEndpoint + "/ticket";

            client.BaseAddress = new Uri(requestUrl);

            string jsonOutput = JsonSerializer.Serialize <PermissionTicket>(ticket);

            using (HttpContent content = new StringContent(jsonOutput))
            {
                HttpResponseMessage response = await client.PutAsync(new Uri(requestUrl), content).ConfigureAwait(false);

                if (!response.IsSuccessStatusCode)
                {
                    string msg = $"updatePermissionTicket() returned with StatusCode := {response.StatusCode}.";
                    this.logger.LogError(msg);
                    throw new HttpRequestException(msg);
                }

                return(true);
            }
        }
예제 #5
0
        /// <inheritdoc/>
        public async Task <PermissionTicket> Create(PermissionTicket ticket, string token)
        {
            HttpClient client = this.httpClientService.CreateDefaultHttpClient();

            client.DefaultRequestHeaders.Accept.Clear();

            client.BearerTokenAuthorization(token);
            string requestUrl = this.serverConfigurationDelegate.ServerConfiguration.PermissionEndpoint;

            client.BaseAddress = new Uri(requestUrl);

            string jsonOutput = JsonSerializer.Serialize <PermissionTicket>(ticket);

            using (HttpContent content = new StringContent(jsonOutput))
            {
                HttpResponseMessage response = await client.PostAsync(new Uri(requestUrl), content).ConfigureAwait(false);

                if (!response.IsSuccessStatusCode)
                {
                    this.logger.LogError($"createPermissionTicket(PermissionTicket ) returned with StatusCode := {response.StatusCode}.");
                }

                string result = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

                PermissionTicket?permissionResponse = JsonSerializer.Deserialize <PermissionTicket>(result);
                return(permissionResponse !);
            }
        }
예제 #6
0
 public void Revoke(PermissionTicket ticket)
 {
     if (ticket == null)
     {
         throw new ArgumentNullException(nameof(ticket), "Ticket cannot be NULL");
     }
     this.storage.Remove(ticket.GetHash());
 }
예제 #7
0
        public IActionResult Validate([FromHeader(Name = "X-Permission-Ticket")] string ticket)
        {
            var valid = this.manager.Validate(ticket, Secret);

            if (valid)
            {
                return(Ok(PermissionTicket.FromJwt(ticket, Secret)));
            }
            return(BadRequest("Ticket is Invalid"));
        }
예제 #8
0
        public IActionResult Validate(PermissionTicket ticket)
        {
            var valid = this.manager.Validate(ticket);

            if (valid)
            {
                return(Ok(ticket));
            }
            return(BadRequest("Ticket is Invalid"));
        }
        public void ValidateFromTicket(PermissionTicket ticket, bool expectedResult)
        {
            // Arrange
            this.storage.Add(ticket.GetHash(), ticket);

            // Act
            var validationResult = this.manager.Validate(ticket);

            // Assert
            validationResult.Should().Be(expectedResult);
        }
        public void ValidateFromJwt(string jwt, bool expectedResult)
        {
            // Arrange
            var ticket = PermissionTicket.FromJwt(jwt, Common.Secret);

            this.storage.Add(ticket.GetHash(), ticket);

            // Act
            var validationResult = this.manager.Validate(jwt, Common.Secret);

            // Assert
            validationResult.Should().Be(expectedResult);
        }
예제 #11
0
        private ClaimsIdentity GetClaimsIdentity(PermissionTicket pemTicket)
        {
            // create claims array from the model
            var claims = new List <Claim>
            {
                new Claim(ClaimTypes.NameIdentifier, pemTicket.Principal.ToString()),
                new Claim(ClaimTypes.Expiration, pemTicket.Expiry.ToUnixTimeSeconds().ToString())
            };

            AddResourceClaims(claims, pemTicket.Resources);

            // generate claimsIdentity on the name of the class
            return(new ClaimsIdentity(claims, nameof(PermissionTicketValidationHandler)));
        }
예제 #12
0
        private async Task <bool> ValidateToken(PermissionTicket pemTicket)
        {
            using var client = this.httpClientFactory.CreateClient("Test");
            var tokenJson = JsonConvert.SerializeObject(pemTicket);
            var result    = await client.PostAsync(new Uri("https://authorization-play.Api/ticket/validate"),
                                                   new StringContent(tokenJson, Encoding.UTF8, "application/json"));

            if (!result.IsSuccessStatusCode)
            {
                return(false);
            }

            return(true);
        }
예제 #13
0
        public void FromJwtSuccessful()
        {
            // Act
            var ticket = PermissionTicket.FromJwt(ExistingJwt, Common.Secret);

            // fix timestamp for hash generation
            ticket.WithExpiry(DateTimeOffset.MinValue.AddMinutes(1));

            // Assert
            var retrievedHash = ticket.GetHash();
            var existingHash  = ExistingTicket.GetHash();

            retrievedHash.Should().BeEquivalentTo(existingHash);
        }
예제 #14
0
        private PermissionTicket GetPermissionTicket(string token)
        {
            PermissionTicket pemTicket;

            try
            {
                pemTicket = PermissionTicket.FromJwt(token, "secret");
            }
            catch (SignatureVerificationException sigVerifyEx)
            {
                return(null);
            }

            return(pemTicket);
        }
예제 #15
0
        public PermissionTicket Request(params PermissionTicketRequest[] request)
        {
            if (request == null || request.Length == 0)
            {
                return(PermissionTicket.Invalid());
            }

            var requestHash = string.Join(".", request.Select(r => r.GetHash()));

            var ticket = this.storage.Find(requestHash);
            var existingTicketExpired = ticket != null && ticket.IsExpired(DateTimeOffset.UtcNow);

            if (!existingTicketExpired && ticket != null)
            {
                return(ticket);
            }

            this.storage.Remove(requestHash);

            var responses = new PermissionValidationResponse[request.Length];

            for (var i = 0; i < request.Length; i++)
            {
                responses[i] = this.validator.Validate(request[i]);
            }

            ticket = PermissionTicket.FromValidation(responses);
            ticket.WithExpiry(DateTimeOffset.UtcNow.AddMinutes(DefaultTicketDurationMinutes));

            if (ticket.IsValid)
            {
                this.storage.Add(requestHash, ticket);
            }

            return(ticket);
        }
예제 #16
0
 public bool Validate(PermissionTicket ticket) =>
 ticket != null &&
 ticket.IsValid &&
 !ticket.IsExpired(DateTimeOffset.UtcNow) &&
 this.storage.Find(ticket.GetHash()) != null;