Exemplo n.º 1
0
        public async Task <TokenUser> CheckUserAndGetInfoAysnc(TokenLoginModel loginModel)
        {
            var expireMin = _configuration.GetValue <int>("RedisConfig:CacheExpireMin");
            var cacheKey  = "TokenUser";

            string[] includes  = { "Roles" };
            TimeSpan expiresIn = TimeSpan.FromMinutes(expireMin);

            if (_time.AddMinutes(expireMin + 1) < DateTime.Now)
            {
                _model = null; _time = DateTime.Now;
            }

            if (_model == null)
            {
                _model = _redisRepository.GetAllCachedData(cacheKey, expiresIn, includes, true);
                if (_model != null)
                {
                    var find = _model.FirstOrDefault(user => user.Username == loginModel.Username && user.Password == loginModel.Password && user.IsSuspended == false);
                    return(find);
                }
                //redis patlarsa
                _model = await _context.TokenUsers.
                         Include(i => i.Roles).AsNoTracking().        //// Microsoft.EntityFrameworkCore.Proxies paketini indirip UseLazyLoadingProxies() methodu da kullanılabilir
                         ToListAsync();
            }
            var findFaster = (_model ?? throw new InvalidOperationException()).FirstOrDefault(user => user.Username == loginModel.Username && user.Password == loginModel.Password && user.IsSuspended == false);

            return(findFaster);
        }
Exemplo n.º 2
0
        public IActionResult Login(TokenLoginModel model)
        {
            try
            {
                if (Globals.AllowFormsLogin == false)
                {
                    return(RedirectToAction("Index", "Home"));
                }

                var authToken = _loginMananger.GetAuthToken(model.Username, model.Password);

                if (authToken == null)
                {
                    throw new Exception("Unknown user or password");
                }

                base.SetAuthCookie(authToken);

                return(RedirectToAction("Index", "Home"));
            }
            catch (Exception ex)
            {
                model.ErrorMessage = ex.Message;
                return(View(model));
            }
        }
Exemplo n.º 3
0
 public IHttpActionResult Token(TokenLoginModel model)
 {
     if (model == null)
     {
         return(BadRequest());
     }
     if (ModelState.IsValid)
     {
         if (model.Kind.Equals("client", StringComparison.OrdinalIgnoreCase))
         {
             return(CreateTokenForClient(model));
         }
         else if (model.Kind.Equals("account", StringComparison.OrdinalIgnoreCase))
         {
             return(CreateTokenForAccount(model));
         }
         else
         {
             return(BadRequest("Unknown token request kind"));
         }
     }
     else
     {
         return(BadRequest(ModelState));
     }
 }
Exemplo n.º 4
0
        public async Task <IActionResult> CreateToken([FromBody] TokenLoginModel login, bool includeRefreshToken)
        {
            var user = await _userManager.FindByNameAsync(login.Username);

            if (user == null || !await _userManager.CheckPasswordAsync(user, login.Password))
            {
                return(BadRequest(new { Error = "Invalid username or password" }));
            }

            var claims = await BuildClaims(user);

            var token = _tokenService.GenerateAccessToken(claims);

            if (includeRefreshToken)
            {
                var refreshToken = _tokenService.GenerateRefreshToken();
                user.RefreshTokenHash = _userManager.PasswordHasher.HashPassword(user, refreshToken);
                await _userManager.UpdateAsync(user);

                return(Ok(new { token = token, refreshToken = refreshToken }));
            }

            var userVm = new
            {
                user.Id,
                user.UserName,
                user.Email,
                user.FullName,
                user.PhoneNumber,
                user.UserAddresses
            };

            return(Ok(new { token = token, user = userVm }));
        }
        public async Task <IActionResult> GetAdminToken(TokenLoginModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }


            if (model.email == "*****@*****.**" && model.mobileNum == "+9999999")
            {
                var tokenDescriptor = new SecurityTokenDescriptor
                {
                    Subject = new ClaimsIdentity(new Claim[]
                    {
                        //new Claim("UserID",contactID.ToString()),
                        new Claim(ClaimTypes.Role, "Administrator")
                    }),
                    Expires            = DateTime.UtcNow.AddMinutes(10),
                    SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtSettings.JWT_Secret)), SecurityAlgorithms.HmacSha256Signature)
                };
                var tokenHandler  = new JwtSecurityTokenHandler();
                var securityToken = tokenHandler.CreateToken(tokenDescriptor);
                var token         = tokenHandler.WriteToken(securityToken);

                return(Ok(new { token }));
            }
            else
            {
                return(BadRequest(new { message = "The TokenLogin input is  false" }));
            }
        }
        public async Task <IActionResult> GetToken(TokenLoginModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            var contactID = 0;

            try
            {
                contactID = _context.Contact.FirstOrDefault(e => e.Email == model.email && e.MobileNum == model.mobileNum).ContactId;
                //if (contactID != 0)
                //{
                var tokenDescriptor = new SecurityTokenDescriptor
                {
                    Subject = new ClaimsIdentity(new Claim[]
                    {
                        new Claim("UserID", contactID.ToString()),
                    }),
                    Expires            = DateTime.UtcNow.AddMinutes(10),
                    SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtSettings.JWT_Secret)), SecurityAlgorithms.HmacSha256Signature)
                };
                var tokenHandler  = new JwtSecurityTokenHandler();
                var securityToken = tokenHandler.CreateToken(tokenDescriptor);
                var token         = tokenHandler.WriteToken(securityToken);

                return(Ok(new { token }));
            }
            catch (Exception e)
            {
                return(BadRequest("Your input parameters were false"));
            }
        }
Exemplo n.º 7
0
        private Client TryFetchUser(TokenLoginModel model)
        {
            Client user = null;

            if (model.Apikey != (default(Guid)) && user == null)
            {
                user = _data.Clients.FirstOrDefault(c => c.CurrentApiKey == model.Apikey);
            }
            return(user);
        }
Exemplo n.º 8
0
        private User TryFetchAccount(TokenLoginModel model)
        {
            User user = null;

            if (model.Apikey != (default(Guid)) && user == null)
            {
                user = _data.Users.FirstOrDefault(c => c.UserApiKey == model.Apikey);
            }
            return(user);
        }
Exemplo n.º 9
0
 public static void LogThisAccess(TokenLoginModel tokenLoginModel, bool isApproved, string access)
 {
     //TokenAccessLogs tokenAccessLogs = new TokenAccessLogs
     //{
     //    Access = access,
     //    AccessTrueFalse = isApproved,
     //    AccessRequest = tokenLoginModel.ToString()
     //};
     //TODO: Db ye logla
 }
Exemplo n.º 10
0
        public async Task <IActionResult> CreateToken([FromBody] TokenLoginModel login)
        {
            Dictionary <string, string> keyValuePairs = new Dictionary <string, string>();

            keyValuePairs.Add("ConsoleType", "0");

            var client      = _httpClientFactory.CreateClient("token_client");
            var tokenClient = new TokenClient(client, new TokenClientOptions
            {
                Address      = $"{CommonHelper.GetWebLocation()}connect/token",
                ClientId     = "client",
                ClientSecret = "secret",
                Parameters   = keyValuePairs,
            });
            var tokenResponse = await tokenClient.RequestPasswordTokenAsync(login.Username, login.Password,
                                                                            "api" + " " + IdentityServerConstants.StandardScopes.OfflineAccess);

            if (tokenResponse.IsError)
            {
                return(Error(500, tokenResponse.ErrorType.ToString(),
                             /*tokenResponse.Error + "," + tokenResponse.ErrorDescription*/ "用户未批准或用户名密码错误"));
            }

            var user = await _userService.GetUserByUsername(login.Username);



            if (login.IncludeRefreshToken)
            {
                return(Success(new
                {
                    token = tokenResponse.AccessToken,
                    refreshToken = tokenResponse.RefreshToken,
                    expiresIn = tokenResponse.ExpiresIn, // 秒
                    expiresAtUtc = DateTime.UtcNow.AddSeconds(tokenResponse.ExpiresIn),
                    IsAdmin = user.IsAdmin
                }));
            }

            return(Success(new
            {
                token = tokenResponse.AccessToken,
                expiresIn = tokenResponse.ExpiresIn, // 秒
                expiresAtUtc = DateTime.UtcNow.AddSeconds(tokenResponse.ExpiresIn),
                IsAdmin = user.IsAdmin
            }));
        }
Exemplo n.º 11
0
        public async Task <IActionResult> GetToken([FromBody] TokenLoginModel loginModel)
        {
            if (ModelState.IsValid)
            {
                var user = await _tokenRepository.CheckUserAndGetInfoAysnc(loginModel);

                if (user != null)
                {
                    string token = TokenHelper.GenerateToken(_configuration, user);
                    //TODO:Girişi logla. Db ye kaydedilebilir takibi kolay olacaktır.
                    //TokenHelper.LogThisAccess(loginModel,true, "Approved");
                    return(Ok(new { User = user.Username, Access = "Approved", Token = token }));
                }
                //TokenHelper.LogThisAccess(loginModel,false, "Not Approved");
                return(BadRequest(new { User = loginModel.Username, Access = "Not Approved" }));
            }
            return(Unauthorized());
        }
Exemplo n.º 12
0
        private IHttpActionResult CreateTokenForClient(TokenLoginModel model)
        {
            Client user = TryFetchUser(model);

            if (user == null)
            {
                return(this.ResponseMessage(new HttpResponseMessage(HttpStatusCode.Unauthorized)));
            }

            if (model.Apikey != default(Guid) && user.CurrentApiKey != model.Apikey)
            {
                return(BadRequest("Api Key Invalid"));
            }

            return(this.ResponseMessage(new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = GetClientTicket(user)
            }));
        }