public IActionResult Logon([FromBody] AppUserLogon user)
        {
            ServicesResult result    = new ServicesResult();
            var            logonUser = _appUserServices.Get(x => (x.Name.Equals(user.Name) || x.Phone.Equals(user.Name)) && x.Pwd.Equals(user.Pwd)).FirstOrDefault();

            if (logonUser != null && logonUser.Id != 0)
            {
                List <Claim> userClaims = new List <Claim>();
                userClaims.Add(new Claim(ClaimTypes.NameIdentifier, logonUser.Id.ToString()));
                userClaims.Add(new Claim(ClaimTypes.Name, logonUser.Name.ToString()));
                userClaims.Add(new Claim(ClaimTypes.Email, logonUser.Email.ToString()));

                string token = _tokenServices.GenerateToken(userClaims);
                result.Result = 200;
                result.Data   = new { user = new { Id = logonUser.Id, Name = logonUser.Name }, token };
            }
            else
            {
                var count = _appUserServices.Get(x => x.Name.Equals(user.Name) || x.Phone.Equals(user.Name)).Count();
                if (count > 0)
                {
                    result.Result = 201;
                    result.Msg    = "请输入正确的用户名密码";
                }
                else
                {
                    result.Result = 204;
                    result.Msg    = "用户名不存在,请注册";
                }
            }
            return(Ok(result));
        }
        /// <summary>
        /// Returns auth token for the validated user.
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        private HttpResponseMessage GetAuthToken(int userId)
        {
            var token    = _tokenServices.GenerateToken(userId);
            var response = Request.CreateResponse(HttpStatusCode.OK, "Authorized");

            response.Headers.Add("Token", token.AuthToken);
            response.Headers.Add("TokenExpiry", ConfigurationManager.AppSettings["AuthTokenExpiry"]);
            response.Headers.Add("Access-Control-Expose-Headers", "Token,TokenExpiry");
            return(response);
        }
Example #3
0
        /// <summary>
        /// Returns auth token for the validated user.
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        private HttpResponseMessage GetAuthToken(int userId)
        {
            var token    = _tokenServices.GenerateToken(userId);
            var response = Request.CreateResponse(HttpStatusCode.OK, "Authorized");

            response.Headers.Add("Token", token.AuthToken);
            response.Headers.Add("TokenExpiry", Convert.ToString(86400));
            response.Headers.Add("Access-Control-Expose-Headers", "Token,TokenExpiry");
            return(response);
        }
        public async Task <ActionResult <dynamic> > Authenticate([FromBody] User user)
        {
            var _user = await _userRepository.GetUser(user.UserName, user.Password);

            var token = _services.GenerateToken(_user);

            return(new
            {
                user = user,
                token = token
            });
        }
Example #5
0
        public void GenerateTokenByUserIdTest()
        {
            const int userId = 1;
            var       maxTokenIdBeforeAdd = _tokens.Max(a => a.TokenId);
            var       tokenEntity         = _tokenServices.GenerateToken(userId);
            var       newTokenDataModel   = new Token()
            {
                AuthToken = tokenEntity.AuthToken,
                TokenId   = maxTokenIdBeforeAdd + 1,
                ExpiresOn = tokenEntity.ExpiresOn,
                IssuedOn  = tokenEntity.IssuedOn,
                UserId    = tokenEntity.UserId
            };

            Assert.Equal(newTokenDataModel.TokenId, _tokens.Last().TokenId);
        }
Example #6
0
        [HttpGet] // Or [AcceptVerbs("GET", "POST")]
        private HttpResponseMessage GetAuthToken(hmisUserBase user)
        {
            var token    = _tokenServices.GenerateToken(user.SID);
            var response = Request.CreateResponse(HttpStatusCode.OK, "Authorized:" + token.AuthToken + "User" + " :" + user);

            response.Headers.Add("Token", token.AuthToken);
            response.Headers.Add("TokenExpiry", ConfigurationManager.AppSettings["AuthTokenExpiry"]);
            response.Headers.Add("Access-Control-Expose-Headers", "Token,TokenExpiry");
            //response.Content = new StringContent("hello Subhamay"+Json(user), Encoding.Unicode);
            //var session = System.Web.HttpContext.Current.Session;
            //if(session!=null)
            //{
            //    if(session["AuthUser"]==null)
            //    {
            //        session["AuthUser"] = token;
            //    }
            //}
            return(response);
        }
        public void Setup()
        {
            _products          = SetUpProducts();
            _tokens            = SetUpTokens();
            _dbEntities        = new Mock <WebApiDbEntities1>().Object;
            _tokenRepository   = SetUpTokenRepository();
            _productRepository = SetUpProductRepository();
            var unitOfWork = new Mock <IUnitOfWork>();

            unitOfWork.SetupGet(s => s.ProductRepository).Returns(_productRepository);
            unitOfWork.SetupGet(s => s.TokenRepository).Returns(_tokenRepository);
            _unitOfWork     = unitOfWork.Object;
            _productService = new ProductServices(_unitOfWork);
            _tokenService   = new TokenServices(_unitOfWork);
            _client         = new HttpClient {
                BaseAddress = new Uri(ServiceBaseURL)
            };
            var tokenEntity = _tokenService.GenerateToken(1);

            _token = tokenEntity.AuthToken;
            _client.DefaultRequestHeaders.Add("Token", _token);
        }
        /// <summary>
        /// Returns auth token for the validated user.
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        private HttpResponseMessage GetAuthenticatedUserInfo(BasicAuthenticationIdentity basicIdentity)
        {
            try
            {
                //Delete old token by userid
                _tokenServices.DeleteByUserEmail(basicIdentity.UserName);
                //Generate new token
                var token = _tokenServices.GenerateToken(basicIdentity.UserName, basicIdentity.EloquaContactId);

                var responseDTO = new ResponseDTO
                {
                    Success    = true,
                    StatusCode = 200,
                    Message    = WellknownResponseMessages.Success
                };

                var response = Request.CreateResponse(HttpStatusCode.OK, responseDTO);
                response.Headers.Add("Token", token.AuthToken);
                response.Headers.Add("TokenExpiry", ConfigurationHelper.AuthTokenExpiry.ToString());
                response.Headers.Add("Access-Control-Expose-Headers", "Token,TokenExpiry");
                return(response);
            }
            catch (Exception ex)
            {
                //Data.EventLog.LogAPIErrorException(userId, string.Empty, ex.ToString());

                return(Request.CreateResponse(HttpStatusCode.InternalServerError, new ResponseDTO
                {
                    Success = false,
                    StatusCode = 500,
                    Message = WellknownResponseMessages.Falied,
                    Errors = new List <string> {
                        ex.Message + "\r\n" + ex.StackTrace
                    }
                }));
            }
        }
Example #9
0
        public async Task <HttpResponseMessage> Authenticate([FromBody] UserCred userCred)
        {
            Debug.WriteLine("Authenticate method has been invoked..");

            //var lcAuthTokenValue = _tokenServices.AuthenticateAsync(userCred.username, userCred.password).Result;
            //return GetAuthToken(userCred.username, lcAuthTokenValue.data.ToString());

            var lcAuthTokenValueTask = _tokenServices.AuthenticateAsync(userCred.username, userCred.password);
            await Task.WhenAll(lcAuthTokenValueTask);

            IUserServices userService = new UserServices();

            dynamic value = lcAuthTokenValueTask.Result;

            var id               = ((Business_Services.Models.Helpers.ResponseWithToken)value).errorId;
            var errorMessage     = ((Business_Services.Models.Helpers.ResponseWithToken)value).errorMessage;
            var tokenValue       = ((Business_Services.Models.Helpers.ResponseWithToken)value).tokenValue;
            var pwdChange        = ((Business_Services.Models.Helpers.ResponseWithToken)value).changePassword;
            var authenticateData = ((Business_Services.Models.Helpers.ResponseWithToken)value).authenticateResult;


            if (id == 0)
            {
                if (pwdChange == "Y")
                {
                    var details = userService.getPartialUserDetailsAsync(authenticateData.AuthorizationToken, userCred.username, userCred.Is_New_MobileUser);

                    await Task.WhenAll(details);

                    Business_Services.Models.User userDetails = (Business_Services.Models.User)details.Result.data;
                    //Debug.WriteLine(userDetails.first_name);

                    var token = _tokenServices.GenerateToken(userCred.username, userCred.password, userDetails.ClientId, authenticateData.AuthorizationToken,
                                                             userDetails.username, userCred.resourcename, userCred.log, userDetails.is_enrolled, userCred.username);

                    authenticateData.AuthorizationToken = token;

                    var responseChangePwd = Request.CreateResponse(HttpStatusCode.OK, new ResponseModel
                    {
                        status = new Status {
                            CustomErrorCode = 100, Message = "success"
                        },
                        data = authenticateData
                    });

                    return(responseChangePwd);
                }
                else
                {
                    var GetTokenTask = GetAuthTokenAsync(userCred.username, userCred.password, tokenValue.ToString(),
                                                         userCred.Is_New_MobileUser, userCred.username, userCred.resourcename, userCred.log);
                    await Task.WhenAll(GetTokenTask);

                    return(GetTokenTask.Result);
                }
            }
            else
            {
                var responseInvalidUser = Request.CreateResponse(HttpStatusCode.OK, new ResponseModel
                {
                    status = new Status {
                        CustomErrorCode = id, Message = errorMessage
                    },
                    data = ""
                });

                return(responseInvalidUser);
            }
        }