public IActionResult GetById(Guid id)
        {
            return(ActionHelper.TryCatchWithLoggerGeneric <IActionResult>(() =>
            {
                ApplicationModel selectedApplication = Applications.FirstOrDefault(x => x.Id == id);
                if (selectedApplication == null)
                {
                    _logger.LogWarning("GetById -> {0} not found", id);
                    return NotFound();
                }

                string claimId = User.Claims.FirstOrDefault(x => x.Type == JwtRegisteredClaimNames.Jti)?.Value;
                string currentToken = _jwtService.Clone(_dataProtectionService.Protect(claimId), true);
                if (string.IsNullOrEmpty(currentToken))
                {
                    return Unauthorized();
                }

                selectedApplication.Url = $"{selectedApplication.Url}?jwt_token={currentToken}";
                ODataResult <ApplicationModel> results = new ODataResult <ApplicationModel>
                {
                    value = new List <ApplicationModel>()
                    {
                        selectedApplication
                    }
                };
                return Ok(results);
            }, _logger));
        }
Esempio n. 2
0
        public TokenResult Create(SamlResponse samlResponse)
        {
            DateTime issued  = DateTime.UtcNow;
            DateTime expire  = DateTime.UtcNow.AddHours(HOURS_TO_EXPIRE);
            string   claimId = Guid.NewGuid().ToString();

            ICollection <Claim> claims = new List <Claim>()
            {
                new Claim(JwtRegisteredClaimNames.Sub, samlResponse.User.Subject),
                new Claim(JwtRegisteredClaimNames.Jti, claimId),
                new Claim(JwtRegisteredClaimNames.Iat, ToUnixDate(issued).ToString()),
                new Claim(JwtRegisteredClaimNames.Exp, ToUnixDate(expire).ToString()),
                new Claim(JwtRegisteredClaimNames.NameId, samlResponse.User.IdpReferenceId ?? NOT_SPECIFIED_VALUE),
                new Claim(JwtRegisteredClaimNames.Email, samlResponse.User.Email ?? NOT_SPECIFIED_VALUE),
                new Claim(ClaimDefinitions.PEC_CLAIM_NAME, samlResponse.User.PEC ?? NOT_SPECIFIED_VALUE),
                new Claim(ClaimDefinitions.MOBILE_PHONE_CLAIM_NAME, _dataProtectionService.Protect(samlResponse.User.MobilePhone ?? NOT_SPECIFIED_VALUE)),
                new Claim(ClaimDefinitions.ADDRESS_CLAIM_NAME, _dataProtectionService.Protect(samlResponse.User.Address ?? NOT_SPECIFIED_VALUE)),
                new Claim(JwtRegisteredClaimNames.GivenName, samlResponse.User.Name),
                new Claim(JwtRegisteredClaimNames.FamilyName, samlResponse.User.Surname),
                new Claim(JwtRegisteredClaimNames.Birthdate, samlResponse.User.DateOfBirth ?? NOT_SPECIFIED_VALUE),
                new Claim(JwtRegisteredClaimNames.Gender, samlResponse.User.Gender ?? NOT_SPECIFIED_VALUE),
                new Claim(ClaimDefinitions.FISCAL_NUMBER_CLAIM_NAME, samlResponse.User.FiscalNumber ?? NOT_SPECIFIED_VALUE),
                new Claim(ClaimDefinitions.PLACE_BIRTH_CLAIM_NAME, samlResponse.User.PlaceOfBirth ?? NOT_SPECIFIED_VALUE),
                new Claim(ClaimDefinitions.COMPANY_NAME_CLAIM_NAME, samlResponse.User.CompanyName ?? NOT_SPECIFIED_VALUE),
                new Claim(ClaimDefinitions.REGISTERED_OFFICE_CLAIM_NAME, _dataProtectionService.Protect(samlResponse.User.RegisteredOffice ?? NOT_SPECIFIED_VALUE)),
                new Claim(ClaimDefinitions.IVA_CODE_CLAIM_NAME, samlResponse.User.IvaCode ?? NOT_SPECIFIED_VALUE)
            };

            JwtSecurityToken token = new JwtSecurityToken(
                issuer: _jwtConfiguration.Issuer,
                audience: _jwtConfiguration.Issuer,
                claims: claims,
                signingCredentials: _jwtConfiguration.SigningCredentials);

            string encodedJwt = new JwtSecurityTokenHandler().WriteToken(token);
            //Save to cache. TODO: persist?
            string sharedEncryptedKey = _dataProtectionService.Protect(claimId);
            DistributedCacheEntryOptions cacheEntryOptions = new DistributedCacheEntryOptions().SetAbsoluteExpiration(expire.AddMinutes(10));

            _memoryCache.Set(claimId, Encoding.UTF8.GetBytes(encodedJwt), cacheEntryOptions);

            return(new TokenResult()
            {
                ReferenceCode = sharedEncryptedKey,
                Token = new JwtToken(encodedJwt)
            });
        }
Esempio n. 3
0
            public async Task <Unit> Handle(CreateUserCommand request, CancellationToken cancellationToken)
            {
                var query = _dataContext.Users.Where(x => x.Id == request.UserId);

                if (await query.AnyAsync(cancellationToken))
                {
                    throw new DuplicateNameException("User Id alreasy exists");
                }



                var user = new User
                {
                    Id          = request.UserId,
                    SecurityKey = Guid.NewGuid().ToString("N"),
                };

                user.PasswordHash = _protectionService.Protect($"{user.SecurityKey}{request.Password}");

                if (request.Roles.Length > 0)
                {
                    foreach (var role in request.Roles)
                    {
                        var roleExists = await _dataContext.Roles.AnyAsync(x => x.Id == role);

                        if (roleExists)
                        {
                            user.Roles.Add(new UserRole(role));
                        }
                    }
                }

                _dataContext.Users.Add(user);
                await _dataContext.SaveChangesAsync(cancellationToken);

                return(Unit.Value);
            }
Esempio n. 4
0
 private string EncryptProperty(string plainText)
 {
     return((plainText == null) ? null : _dataProtectionService.Protect(Encoding.UTF8.GetBytes(plainText)));
 }