Пример #1
0
        public async Task <ActionResult <TokenResponse> > CreateToken([FromBody] CreateTokenCommand command, [FromHeader(Name = "X-Correlation-ID")] string correlationId, CancellationToken cancellationToken)
        {
            if (!command.IsValid())
            {
                var errors = command.ValidationResult().Errors.Select(err => new
                {
                    err.PropertyName,
                    err.ErrorMessage
                }).ToDictionary(d => d.PropertyName, d => d.ErrorMessage).ToList();

                var error = new Error
                {
                    Code    = ErrorMessages.InputInvalid.code,
                    Message = ErrorMessages.InputInvalid.message,
                    Errors  = errors
                };

                return(BadRequest(error));
            }

            var result = await _mediator.Send(command, cancellationToken);

            if (result.IsSuccess)
            {
                return(Ok(result.Value));
            }

            return(StatusCode((int)HttpStatusCode.InternalServerError));
        }
Пример #2
0
 public TokenModel CreateToken(CreateTokenCommand command)
 {
     EnsureIsValid(command);
     try
     {
         var token  = command.ToEntity <CreateTokenCommand, ApplicationToken>();
         var client = _deps.ApplicationClients.Find(command.ClientId);
         if (client == null)
         {
             throw NotFound.ExceptionFor <ApplicationClient>(command.ClientId);
         }
         var user = _deps.Users.Find(command.UserId);
         if (user == null)
         {
             throw NotFound.ExceptionFor <User>(command.UserId);
         }
         token.Client = client;
         token.User   = user;
         _deps.ApplicationTokens.Create(token);
         Commit();
         return(command.ToClass <CreateTokenCommand, TokenModel>());
     }
     catch (Exception ex)
     {
         throw new ServiceException("Can't create application token.", ex);
     }
 }
Пример #3
0
        public async Task ExecuteAsync()
        {
            var userClaim = new UserClaim();
            var expected  = Guid.NewGuid().ToString();
            var mock      = new Mock <IJwtFactory>();

            mock.Setup(x => x.Create(userClaim)).Returns(expected);
            var command = new CreateTokenCommand(mock.Object);
            var actual  = await command.ExecuteAsync(userClaim);

            actual.Is(expected);
        }
Пример #4
0
        public async Task CreatesANewValidatedToken()
        {
            var newToken = new CreateTokenCommand()
            {
                Address   = "Test Address",
                Email     = "*****@*****.**",
                Fullname  = "Full Name",
                Telephone = "0554 454545"
            };

            var response = await _client.PostAsync($"api/token", new StringContent(JsonConvert.SerializeObject(newToken), Encoding.UTF8, "application/json"));

            response.EnsureSuccessStatusCode();
            var stringResponse = await response.Content.ReadAsStringAsync();

            var result = JsonConvert.DeserializeObject <CreateTokenResult>(stringResponse);

            Assert.NotNull(result);
            Assert.NotNull(result.Token);

            // validate token using kwts
            var jwksResponse = await _client.GetAsync("/jwks");

            jwksResponse.EnsureSuccessStatusCode();
            var stringjwksResponse = await jwksResponse.Content.ReadAsStringAsync();

            var jwksResult = JsonConvert.DeserializeObject <JsonWebKeySet>(stringjwksResponse);

            Assert.NotNull(jwksResult);

            // decode token
            var handler   = new JwtSecurityTokenHandler();
            var jsonToken = handler.ReadToken(result.Token) as JwtSecurityToken;
            var kid       = jsonToken.Header.Kid;

            var keys = jwksResult.GetSigningKeys();
            var key  = keys.FirstOrDefault(x => x.KeyId == kid);

            var validations = new TokenValidationParameters
            {
                ValidateIssuerSigningKey = true,
                IssuerSigningKey         = key,
                ValidateIssuer           = false,
                ValidateAudience         = false
            };
            var claimsPrincipal = handler.ValidateToken(result.Token, validations, out var tokenSecure);

            Assert.Equal(7, claimsPrincipal.Claims.Count());
        }
Пример #5
0
        public async Task GivenLongRunningCreateRequest_WhenTokenSourceCallsForCancellation_RequestIsTerminated()
        {
            // Arrange, generate a token source that times out instantly
            var tokenSource = new CancellationTokenSource(TimeSpan.FromMilliseconds(0));
            var newToken    = new CreateTokenCommand()
            {
                Address   = "Test Address",
                Email     = "*****@*****.**",
                Fullname  = "Full Name",
                Telephone = "0554 454545"
            };

            // Act
            var request = _client.PostAsync("/Tokens", new StringContent(JsonConvert.SerializeObject(newToken), Encoding.UTF8, "application/json"), tokenSource.Token);

            // Assert
            await Assert.ThrowsAsync <OperationCanceledException>(async() => await request);
        }
Пример #6
0
        public async Task CreatesANewToken()
        {
            var newToken = new CreateTokenCommand()
            {
                Address   = "Test Address",
                Email     = "*****@*****.**",
                Fullname  = "Full Name",
                Telephone = "0554 454545"
            };

            var response = await _client.PostAsync($"api/token", new StringContent(JsonConvert.SerializeObject(newToken), Encoding.UTF8, "application/json"));

            response.EnsureSuccessStatusCode();
            var stringResponse = await response.Content.ReadAsStringAsync();

            var result = JsonConvert.DeserializeObject <CreateTokenResult>(stringResponse);

            Assert.NotNull(result);
            Assert.NotNull(result.Token);

            // validate token using kwts
        }
Пример #7
0
        public async Task <Result <TokenResponse> > Handle(CreateTokenCommand request, CancellationToken cancellationToken)
        {
            var seedBytes = OtpNetService.CreateSeed().seedBytes;

            if (!string.IsNullOrEmpty(request.Seed))
            {
                seedBytes = Encoding.UTF8.GetBytes(request.Seed + request.TokenType);
            }

            var token = _service.GenerateToken(seedBytes, _defaultTimeTopt.Range, _defaultTimeTopt.Size);

            var ttl    = request.TimeToLive ?? token.timeToLive;
            var result = new TokenResponse
            {
                Hash       = Base32Encoding.ToString(seedBytes),
                TimeToLive = ttl,
                Token      = token.token
            };
            await _repository.InsertTokenAsync(result.Hash, result.Token, request.TokenType, result.TimeToLive, cancellationToken);

            return(Result.Ok(result));
        }
        public override void Create(AuthenticationTokenCreateContext context)
        {
            //Create new application token in the database
            var client = context.OwinContext.Get<ApplicationClientModel>("vabank:client");
            if (client == null)
            {
                throw new InvalidOperationException("Client is not in owin context. Can't create refresh token");
            }
            var user = context.OwinContext.Get<UserIdentityModel>("vabank:user");
            if (user == null)
            {
                throw new InvalidOperationException("User is not in owin context. Can't create refresh token");
            }

            var container = context.OwinContext.GetAutofacLifetimeScope();
            var membershipService = container.Resolve<IAuthorizationService>();
            var operationService = container.Resolve<IOperationService>();

            var tokenId = Guid.NewGuid().ToString("N");
            var token = new CreateTokenCommand
            {
                Id = VaBank.Common.Security.Hash.Compute(tokenId),
                ClientId = client.Id,
                IssuedUtc = DateTime.UtcNow,
                ExpiresUtc = DateTime.UtcNow.AddSeconds(client.RefreshTokenLifetime),
                UserId = user.UserId
            };

            context.Ticket.Properties.IssuedUtc = token.IssuedUtc;
            context.Ticket.Properties.ExpiresUtc = token.ExpiresUtc;
            token.ProtectedTicket = context.SerializeTicket();
            membershipService.CreateToken(token);
            if (operationService.HasCurrent)
            {
                operationService.Stop(operationService.Current);
            }
            context.SetToken(tokenId);
            base.Create(context);
        }