コード例 #1
0
ファイル: DataSeeder.cs プロジェクト: war-man/master-api
        public static void SeedAudiences()
        {
            if (_context.Audiences.Any())
            {
                return;
            }

            new List <Audience> {
                new Audience
                {
                    ClientId             = Guid.NewGuid().ToString(),
                    Name                 = "MasterApi SPA",
                    ApplicationType      = ApplicationTypes.JavaScript,
                    Active               = true,
                    RefreshTokenLifeTime = 7200,
                    Secret               = _crypto.Hash("loc@lh0st"),
                    AllowedOrigin        = "http://localhost:55000",
                    ObjectState          = ObjectState.Added
                },
                new Audience
                {
                    ClientId             = Guid.NewGuid().ToString(),
                    Name                 = "Console",
                    ApplicationType      = ApplicationTypes.NativeConfidential,
                    Active               = true,
                    RefreshTokenLifeTime = 14400,
                    Secret               = _crypto.Hash("c0ns0l3"),
                    AllowedOrigin        = "*",
                    ObjectState          = ObjectState.Added
                }
            }.ForEach(x => _context.Audiences.Add(x));
            _hasUpdates = true;
        }
コード例 #2
0
        private async Task <string> StoreRefreshToken(IIdentity identity)
        {
            var refreshTokenId = Guid.NewGuid().ToString("n");
            var refreshToken   = new RefreshToken
            {
                Id          = _crypto.Hash(refreshTokenId),
                ClientId    = _audience.ClientId,
                Subject     = identity.Name,
                IssuedUtc   = DateTime.UtcNow,
                ExpiresUtc  = DateTime.UtcNow.AddMinutes(Convert.ToDouble(_audience.RefreshTokenLifeTime)),
                ObjectState = ObjectState.Added
            };

            // create metadata to pass on to refresh token provider
            var props = new AuthenticationProperties(new Dictionary <string, string>
            {
                { "as:client_id", _audience.ClientId },
                { "userName", identity.Name }
            })
            {
                IssuedUtc  = refreshToken.IssuedUtc,
                ExpiresUtc = refreshToken.ExpiresUtc
            };

            var ticket      = new AuthenticationTicket(new ClaimsPrincipal(identity), props, JwtBearerDefaults.AuthenticationScheme);
            var ticketBytes = new TicketSerializer().Serialize(ticket);

            refreshToken.ProtectedTicket = Convert.ToBase64String(ticketBytes);

            await _authService.AddRefreshToken(refreshToken);

            return(refreshTokenId);
        }
コード例 #3
0
ファイル: AcccountService.cs プロジェクト: sammyndu/nwassa
        public AuthResponse Login(LoginModel login)
        {
            UserDocument user;

            if (IsPhoneNumber(login.Username))
            {
                var userCollection = _userRepository.GetCollection();
                var users          = userCollection.Find(x => x.PhoneNumber == login.Username);
                user = users.FirstOrDefault();
            }
            else
            {
                user = _userService.GetByEmail(login.Username);
            }
            if (user == null)
            {
                throw new InvalidCredentialException("Invalid Email/Password combination.");
            }


            var encrptedPassword = _crypto.Hash(login.Password, user.LoginProfile.Salt, 5523);

            if (user.LoginProfile.Password != encrptedPassword)
            {
                throw new InvalidCredentialException("Invalid Email/Password combination.");
            }

            if (user != null)
            {
                var userInfo = new UserInfo
                {
                    Id            = user.Id,
                    Email         = user.Email,
                    FirstName     = user.FirstName,
                    LastName      = user.LastName,
                    PhoneNumber   = user.PhoneNumber,
                    PassportPhoto = user.PassportPhoto,
                    BVN           = user.BVN,
                    DateCreated   = user.DateCreated
                };
                var token = GenerateJwtToken(userInfo);
                return(new AuthResponse {
                    User = userInfo, Token = token
                });
            }

            return(null);
        }
コード例 #4
0
        /// <summary>
        /// What is the obfuscation-byte array with this size based on this string?
        /// </summary>
        /// <param name="crypto">
        /// Cryptography service used for hashing.
        /// </param>
        /// <param name="fromString">
        /// The string to generate the modifier from.
        /// </param>
        /// <param name="sourceLength">
        /// The length of the byte array to be returned.
        /// </param>
        /// <returns>
        /// A byte array with length sourceLength generated using fromString.
        /// </returns>
        private static byte[] GenModifier(ICrypto crypto, string fromString, int sourceLength)
        {
            var output = new byte[0];

            for (int i = 0; output.Length < sourceLength; i++)
            {
                output = output.Merge(crypto.Hash(From(fromString + i)));
            }
            return(output.Take(sourceLength).ToArray());
        }
コード例 #5
0
        /// <summary>
        ///     Creates the specified parameters.
        /// </summary>
        /// <param name="parameters">The parameters.</param>
        public void Create(CreateUserParameters parameters)
        {
            parameters.Password = _crypto.Hash(parameters.Password);

            using (ITransaction trans = _session.BeginTransaction())
            {
                _session.CreateCommandProcedure("User_Create", parameters)
                .ExecuteUpdate();

                trans.Commit();
            }
        }
コード例 #6
0
        public async ValueTask <UserRecord> Retrieve(LoginRequest request)
        {
            var user = await _userStore.GetByEmail(request.Email);

            if (user == null)
            {
                return(null);
            }

            return(user.PasswordHash == _crypto.Hash(request.Password, request.Email)
                ? user
                : null);
        }
コード例 #7
0
ファイル: UserService.cs プロジェクト: mruhul/BDDShop
        public async ValueTask <string> Create(RegisterUser request)
        {
            var id = Guid.NewGuid().ToString();

            await _userStore.Create(new UserRecord
            {
                Id           = id,
                Email        = request.Email,
                PasswordHash = _crypto.Hash(request.Password, salt: request.Email)
            });

            return(id);
        }
コード例 #8
0
        public async Task <UserAccount> CreateNewLocalUserAccountAsync(string email, string password, string returnUrl = null)
        {
            var now = DateTime.UtcNow;

            var userAccount = new UserAccount
            {
                Id           = Guid.NewGuid(),
                Email        = email,
                PasswordHash = _crypto.HashPassword(password,
                                                    _applicationOptions.PasswordHashingIterationCount),
                FailedLoginCount  = 0,
                IsEmailVerified   = false,
                IsLoginAllowed    = _applicationOptions.RequireLocalAccountVerification,
                PasswordChangedAt = now,
                CreatedAt         = now,
                UpdatedAt         = now
            };

            if (_applicationOptions.RequireLocalAccountVerification &&
                !String.IsNullOrWhiteSpace(returnUrl))
            {
                // Set verification key
                userAccount.SetVerification(
                    _crypto.Hash(_crypto.GenerateSalt()).StripUglyBase64(),
                    VerificationKeyPurpose.ConfirmAccount,
                    returnUrl,
                    now);
            }

            await _userAccountStore.WriteAsync(userAccount);

            // Emit event
            await _eventService.RaiseSuccessfulUserAccountCreatedEventAsync(
                userAccount.Id,
                IdentityServerConstants.LocalIdentityProvider);

            return(userAccount);
        }
コード例 #9
0
        public UserInfo Login(LoginInfo loginInfo)
        {
            User user  = null;
            var  login = loginInfo.Login.ToUpper();

            user = dbContext.Users.SingleOrDefault(u => u.Username.ToUpper() == login || u.Email.ToUpper() == login);
            if (user == null)
            {
                throw new LoginFailedException("Username or password is incorrect.");
            }
            if (crypto.Hash(loginInfo.Password) == user.Password)
            {
                return(new UserInfo
                {
                    Email = user.Email,
                    Username = user.Username,
                    Firstname = user.Firstname,
                    Lastname = user.Lastname,
                    Token = GenerateToken(user)
                });
            }
            throw new LoginFailedException();
        }
コード例 #10
0
        public void SetVerification(
            UserAccount userAccount,
            VerificationKeyPurpose purpose,
            string storage  = null,
            DateTime?sentAt = null)
        {
            userAccount.VerificationKey = crypto
                                          .Hash(crypto.GenerateSalt())
                                          .StripUglyBase64()
                                          .ToLowerInvariant();

            userAccount.VerificationPurpose   = (int)purpose;
            userAccount.VerificationKeySentAt = sentAt ?? DateTime.UtcNow;
            userAccount.VerificationStorage   = storage;
        }