Beispiel #1
0
        private static async Task <AuthenticationResponseModel> GetResponse(object requestModel, string route)
        {
            var request = new HttpRequestMessage
            {
                RequestUri = new Uri(route),
                Method     = HttpMethod.Post,
                Content    = new StringContent(JsonConvert.SerializeObject(requestModel), Encoding.UTF8, "application/json")
            };

            HttpClient httpClient = new HttpClient();
            var        response   = await httpClient.SendAsync(request);

            var responseString = await response.Content.ReadAsStringAsync();

            AuthenticationResponseModel responseModel = JsonConvert.DeserializeObject <AuthenticationResponseModel>(responseString);

            if (responseModel != null)
            {
                return(responseModel);
            }

            return(new AuthenticationResponseModel
            {
                Success = false,
                Errors = new[] { "Request failed" }
            });
        }
        public async Task <IActionResult> Login(string username, string password)
        {
            try
            {
                var user = await _userManager.Users.FirstOrDefaultAsync(model => model.NormalizedUserName == _userManager.NormalizeKey(username));

                var validCredentials = await _signInManager.CheckPasswordSignInAsync(user, password, false);

                if (validCredentials == SignInResult.Success)
                {
                    var token = GetAuthenticatedToken(user);
                    var model = new AuthenticationResponseModel
                    {
                        Token        = token.ToString(),
                        Username     = username,
                        RefreshToken = "refresh token goes here!"
                    };
                    return(Ok(model));
                }
                return(Unauthorized());
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("", ex, null);
            }
            return(BadRequest(ModelState));
        }
Beispiel #3
0
        public async Task <AuthenticationResponseModel> GetTokenAsync(AuthenticationRequestModel model)
        {
            var response = new AuthenticationResponseModel();
            var user     = await _userManager.FindByEmailAsync(model.Email);

            if (user == null)
            {
                response.IsAuthenticated = false;
                response.Message         = $"No Accounts Registered with {model.Email}.";
                return(response);
            }
            if (await _userManager.CheckPasswordAsync(user, model.Password))
            {
                response.IsAuthenticated = true;
                JwtSecurityToken jwtSecurityToken = await CreateJwtToken(user);

                response.Token    = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);
                response.Email    = user.Email;
                response.UserName = user.UserName;
                var rolesList = await _userManager.GetRolesAsync(user).ConfigureAwait(false);

                response.Roles = rolesList.ToList();
                return(response);
            }
            response.IsAuthenticated = false;
            response.Message         = $"Incorrect Credentials for user {user.Email}.";
            return(response);
        }
Beispiel #4
0
        public async Task <IActionResult> AuthenticateUser([FromBody] AuthenticateUserRequest request)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            string token;

            if (string.IsNullOrEmpty(request.UniqueId))
            {
                var identity = await GetClaimsIdentity(request);

                if (identity == null)
                {
                    _logger.LogInformation($"Invalid username ({request.User}) or password ({request.Password})");
                    return(BadRequest("Invalid credentials"));
                }

                token = GetTokenFromIdentity(identity);
            }
            else
            {
                var identity = await GetClaimsIdentity(request);

                if (identity == null)
                {
                    _logger.LogInformation($"Invalid Phone ({request.User}) or password ({request.Password})");
                    return(BadRequest(_mobileSecurityOptions.InvalidCredentialsErrorMessage));
                }

                token = GetTokenFromIdentity(identity);
            }

            // Serialize and return the response
            var response = new AuthenticationResponseModel
            {
                access_token = token,
                expires_in   = (int)_jwtOptions.ValidFor.TotalSeconds
            };

            return(Ok(response));
        }
Beispiel #5
0
        public async Task <IActionResult> AuthenticateUser([FromBody] AuthenticateUserRequest request)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            string token;

            // verific daca userul exista si daca da, il returneaza din baza de date
            var userInfo = await _mediator.Send(new ApplicationUser
            {
                Email    = request.Email,
                Password = request.Password
            });

            ClaimsIdentity identity;

            if (!userInfo.IsAuthenticated)
            {
                _logger.LogInformation($"Invalid username ({request.Email}) or password ({request.Password})");
                return(Unauthorized("Invalid credentials"));
            }

            // Get the generic claims
            identity = new ClaimsIdentity(await GetGenericIdentity(request.Email, userInfo.NgoId.ToString(), UserType.Assistant.ToString()),
                                          new[]
            {
                new Claim(ClaimsHelper.UserIdProperty, userInfo.UserId.ToString(), ClaimValueTypes.Boolean)
            });

            //var identity = await GetClaimsIdentity(request);
            if (identity == null)
            {
                _logger.LogInformation($"Invalid username ({request.Email}) or password ({request.Password})");
                return(Unauthorized("Invalid credentials"));
            }

            token = GetTokenFromIdentity(identity, _jwtOptions.IssuedAt.Add(TimeSpan.FromHours(0.5)));

            // save the temporary token
            if (!_accountService.SaveTemporaryToken(userInfo.UserId, token))
            {
                return(Unauthorized("Token issue"));
            }

            var phone = userInfo.Phone.StartsWith('0') ? userInfo.Phone.Remove(0, 1) : userInfo.Phone;

            string result = await _authy.PhoneVerificationRequestAsync(
                "+40",
                phone
                );

            // Serialize and return the response
            var response = new AuthenticationResponseModel
            {
                access_token = token,
                expires_in   = (int)TimeSpan.FromHours(0.5).TotalSeconds,      //(int)_jwtOptions.ValidFor.TotalSeconds,
                first_login  = userInfo.FirstAuthentication,
                phone_verification_request = result
            };

            return(Ok(response));
        }