Beispiel #1
0
        public ValidateResponse Validate(ValidateToken validateToken)
        {
            var validationParameters = new TokenValidationParameters
            {
                IssuerSigningKey = _options.SigningCredentials.Key,
                ValidateAudience = false,
                ValidateIssuer   = true,
                ValidIssuer      = validateToken.Issuer
            };

            try
            {
                new JwtSecurityTokenHandler().ValidateToken(validateToken.AccessToken, validationParameters, out var securityToken);
                var jwt = (JwtSecurityToken)securityToken;

                return(new ValidateResponse
                {
                    Claims = jwt.Claims
                             .Where(x => x.Type != "scope")
                             .ToDictionary(x => x.Type, x => x.Value),
                    AllowedScopes = jwt.Claims
                                    .Where(x => x.Type == "scope")
                                    .Select(x => x.Value)
                                    .ToList()
                });
            }
            catch
            {
                return(null);
            }
        }
 public AuthController()
 {
     _context        = new ApplicationDbContext();
     validator       = new ValidateToken();
     validateauth    = new ValidateAuth();
     activeDirectory = new ADClass();
 }
Beispiel #3
0
        public Task <ValidateToken> ValidateServiceToken(HttpContext httpContext)
        {
            ValidateToken requestToken = new ValidateToken();

            requestToken.ClientScope = new List <string>();

            try
            {
                var identity = httpContext.User.Identity as ClaimsIdentity;

                foreach (var claim in identity.Claims)
                {
                    if (claim.Type.Contains("role"))
                    {
                        requestToken.ClientScope.Add(claim.Value);
                    }

                    if (claim.Type.Contains("serialnumber"))
                    {
                        requestToken.Secret = claim.Value;
                    }

                    if (claim.Type.Contains("nameidentifier"))
                    {
                        requestToken.ClientId = Guid.Parse(claim.Value);
                    }

                    if (claim.Type.Contains("givenname"))
                    {
                        requestToken.ClientGrantType = claim.Value;
                    }
                }

                if (_configuration.GetClientID(requestToken.ClientId))
                {
                    var model = _applicationRepository.ClientVerify(requestToken.ClientId.ToString(), requestToken.Secret, requestToken.ClientScope, requestToken.ClientGrantType);

                    if (!model.Success)
                    {
                        throw new Exception($"Cliente não encontrado. Erro: {model.ResultMessage}");
                    }
                }
                else
                {
                    throw new Exception($"ClientID {requestToken.ClientId} incorreto");
                }

                requestToken.Success       = true;
                requestToken.ResultMessage = "Token validado com sucesso.";
            }
            catch (Exception ex)
            {
                requestToken.Success       = false;
                requestToken.ResultMessage = ex.Message;
            }

            return(Task.FromResult(requestToken));
        }
Beispiel #4
0
        public async Task <ActionResult <UserTokenDto> > ValidateJwtToken([FromBody] ValidateToken token)
        {
            if (token.Token != null)
            {
                var vailidation = await _authRepository.ValidateJwtToken(token);

                return(vailidation);
            }
            return(new UserTokenDto());
        }
Beispiel #5
0
        public async Task <IActionResult> ValidateToken([FromBody] ValidateToken validateToken)
        {
            if (validateToken.Cvv.ToString().Length > 5)
            {
                return(BadRequest("Cvv lenght error"));
            }

            var result = await tokenService.ValidateToken(validateToken);

            return(Ok(result));
        }
Beispiel #6
0
        public async Task <bool> ValidateToken(ValidateToken validateToken)
        {
            var customer = await customerRepository.GetCustomerByRegistrationDate(validateToken.RegistrationDate);

            TimeSpan ts = DateTime.UtcNow - customer.RegistrationDateTimeInUtc;

            if (ts.TotalMinutes > 15)
            {
                return(false);
            }

            return(true);
        }
Beispiel #7
0
 private void CreateTokenValidatorObject()
 {
     try
     {
         if (!string.IsNullOrEmpty(_kafkaConfig.TokenServerUri))
         {
             _validateToken = new ValidateToken(_kafkaConfig.TokenServerUri);
         }
     }
     catch (Exception ex)
     {
         _logger.LogError(ex, $"failed to Create Object of TokenValidator  message: {ex.Message}");
     }
 }
Beispiel #8
0
        public void If_no_token_error_no_response_is_set_and_token_data_is_set()
        {
            // 1. Arrange
            var attr    = new ValidateTokenDataAttribute();
            var context = new HttpActionContext
            {
                ActionDescriptor = new ReflectedHttpActionDescriptor()
            };
            const string tokenString = "token";
            var          request     = new ValidateToken
            {
                AuthToken = tokenString
            };

            context.ActionArguments.Add("request", request);

            var playerId = Guid.NewGuid();
            var token    = playerId.ToString();
            var mtp      = new Mock <ITokenProvider>(MockBehavior.Strict);

            mtp
            .Setup(tp => tp.Decrypt(tokenString))
            .Returns(playerId);
            attr.TokenProvider = mtp.Object;

            var mtvp = new Mock <ITokenValidationProvider>(MockBehavior.Strict);

            mtvp
            .Setup(tvp => tvp.ValidateToken(token));     // no error
            attr.TokenValidation = mtvp.Object;

            var mJson = new Mock <IJsonSerializationProvider>(MockBehavior.Strict);

            mJson
            .Setup(j => j.SerializeToString(It.IsAny <GameApiResponseBase>()))
            .Returns <GameApiResponseBase>(o => o.ErrorDescription);
            attr.Json = mJson.Object;

            // 2. Act
            attr.OnActionExecuting(context);

            // 3. Assert
            Assert.That(context.Response, Is.Null);
//            Assert.That(request.TokenData, Is.EqualTo(token));
            mtp.Verify(tp => tp.Decrypt(tokenString), Times.Once());
            mtvp.Verify(tvp => tvp.ValidateToken(token), Times.Once());
        }
        public async Task <ValidatedUser> ValidateUserToken(string token)
        {
            ValidatedUser validatedUser = null;
            ValidateToken validateToken = new ValidateToken
            {
                Token = token
            };

            var jsonSerializedToken = JsonConvert.SerializeObject(validateToken);
            var request             = new HttpRequestMessage
            {
                Method     = HttpMethod.Post,
                RequestUri = new Uri($"http://{this._httpContextAccessor.HttpContext.Request.Headers[HEADER_VTEX_ACCOUNT]}.vtexcommercestable.com.br/api/vtexid/credential/validate"),
                Content    = new StringContent(jsonSerializedToken, Encoding.UTF8, APPLICATION_JSON)
            };

            string authToken = this._httpContextAccessor.HttpContext.Request.Headers[HEADER_VTEX_CREDENTIAL];

            if (authToken != null)
            {
                request.Headers.Add(AUTHORIZATION_HEADER_NAME, authToken);
            }

            var client = _clientFactory.CreateClient();

            try
            {
                var response = await client.SendAsync(request);

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

                //_context.Vtex.Logger.Info("ValidateUserToken", null, $"[{response.StatusCode}] {responseContent}");
                if (response.IsSuccessStatusCode)
                {
                    validatedUser = JsonConvert.DeserializeObject <ValidatedUser>(responseContent);
                }
            }
            catch (Exception ex)
            {
                _context.Vtex.Logger.Error("ValidateUserToken", null, $"Error validating user token", ex);
            }

            return(validatedUser);
        }
        public async Task <UserTokenDto> ValidateJwtToken(ValidateToken token)
        {
            var model        = new LoginDto();
            var tokenHandler = new JwtSecurityTokenHandler();
            var key          = Encoding.ASCII.GetBytes(_configuration["JWT:key"]);

            try
            {
                tokenHandler.ValidateToken(token.Token, new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(key),
                    ValidateIssuer           = false,
                    ValidateAudience         = false,
                    // set clockskew to zero so tokens expire exactly at token expiration time (instead of 5 minutes later)
                    ClockSkew = TimeSpan.Zero
                }, out SecurityToken validatedToken);

                var jwtToken = (JwtSecurityToken)validatedToken;
                var claims   = "";

                foreach (var item in jwtToken.Claims)
                {
                    if (item.Type == "unique_name")
                    {
                        claims = item.Value;
                    }
                }

                model.Email    = claims;
                model.Password = "";
                var result = await BuildToken(model, new List <string>());

                return(result);
            }
            catch
            {
                return(new UserTokenDto());
            }
        }
Beispiel #11
0
        public ActionResult GetList(ScreenResultModel screen)
        {
            UserForTemplet user = new ValidateToken().CheckUser(screen.TokenValue);

            if (user.StateCode != StateCode.normal)
            {
                return(Json(new List <TempletForJson>()
                {
                    new TempletForJson()
                    {
                        StateCode = user.StateCode, StateDescription = user.StateDescription
                    }
                }));
            }
            IQueryable <BaseTemplet> templets = util.GetScreenResult(user, screen, int.MaxValue, out int totalcount); //根据筛选条件查询结果
            List <BaseTemplet>       temp     = templets.ToList();                                                    //由于直接使用IQueryable赋值会抛出DataReader未释放的异常,故先转换为List。推测是IQueryable的数据库访问是用时查询,缺少异步封装导致的(就是懒得写异步了)
            List <TempletForJson>    result   = new List <TempletForJson>();                                          //由于外键链接,直接使用Json实例化查询结果会导致重复引用,所以这里建立新模型以方便Json传输

            foreach (BaseTemplet templet in temp)
            {
                result.Add(new TempletForJson()
                {
                    ID                  = templet.ID,
                    UserID              = templet.User.ID,
                    Organization        = templet.Organization == null ? new Guid() : templet.Organization.ID,
                    Accessibility       = templet.Accessibility,
                    TempletName         = templet.TempletName,
                    TempletIntroduction = templet.TempletIntroduction,
                    ImagePath           = templet.ImagePath,
                    FilePath            = templet.FilePath,
                    ModTime             = templet.ModTime,
                    StateCode           = StateCode.normal,
                    StateDescription    = "获取成功"
                });
            }

            return(Json(result));
        }
Beispiel #12
0
        public IActionResult Validate([FromBody] ValidateToken validateToken)
        {
            var result = _tokenRepository.Validate(validateToken);

            return(Ok(result));
        }
 public async Task <ValidateTokenResponse> Post(ValidateToken request)
 {
     return(await GameActions.ValidateTokenAsync(request));
 }
Beispiel #14
0
 internal static bool IsTokenValid(string token)
 {
     return(ValidateToken.Validate(Configuration, token));
 }
        async Task <ValidateTokenResponse> ICommonGameActionsProvider.ValidateTokenAsync(ValidateToken request)
        {
            var playerId   = GetPlayerIdFromToken(request);
            var playerData = await _gameQueries.GetPlayerDataAsync(playerId); // Get player

            if (playerData == null)
            {
                throw new PlayerNotFoundException("Cannot find player with id=" + playerId);
            }

            var balance = await _gameQueries.GetPlayableBalanceAsync(playerId);       // Get balance

            var brandCode = await _gameQueries.GetBrandCodeAsync(playerData.BrandId); // Get brand code

            var playerBetLimitCode = await _gameQueries.GetPlayerBetLimitCodeOrNullAsync(playerData.VipLevelId, Context.GameProviderId, playerData.CurrencyCode);

            var balanceCurrencyCode =
                await
                _gameQueries.GetMappedGameProviderCurrencyCodeAsync(Context.GameProviderId,
                                                                    balance.CurrencyCode);

            return(new ValidateTokenResponse
            {
                Balance = balance.Balance,
                PlayerId = playerData.Id,
                PlayerDisplayName = playerData.DisplayName,
                BrandCode = brandCode ?? string.Empty,
                Language = playerData.CultureCode ?? string.Empty,
                CurrencyCode = balanceCurrencyCode,
                BetLimitCode = playerBetLimitCode ?? ""
            });
        }
Beispiel #16
0
 public ActionResult <IEnumerable <string> > Get()
 {
     return(new string[] { ValidateToken.ValidateTokenServer(GenerateToken.GenerateJwtToken("10")) });
 }
Beispiel #17
0
 public CustomUserController()
 {
     _context        = new ApplicationDbContext();
     validator       = new ValidateToken();
     activeDirectory = new ADClass();
 }
Beispiel #18
0
 protected internal virtual void OnValidateToken(ParsingContext context)
 {
     ValidateToken?.Invoke(this, context.SharedValidateTokenEventArgs);
 }