Ejemplo n.º 1
0
 public LoginController()
 {
     _loginResource = new LoginResource();
 }
Ejemplo n.º 2
0
 public void TestInitialize()
 {
     LoginResource = new LoginResource();
     Helpers.SetBaseAddress();
     Helpers.Wipe();
 }
Ejemplo n.º 3
0
        public bool CheckPassword(LoginResource login)
        {
            if (login.Login != LOGIN)
            {
                throw new Exception("Nie znaleziono użytkownika o podanym loginie");
            }

            int iterations = 0;

            try
            {
                iterations = PBKDF2_ITERATIONS;
            }
            catch (ArgumentNullException ex)
            {
                throw new Exception(
                          "Invalid argument given to Int32.Parse",
                          ex
                          );
            }
            catch (FormatException ex)
            {
                throw new Exception(
                          "Could not parse the iteration count as an integer.",
                          ex
                          );
            }
            catch (OverflowException ex)
            {
                throw new Exception(
                          "The iteration count is too large to be represented.",
                          ex
                          );
            }

            if (iterations < 1)
            {
                throw new Exception(
                          "Invalid number of iterations. Must be >= 1."
                          );
            }

            byte[] hash = null;
            try
            {
                hash = Convert.FromBase64String(PASSWORD);
            }
            catch (ArgumentNullException ex)
            {
                throw new Exception(
                          "Invalid argument given to Convert.FromBase64String",
                          ex
                          );
            }
            catch (FormatException ex)
            {
                throw new Exception(
                          "Base64 decoding of pbkdf2 output failed.",
                          ex
                          );
            }

            int storedHashSize = 0;

            try
            {
                storedHashSize = HASH_BYTES;
            }
            catch (ArgumentNullException ex)
            {
                throw new Exception(
                          "Invalid argument given to Int32.Parse",
                          ex
                          );
            }
            catch (FormatException ex)
            {
                throw new Exception(
                          "Could not parse the hash size as an integer.",
                          ex
                          );
            }
            catch (OverflowException ex)
            {
                throw new Exception(
                          "The hash size is too large to be represented.",
                          ex
                          );
            }

            if (storedHashSize != hash.Length)
            {
                throw new Exception(
                          "Hash length doesn't match stored hash length."
                          );
            }

            byte[] testHash = PBKDF2(login.Haslo, Convert.FromBase64String(SALT), iterations, hash.Length);
            return(SlowEquals(hash, testHash));
        }
        public async Task <LoginOutputResource> LoginAsync(LoginResource resource)
        {
            LoginOutputResource Result = new LoginOutputResource();

            //將密碼加密
            MD5HashUtils MD5         = new MD5HashUtils();
            string       Md5Password = MD5.MD5Hash(resource.password);

            //比對這組帳號密碼是否有人存在
            var Users = await _UsersRepository.ReadOneAsync(resource.account_number, Md5Password);

            if (Users != null)
            {
                //撈取該帳號的權限
                var RolePermissions = await _RolePermissionsRepository.ReadAllAsync(Users.roles.role);

                var FunctionNamesCount = (from r in RolePermissions
                                          where (r.role_id == Users.role_id)
                                          select new { r.permissions.function_names }
                                          ).Distinct().ToList();

                Result.user_id   = Users.user_id;
                Result.user_name = Users.user_name;
                Result.role      = Users.roles.role;

                Result.Permissions = new PermissionsResource[FunctionNamesCount.Count()];
                int count = 0;

                foreach (var f in FunctionNamesCount)
                {
                    Result.Permissions[count] = new PermissionsResource();
                    Result.Permissions[count].function_names = new FunctionNamesResource();
                    Result.Permissions[count].actions        = new List <ActionsResource>();

                    Result.Permissions[count].function_names.function_name_id      = f.function_names.function_name_id;
                    Result.Permissions[count].function_names.function_name         = f.function_names.function_name;
                    Result.Permissions[count].function_names.function_name_chinese = f.function_names.function_name_chinese;

                    var ActionsList = (from r in RolePermissions
                                       where (r.role_id == Users.role_id && r.permissions.function_names.function_name == f.function_names.function_name.ToString())
                                       select new { r.permissions.actions }
                                       ).Distinct().ToList();

                    foreach (var a in ActionsList)
                    {
                        Result.Permissions[count].actions.Add(new ActionsResource()
                        {
                            action_id = a.actions.action_id,
                            action    = a.actions.action
                        });
                    }


                    count++;
                }

                var userClaims = new ClaimsIdentity(new[] {
                    //使用者識別碼
                    new Claim(JwtRegisteredClaimNames.NameId, resource.account_number),
                    //JWT的唯一ID,防止JWT重複使用
                    new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                    new Claim("Role", Users.roles.role)
                });

                // 取得對稱式加密 JWT Signature 的金鑰
                // 這部分是選用,但此範例在 Startup.cs 中有設定 ValidateIssuerSign ingKey = true 所以這裡必填
                var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]));
                //建立 JWT TokenHandler 以及用於描述 JWT 的 TokenDescriptor
                var tokenHandler = new JwtSecurityTokenHandler();


                var tokenDescriptor = new SecurityTokenDescriptor
                {
                    Issuer   = _config["Jwt:Issuer"],
                    Audience = _config["Jwt:Issuer"],
                    Subject  = userClaims,
                    // Expires = DateTime.Now.AddMinutes(30), //到期時間
                    SigningCredentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256)
                };


                // 產出所需要的 JWT Token 物件
                var securityToken = tokenHandler.CreateToken(tokenDescriptor);
                // 產出序列化的 JWT Token 字串
                var serializeToken = tokenHandler.WriteToken(securityToken);

                Result.JWTKey = serializeToken;
            }

            return(Result);
        }
        private Task <string> GetCustomer(LoginResource model)
        {
            var str = $"Surrogate check:{model.Email}-{model.Password}";

            return(Task.FromResult <string>(str));
        }
Ejemplo n.º 6
0
        public async Task <GenericResponse <LoginResponse> > LoginAsync(LoginResource loginResource)
        {
            var user = await _userManager.FindByEmailAsync(loginResource.Email);

            if (user == null)
            {
                return new GenericResponse <LoginResponse>
                       {
                           Succeeded    = false,
                           ErrorMessage = "The user account does not exist!"
                       }
            }
            ;

            if (!await _userManager.IsEmailConfirmedAsync(user))
            {
                return new GenericResponse <LoginResponse>
                       {
                           Succeeded    = false,
                           ErrorMessage = "The email is not yet verified"
                       }
            }
            ;

            var isPasswordValid = await _userManager.CheckPasswordAsync(user, loginResource.Password);

            if (!isPasswordValid)
            {
                return new GenericResponse <LoginResponse>
                       {
                           Succeeded    = false,
                           ErrorMessage = "The user account does not exist!"
                       }
            }
            ;

            var tokenHandler = new JwtSecurityTokenHandler();
            var secretKey    = Encoding.ASCII.GetBytes(_jwtSetting.SecretKey);

            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[]
                {
                    new Claim(ClaimTypes.NameIdentifier, user.Id),
                    new Claim(ClaimTypes.Email, user.Email)
                }),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(secretKey), SecurityAlgorithms.HmacSha256Signature),
                Expires            = DateTime.UtcNow.AddHours(4)
            };

            var token = tokenHandler.CreateToken(tokenDescriptor);

            return(new GenericResponse <LoginResponse>
            {
                Succeeded = true,
                Data = new LoginResponse
                {
                    Token = tokenHandler.WriteToken(token)
                }
            });
        }
Ejemplo n.º 7
0
        //returnen van een anoniem object
        public async Task <object> GenerateJwtToken(LoginResource identityResource)
        {
            //0. Geen gebruik van de signin manager voor het token-> deze signin manager
            //maakt een autorisatie cookie aan . De signin manager gebruiken (Cookie
            // authenticatie) zou kunnen als backup voor een falend token.

            //=> Token aanmaken na loggedin user  met extra claims + verplichte JWT claims.

            //1. Gebruiker opzoeken in de database met async UserManager en hash vergelijking

            TEntity user;

            try {
                user = await userManager.FindByNameAsync(identityResource.Username);

                var roles = await userManager.GetRolesAsync(user);

                if (user == null || hasher.VerifyHashedPassword(user, user.PasswordHash, identityResource.Password) != PasswordVerificationResult.Success)
                {
                    return(new { error = "Unknown user or password" });
                }

                Console.Write("password verified: {0}", user.PasswordHash);

                //2. claims (key/value) toevoegen
                //2.1 Customised of extra claims, komende van het Identity system (vb. rollen):
                var userClaims = await userManager.GetClaimsAsync(user);

                //await userManager.RemoveClaimsAsync(user, userClaims);

                var myExtraKey = "myExtraKey";

                if (!userClaims.Any(uc => uc.Type == myExtraKey))
                {
                    await userManager.AddClaimAsync(user, new Claim(myExtraKey, "myExtraValue"));
                }
                //combined string van roles kan niet => ClaimTypes.Role
                foreach (var role in roles)
                {
                    if (!userClaims.Any(uc => uc.Type == ClaimTypes.Role && uc.Value == role))
                    {
                        await userManager.AddClaimAsync(user, new Claim(ClaimTypes.Role, role));
                    }
                }

                userClaims = await userManager.GetClaimsAsync(user);


                //2.2. Noodzakelijke claims komende vd JWD spec
                var claims = new List <Claim>
                {
                    //JWT claims zijn ingebouwd in de JWT spec: "sub"scriber, JWT Id
                    new Claim(JwtRegisteredClaimNames.Sub, identityResource.Username), //subscriber
                    new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),

                    /*//extra claims (waardoor toch datastore info beschikbaar wordt)
                     * new Claim(JwtRegisteredClaimNames.Birthdate, identityResource.Birthdate.ToString())*/
                }.Union(userClaims); //nog de extra userClaims toevoegen.

                //3. Sigin credentials met de symmetric key & encryptie methode
                var key   = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["Tokens:Key"]));
                var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); //key en protocol

                //4. aanmaken van het token
                var token = new JwtSecurityToken(
                    issuer: configuration["Tokens:Issuer"],     //onze website
                    audience: configuration["Tokens:Audience"], //gebruikers
                    claims: claims,
                    expires: DateTime.UtcNow.AddMinutes(Convert.ToDouble(configuration["Tokens: Expires"])),
                    signingCredentials: creds //controleert token v
                    );

                //5. user info returnen (vervaldatum als additionele info)
                return(new {
                    token = new JwtSecurityTokenHandler().WriteToken(token), //token generator
                    expiration = token.ValidTo
                });
            } catch (Exception exc) {
                logger.LogError($"Exception thrown when creating JWT: {exc}");
                return(new { error = "Failed to generate JWT token" }); //minimale info ->meer in de logger
            }
        }
Ejemplo n.º 8
0
        public static void PhysiotherapistLogin()
        {
            LoginResource loginResource = new LoginResource();

            loginResource.CreateLogin("*****@*****.**", "Password123");
        }
Ejemplo n.º 9
0
        public static void PatientLogin()
        {
            LoginResource loginResource = new LoginResource();

            loginResource.CreateLogin("*****@*****.**", "Password123");
        }