Esempio n. 1
0
        public async Task <IActionResult> GetToken([FromBody] GetTokenModel model)
        {
            var handler = _handlerFactory(model.GrantType);

            if (handler == null)
            {
                return(_responseService.GenerateResponse(HttpStatusCode.BadRequest, $"Grant Type \"{model.GrantType}\" is not supported."));
            }

            var result = await handler.Authenticate(model);

            if (result == null)
            {
                return(_responseService.GenerateResponse(HttpStatusCode.BadRequest, "The credentials provided were invalid."));
            }

            if (result.RequiresTwoFactor || result.RequiresExternal)
            {
                return(_responseService.GenerateResponse(HttpStatusCode.BadRequest, result));
            }

            if (result.IsLockedOut)
            {
                return(_responseService.GenerateResponse(HttpStatusCode.BadRequest, "This account has been locked out, please try again later."));
            }

            if (result.User == null)
            {
                return(_responseService.GenerateResponse(HttpStatusCode.BadRequest, "The credentials provided were invalid."));
            }

            var token = await _jwtService.GenerateToken(result.User);

            return(_responseService.GenerateResponse(HttpStatusCode.OK, token));
        }
Esempio n. 2
0
        public async Task <bool> LoginAsync(string username, string password, bool rememberMe)
        {
            string errorMessage;

            try
            {
                GetTokenModel model = new GetTokenModel()
                {
                    Username   = username,
                    Password   = password,
                    RememberMe = rememberMe
                };

                await RetrieveTokenAsync(model);
                await UpdateUserInfoAsync();

                LastUpdateIpTime = DateTime.Now;
                return(true);
            }
            catch (ApiException)
            {
                errorMessage = "Unauthorized";
            }
            catch (Exception ex)
            {
                errorMessage = ex.Message;
            }

            await ShowErrorAsync(errorMessage);

            return(false);
        }
Esempio n. 3
0
        public IActionResult Login([FromForm] UserLogin form)
        {
            try
            {
                var user     = GetUser(form.Email);
                var Userrole = user.Role;
                var Userid   = user.Email;
                var UserName = user.Fname;

                GetTokenModel token = GetToken.getToken(Userrole, Userid, UserName);

                var text = _service.LoginUser(form);
                if (text == true)
                {
                    return(Ok(token));
                }
                else
                {
                    return(BadRequest());
                }
            }
            catch
            {
                return(BadRequest());
            }
        }
        public AuthUser Login(string email, string password)
        {
            var request = new RestRequest(@"/token", Method.POST);

            var encodedBody = string.Format("username={0}&password={1}&grant_type=password", email, password);

            request.AddParameter("application/x-www-form-urlencoded", encodedBody, ParameterType.RequestBody);
            request.AddParameter("Content-Type", "application/x-www-form-urlencoded", ParameterType.HttpHeader);
            IRestResponse response  = client.Execute(request);
            string        result    = response.Content;
            GetTokenModel getParams = JsonConvert.DeserializeObject <GetTokenModel>(result);

            client.Authenticator = new OAuth2AuthorizationRequestHeaderAuthenticator(getParams.access_token, "bearer");

            if (!String.IsNullOrEmpty(getParams.access_token) && email == getParams.userName)
            {
                var user = new AuthUser()
                {
                    accessToken = getParams.access_token,
                    Email       = getParams.userName,
                    Name        = getParams.FirstName,
                    Surname     = getParams.LastName,
                    Id          = getParams.userId
                };
                return(user);
            }
            else
            {
                return(null);
            }
        }
Esempio n. 5
0
        private async Task <TokenModel> RetrieveTokenAsync(GetTokenModel model)
        {
            var tokenInfo = await _authApi.RetrieveTokenAsync(model);

            _preferencesService.TokenInfo = tokenInfo;
            return(tokenInfo);
        }
        public void  GetTokenTest()
        {
            var v = "";

            var models = new GetTokenModel();

            models.OpMid     = "aaaa1bbbb2cccc3dddd4eeee5ffff6ee";
            models.CardNo    = "7413159981000227";
            models.CallTime  = DateTime.Now.ToString("yyyyMMddhhmmss");
            models.MachineID = "Machine0001";
            models.SetMask();

            var data     = JsonConvert.SerializeObject(models);
            var postData = new List <KeyValuePair <string, string> >();

            postData.Add(new KeyValuePair <string, string>("v", data));


            var formContent = new FormUrlEncodedContent(postData);

            var result = client.Post("http://localhost:17805/api/Security/GetToken", formContent);
            //var result=client.p

            //client.BaseAddress = new Uri("http://localhost:17805/");

            //client.DefaultRequestHeaders.Accept.Clear();
            //client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            //HttpResponseMessage response = await client.PostAsync("api/Security/GetToken", formContent);
            //response.EnsureSuccessStatusCode();
        }
Esempio n. 7
0
        public IActionResult loginEmail([FromBody] LoginEmail logins)
        {
            Hash hash = new Hash();

            logins.EmpPassword = hash.HashPassword(logins.EmpPassword);

            if (_service.LoginEmail(logins))
            {
                var data    = _service.GetEmployeeByEmail(logins.EmpEmail);
                var Emprole = data.PositionPId;
                var EmpName = data.EmpName;
                var Empid   = data.EmpId;



                GetTokenModel token = GetToken.getToken(Emprole, Empid, EmpName);

                return(Ok(new
                {
                    token = token.Token,
                    expiration = token.Expiretion
                }));
            }
            else
            {
                return(BadRequest("there error"));
            }
        }
Esempio n. 8
0
 public Task <TokenModel> RetrieveTokenAsync(GetTokenModel model)
 {
     return(Url("token")
            .FormUrlEncoded()
            .Param(nameof(model.Username), model.Username)
            .Param(nameof(model.Password), model.Password)
            .Param(nameof(model.RememberMe), model.RememberMe.ToString())
            .PostAsync <TokenModel>());
 }
Esempio n. 9
0
        public void IsValidTest()
        {
            GetTokenModel model1   = new GetTokenModel();
            var           result1  = model1.IsValid <ApiResult>();
            var           expected = EnumItem.Get(Ref.ErrorCode._002).FinalValue;
            var           actual   = result1.ErrorCode;

            Assert.AreEqual(expected, actual);
        }
        public async System.Threading.Tasks.Task <IActionResult> GetAsync([FromBody] GetTokenModel user)
        {
            var currentUser = await _userManager.FindByEmailAsync(user.Email);

            if (currentUser == null)
            {
                currentUser = await _userManager.FindByNameAsync(user.Email);
            }


            var result = await _signInManager.PasswordSignInAsync(user.Email, user.Password, true, lockoutOnFailure : false);

            if (result.Succeeded)
            {
                _logger.LogInformation($"User {user.Email} logged in.");
            }
            else
            {
                _logger.LogError($"User {user.Email} error logged in.");
                return(Ok(new
                {
                    error = "Unauthorized"
                }));
            }
            var currentUserRole = await _userManager.GetRolesAsync(currentUser);

            var role = currentUserRole[0];


            var authClaims = new[]
            {
                new Claim(JwtRegisteredClaimNames.Sub, currentUser.Email),
                new Claim(JwtRegisteredClaimNames.Jti, currentUser.Email.ToString()),
                new Claim(ClaimTypes.Role, role)
            };

            var token = new JwtSecurityToken(
                issuer: _authOptions.Issuer,
                audience: _authOptions.Audience,
                expires: DateTime.Now.AddHours(_authOptions.ExpiresInMinutes),
                claims: authClaims,
                signingCredentials: new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_authOptions.SecureKey)),
                                                           SecurityAlgorithms.HmacSha256Signature)
                );

            var rt = CreateRefreshToken(currentUser.Id, currentUser.Id);
            await _tk.CreateAsync(rt);

            return(Ok(new
            {
                token = new JwtSecurityTokenHandler().WriteToken(token),
                expiration = token.ValidTo,
                id = currentUser.Id,
                userRole = role,
                userName = currentUser.Email,
            }));
        }
Esempio n. 11
0
        public async Task <IActionResult> GenerateToken([FromBody] GetTokenModel model)
        {
            var token = await this.tokenService.GetTokenAsync(model.Email, model.OrganisationId, model.AppSecret);

            if (!string.IsNullOrWhiteSpace(token))
            {
                return(this.Ok(token));
            }

            return(this.StatusCode((int)HttpStatusCode.Unauthorized));
        }
Esempio n. 12
0
        public IActionResult GetToken([FromBody] GetTokenModel getTokenModel)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }
            var dreamerUser = SecurityRepository.Login(getTokenModel.Email, getTokenModel.Password);

            if (dreamerUser == null)
            {
                return(Unauthorized());
            }
            return(Json(BuildToken(dreamerUser)));
        }
Esempio n. 13
0
        public ActionResult <TokenModel> Token([FromBody] GetTokenModel model)
        {
            if (model.Username != "testuser" || model.Password != "1234567")
            {
                return(Unauthorized());
            }

            var token = OAuthTokenProvider.GetAccessToken(new TokenOptions
            {
                Identifier = model.Username
            });

            return(Created("", new TokenModel
            {
                Token = token
            }));
        }
Esempio n. 14
0
        public IActionResult SignUpUser([FromForm] User user)
        {
            var Userrole = "";
            var Userid   = "";
            var UserName = "";

            if (user.Email == "*****@*****.**")
            {
                user.Role = "admin";
                Userrole  = user.Role;
                Userid    = user.Email;
                UserName  = user.Fname;
            }
            else
            {
                user.Role = "user";
                Userrole  = user.Role;
                Userid    = user.Email;
                UserName  = user.Fname;
            }



            try
            {
                var text = _service.SignUpUser(user);
                if (text > 0)
                {
                    GetTokenModel token    = GetToken.getToken(Userrole, Userid, UserName);
                    Boolean       SendCode = SendMail.SendloginCode(text.ToString(), user.Email, user.Fname);
                    return(Ok(token));
                }
                else
                {
                    return(BadRequest());
                }
            }
            catch
            {
                return(BadRequest());
            }
        }
Esempio n. 15
0
        public static GetTokenModel getToken(string role, string id, string name)
        {
            var claims = new[]
            {
                new Claim(JwtRegisteredClaimNames.Sub, role),
                new Claim(JwtRegisteredClaimNames.NameId, id),
                new Claim(JwtRegisteredClaimNames.UniqueName, name),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
            };

            var signingkey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("creativesoftware@12345moratuwaproject"));

            var token = new JwtSecurityToken(
                issuer: "http://oec.com",
                audience: "http://oec.com",
                expires: DateTime.UtcNow.AddDays(1),
                claims: claims,
                signingCredentials: new Microsoft.IdentityModel.Tokens.SigningCredentials(signingkey, SecurityAlgorithms.HmacSha256)



                );
            //    return Ok(new
            //    {
            //        token = new JwtSecurityTokenHandler().WriteToken(token),
            //        expiration = token.ValidTo
            //    });

            var toke       = new JwtSecurityTokenHandler().WriteToken(token);
            var expiration = token.ValidTo;

            var send = new GetTokenModel {
                Token = toke, Expiretion = expiration
            };

            // return new string[] { toke, expiration.ToString() };
            return(send);
        }
        public IActionResult loginId([FromBody] LoginId logins)
        {
            if (_service.LoginId(logins))
            {
                var data    = _service.GetEmployeeById(logins.EmpId);
                var Emprole = data.PositionPId;
                var Empid   = data.EmpId;
                var EmpName = data.EmpName;


                GetTokenModel token = GetToken.getToken(Emprole, Empid, EmpName);

                return(Ok(new
                {
                    token = token.Token,
                    expiration = token.Expiretion
                }));
            }
            else
            {
                return(BadRequest("there error"));
            }
        }
        public async Task <IActionResult> Login(LoginModel LoginModel)
        {
            LoginModel.clientId     = _config["Client_Id"];
            LoginModel.clientSecret = _config["Client_Secret"];
            GetTokenModel       token    = null;
            HttpResponseMessage response = await _userService.Login(LoginModel);

            if (response.IsSuccessStatusCode)

            {
                token = response.Content.ReadAsAsync <GetTokenModel>().Result;
            }
            if (token != null && token.User != null)
            {
                UserProfileModel User = _mapper.Map <UserProfileModel>(token.User);
                User.Language = "en";
                User.Roles    = token.roles;

                _sessionHandler.Token       = token.access_token;
                _sessionHandler.UserProfile = User;
                _sessionHandler.Language    = User.Language;
                return(RedirectToAction("Index", "Home"));
            }
            else
            {
                try
                {
                    TempData["Message"] = response.Content.ReadAsAsync <CustomResponse>().Result.Value;
                }
                catch (Exception)
                {
                    TempData["Message"] = response.Content.ReadAsStringAsync().Result;
                }
                return(View(LoginModel));
            }
        }
    public async Task <IHttpActionResult> CreateToken([FromBody] GetTokenModel model)
    {
        if (model.grant_type == "password" && !Membership.ValidateUser(model.username, model.password))
        {
            return(Json(new { success = false, status = 403, message = "Cannot validate your username or password" }));
        }

        if (model.grant_type == "admin" && !User.IsInRole("administrators"))
        {
            return(Json(new { success = false, status = 403, message = "You are not in administrator role" }));
        }

        var ip = this.GetClientIp();

        if (model.grant_type == "local_network" && !ip.StartsWith("1"))
        {
            return(Json(new { success = false, status = 403, message = "local_network request must be done within specified IP address range " + ip }));
        }

        model.expiry = DateTime.Today.AddMonths(1);// give it 1 month validity
        var tokenService = ObjectBuilder.GetObject <ITokenService>();

        var context = new SphDataContext();
        var user    = await context.LoadOneAsync <UserProfile>(x => x.UserName == model.username);

        if (null == user)
        {
            user = new UserProfile
            {
                UserName    = model.username,
                Designation = "Device",
                HasChangedDefaultPassword = true,
                Email       = $"{model.username}@pos.com.my",
                Department  = "PPL",
                IsLockedOut = false
            };
            var profile = new Profile
            {
                UserName        = model.username,
                Password        = "******",
                ConfirmPassword = "******",
                Roles           = new[] { "devices" },
                Designation     = "Device",
                Email           = $"{model.username}@pos.com.my"
            };
            var ok = await AddUserAsync(profile).ConfigureAwait(false);

            if (!ok)
            {
                return(Invalid("Cannot create device with id " + model.username));
            }
        }

        // get existing token that still have at least 14 days validity
        var repos = ObjectBuilder.GetObject <ITokenRepository>();
        var lo    = await repos.LoadAsync(model.username, DateTime.Today.AddDays(14));

        var existing = lo.ItemCollection.LastOrDefault();

        if (null != existing)
        {
            var token1 = existing.GenerateToken();
            return(Json(existing.ToJson().Replace("\"WebId\"", $"\"token\":\"{token1}\",\r\n\"WebId\"")));
        }

        var roles = Roles.GetRolesForUser(model.username);
        var claim = await tokenService.CreateTokenAsync(user, roles, model.expiry);

        var token = claim.GenerateToken();
        var json  = claim.ToJson()
                    .Replace("\"WebId\"", $"\"token\":\"{token}\",\r\n\"WebId\"");

        return(Json(json));
    }