コード例 #1
0
        public IActionResult Post(ApiLoginModel loginModel)
        {
            try {
                ClaimsPrincipal userPrincipal = authentcationService.ValidateAndGetUser(loginModel.Username, loginModel.Password);

                logger.LogLoginEvent("Api token requested", HttpContext, loginModel.Username);

                return(Ok(new {
                    token = new JwtSecurityTokenHandler().WriteToken(new JwtSecurityToken(
                                                                         issuer: settings.TokenIssuer,
                                                                         audience: settings.TokenAudience,
                                                                         claims: userPrincipal.Claims,
                                                                         expires: DateTime.UtcNow.AddDays(settings.TokenExpireTimeInDays),
                                                                         signingCredentials: new SigningCredentials(new SymmetricSecurityKey(
                                                                                                                        Convert.FromBase64String(settings.TokenSigningKey)), SecurityAlgorithms.HmacSha256)
                                                                         ))
                }));
            } catch (InvalidCredentialException) {
                logger.LogFailedLogin("Api token request with invalid credentials", HttpContext, loginModel.Username);
                return(Unauthorized());
            } catch (UnauthorizedAccessException) {
                logger.LogFailedLogin("Api token request with missing Permissions", HttpContext, loginModel.Username);
                return(Unauthorized());
            }
        }
コード例 #2
0
        /// <inheritdoc />
        public async Task <ApiLoginResult> LoginAsync(ApiLoginModel model)
        {
            if (string.IsNullOrEmpty(model.Token))
            {
                throw new ArgumentException("Authentication token missing.");
            }

            var authResult = await Authenticate(new ApiLoginModel
            {
                Username = model.Username,
                Token    = model.Token
            });

            string responseContent = await authResult.Content.ReadAsStringAsync();

            if (authResult.StatusCode == HttpStatusCode.BadRequest)
            {
                return new ApiLoginResult {
                           HasError = true
                }
            }
            ;

            return(JsonConvert.DeserializeObject <ApiLoginResult>(responseContent));
        }
コード例 #3
0
        public async Task <IActionResult> Login([FromForm] ApiLoginModel model)
        {
            var result = await _signInManager.PasswordSignInAsync(model.Name, model.Pwd, true, false);

            if (result.Succeeded)
            {
                var signingKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_settings.Value.SecretKey));
                var options    = new TokenProviderOptions()
                {
                    Issuer             = "EntityAbstract",
                    Audience           = "EntityAbstractAudience",
                    SigningCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256)
                };
                var tpm   = new TokenProvider(options);
                var token = await tpm.GenerateToken(model.Name, model.Pwd);

                var user = await _userManager.FindByNameAsync(model.Name);

                return(token != null ? (IActionResult)Json(token) : BadRequest());
            }

            if (result.IsLockedOut)
            {
                return(BadRequest("Lockout"));
            }
            else
            {
                return(BadRequest("Invalid login attempt"));
            }
        }
コード例 #4
0
        public HttpResponseMessage Post([FromBody] ApiLoginModel model)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    throw new Exception("Datos invalidos");
                }

                if (!WebSecurity.Login(model.Email, model.Password))
                {
                    throw new Exception("Usuario o contraseña incorrectos.");
                }

                var user = userService.GetUserbyEmail(model.Email);

                if (user == null)
                {
                    throw new Exception("No se encontró el usuario.");
                }


                return(this.Request.CreateResponse(HttpStatusCode.OK, new { Message = "Se ha iniciado sesión.", UserCode = user.Code, UserId = user.UserId }));
            }
            catch (Exception ex)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex.Message));
            }
        }
コード例 #5
0
 public CarStoreRestAuthenticator(string consumerName, string consumerPassword, string loginUrl, string refreshUrl)
 {
     _apiLoginModel = new ApiLoginModel {
         Name = consumerName, Password = consumerPassword
     };
     _loginUrl   = loginUrl;
     _refreshUrl = refreshUrl;
 }
コード例 #6
0
        public async Task <IActionResult> Login(ApiLoginModel model)
        {
            ApiLoginResult result = await _authenticationService.LoginAsync(model);

            if (string.IsNullOrEmpty(result.Token))
            {
                return(Unauthorized()); //The external API returns a bad request instead of unauthorized when the user credentials are wrong, hence we have to use this ugly check.
            }
            result.Token = _tokenService.GenerateToken(result.Token);
            return(Ok(GenerateSuccessfulResponse(result)));
        }
コード例 #7
0
        public async Task <ActionResult> Login([FromBody] ApiLoginModel model)
        {
            Repository.ClearExpiredLogins(TimeoutHours);

            if (ModelState.IsValid == true)
            {
                Microsoft.AspNetCore.Identity.SignInResult signInResult = await this.IdentityService.LoginAsync(model, mustBeInRole : "Api");

                if (signInResult != null)
                {
                    if (signInResult.Succeeded == true)
                    {
                        ApiSessionModel apiSessionModel = Repository.FetchByLogin(model);

                        if (apiSessionModel != null)
                        {
                            apiSessionModel.SessionStarted = DateTime.Now;
                        }
                        else
                        {
                            // store username, password and email for later in in memory repo
                            apiSessionModel = new ApiSessionModel()
                            {
                                Email          = model.Email,
                                Password       = model.Password,
                                Token          = Guid.NewGuid().ToString().Replace("-", string.Empty),
                                SessionStarted = DateTime.Now
                            };
                            Repository.Create(apiSessionModel);
                        }

                        Repository.Save();

                        // return magic key
                        Response.Headers.Add(new KeyValuePair <string, StringValues>(HeaderTokenName, apiSessionModel.Token));

                        return(Ok());
                    }
                    else
                    {
                        return(new StatusCodeResult(403)); // forbidden
                    }
                }
                else
                {
                    return(new StatusCodeResult(403)); // forbidden
                }
            }
            else
            {
                return(new StatusCodeResult(403)); // forbidden
            }
        }
コード例 #8
0
        [Post("/api/authentication/login")] //Refit does not support using constants. See: https://github.com/reactiveui/refit/issues/263
        public async Task <HttpResponseMessage> Authenticate(ApiLoginModel loginData)
        {
            if (!string.IsNullOrEmpty(loginData.Token))
            {
                ApiLoginResult result = new ApiLoginResult {
                    Token = loginData.Token, Expires = 0, HasError = false, Username = loginData.Username
                };

                HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new StringContent(JsonConvert.SerializeObject(result))
                };
                return(response);
            }
            return(new HttpResponseMessage(HttpStatusCode.BadRequest));
        }
コード例 #9
0
 public IActionResult LogIn([FromBody] ApiLoginModel request)
 {
     try
     {
         var customer = authService.AuthenticateCustomer(request, out string token);
         if (customer != null)
         {
             var model = new {
                 customer.Id,
                 Name = customer.ArabicName,
                 customer.Email,
                 customer.UserName,
                 customer.Mobile,
                 customer.Pocket,
                 customer.Address,
                 Image = AppSession.AppURL + AppSession.CustomerUploads + "/" + customer.ImageName,
                 token
             };
             return(Ok(new ApiResponseModel
             {
                 Status = EN_ResponseStatus.Success,
                 Message = "Logged in successflly",
                 Data = model,
                 Errors = null
             }));
         }
         return(Ok(new ApiResponseModel
         {
             Status = EN_ResponseStatus.Faild,
             Message = "Invalid email or password",
             Data = null,
             Errors = new string[] { "Invalid email or password" }
         }));
     }
     catch (Exception ex)
     {
         return(Ok(new ApiResponseModel
         {
             Status = EN_ResponseStatus.Faild,
             Message = "Error: " + ex.Message,
             Data = null,
             Errors = new string[] { "Error: " + ex.Message }
         }));
     }
 }
コード例 #10
0
        public RegisterResult Register([FromBody] PatientRegistrationModel registerModel)
        {
            if (!ModelState.IsValid)
            {
                return(new RegisterResult()
                {
                    Success = false, Message = "Заполните все необходимые поля"
                });
            }

            if (_dbContext.PatientProfiles.FirstOrDefault(x => x.PhoneNumber == registerModel.PhoneNumber) == null)
            {
                string         apiKey  = GenerateApiKey();
                PatientProfile patient = new PatientProfile()
                {
                    Email        = registerModel.Email,
                    Gender       = registerModel.Gender,
                    RegisterDate = DateTime.Now,
                    BirthdayDate = registerModel.BirthdayDate,
                    Name         = registerModel.Name,
                    LastName     = registerModel.LastName,
                    SecondName   = registerModel.SecondName,
                    PhoneNumber  = registerModel.PhoneNumber,
                    PolicyNumber = registerModel.PolicyNumber,
                };
                _dbContext.PatientProfiles.Add(patient);
                _dbContext.SaveChanges();
                ApiLoginModel apiLogin = new ApiLoginModel
                {
                    PatientProfile = patient,
                    ApiKey         = apiKey
                };
                _dbContext.ApiAuthentication.Add(apiLogin);
                _dbContext.SaveChanges();
                return(new RegisterResult()
                {
                    Success = true, ApiKey = apiKey
                });
            }
            return(new RegisterResult()
            {
                Success = false, Message = "Пользователь с таким номером уже зарегистрирован"
            });
        }
コード例 #11
0
        public void Can_Get_Tokens_And_Add_In_Header()
        {
            WebRequest.RegisterPrefix("test", new TestWebRequestCreate());
            RestClient     client     = new RestClient("test://");
            RestRequest    request    = new RestRequest(Method.GET);
            string         response   = JsonConvert.SerializeObject(new { accessToken = "accessTest", refreshToken = "refreshTest" });
            TestWebRequest webRequest = TestWebRequestCreate.CreateTestRequest(response);

            _restAuthenticator.Authenticate(client, request);
            ApiLoginModel apiLoginModel = JsonConvert.DeserializeObject <ApiLoginModel>(webRequest.ContentAsString());

            Assert.True(request.Parameters[0].Name == "Authorization");
            Assert.True((string)request.Parameters[0].Value == "Bearer accessTest");
            Assert.True(request.Parameters[0].Type == ParameterType.HttpHeader);
            Assert.True(_restAuthenticator.AccessToken == "accessTest");
            Assert.True(_restAuthenticator.RefreshToken == "refreshTest");
            Assert.Equal(_consumerName, apiLoginModel.Name);
            Assert.Equal(_consumerPassword, apiLoginModel.Password);
        }
コード例 #12
0
        public void Login()
        {
            ApiLoginModel model = new ApiLoginModel()
            {
                Email = "*****@*****.**", Password = "******"
            };

            using (RESTClient restClient = new RESTClient(BaseUrl))
            {
                RestResult apiResult = restClient.Execute("Authorize/Login", RestSharp.Method.POST, jsonBody: model);

                Assert.True(apiResult.StatusCode == StatusCodes.Status200OK, "Logging in was not sucessful.");

                this.ApiToken  = apiResult.Headers.Find(h => h.Name == "ApiToken").Value.ToString();
                this.ApiCookie = apiResult.Cookies.Find(c => c.Name == AuthCookieName);

                Assert.True(this.ApiToken != string.Empty, "A token was not returned");
            }
        }
コード例 #13
0
        public async Task <IActionResult> Login([FromBody] ApiLoginModel model)
        {
            var client  = new RestClient("http://customerapi/api/customers");
            var request = new RestRequest($"email/{model.Username}");

            var response = client.Get <User>(request);
//            var user = _users.FirstOrDefault(x => x.Username == model.Username);

            var user = response.Data;

            if (!response.IsSuccessful) // TODO: Implement proper authentication in v2
            {
                return(Unauthorized("Could not login with the provided credentials"));
            }

            var jwt = _jwt.GenerateAccessToken(user);

            return(Ok(new ApiJwtModel()
            {
                access_token = jwt.Item1, expires_in = jwt.Item2
            }));
        }
コード例 #14
0
        public async Task <IActionResult> Login([FromBody] ApiLoginModel model)
        {
            var user = await _userManager.FindByNameAsync(model.Username);

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

            var loginResult = await _signInManager.CheckPasswordSignInAsync(user, model.Password, false);

            if (loginResult.Succeeded)
            {
                var tokenResult = await CreateTokenAndSignIn(user);

                // also sign in default scheme
                await SignInDefaultScheme(user);

                return(Ok(tokenResult));
            }

            return(Unauthorized());
        }
コード例 #15
0
        public Customer AuthenticateCustomer(ApiLoginModel request, out string token)
        {
            token = string.Empty;
            var customer = _userManagementService.IsValidCustomer(request.Email, request.Password);

            if (customer != null)
            {
                var claims          = new[] { new Claim(ClaimTypes.Email, request.Email) };
                var key             = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_tokenManagement.Secret));
                var credentials     = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature);
                var expireDate      = DateTime.Now.AddDays(_tokenManagement.AccessExpiration);
                var tokenDiscriptor = new SecurityTokenDescriptor
                {
                    Subject            = new ClaimsIdentity(claims),
                    Expires            = expireDate,
                    SigningCredentials = credentials
                };
                var tokenHandler = new JwtSecurityTokenHandler();
                var tokenObj     = tokenHandler.CreateToken(tokenDiscriptor);
                token = tokenHandler.WriteToken(tokenObj);
            }
            return(customer);
        }
コード例 #16
0
 public ApiSessionModel FetchByLogin(ApiLoginModel model)
 {
     return((from ApiSessionModel l in this.FetchAll
             where l.Email == model.Email && l.Password == model.Password
             select l).FirstOrDefault());
 }
コード例 #17
0
 public async Task <SignInResult> LoginAsync(ApiLoginModel model, string mustBeInRole = "")
 {
     return(await this.LoginAsync(model.Email, model.Password, mustBeInRole));
 }