public override Task ValidateIdentity(OAuthValidateIdentityContext context)
        {
            var ipToken   = context.Ticket.Properties.Dictionary["UserIp"];
            var ipRequest = context.Request.RemoteIpAddress;

            if (!ipToken.Equals(ipRequest))
            {
                context.Rejected();
                context.SetError("MENSAJE_ERROR_TOKEN_IP_INVALIDA");
                return(Task.FromResult <object>(null));
            }
            if (context.Request.Headers.ContainsKey("Authorization"))
            {
                var tokenRequest = context.Request.Headers["Authorization"].Replace("Bearer ", "").Trim();
                var strIdUsuario = context.Ticket.Properties.Dictionary["IdUsuario"];
                //var tokenTaskHelper = TokenTaskHelper.GetInstance();
                var tokenUsuario = TokenTaskHelper.GetToken(strIdUsuario);
                if (tokenUsuario == null || !tokenUsuario.Equals(tokenRequest))
                {
                    var login     = new LoginController();
                    var idUsuario = Int64.Parse(strIdUsuario);
                    var tokenAux  = login.GetTokenUsuario(idUsuario);
                    tokenUsuario = TokenTaskHelper.SetToken(strIdUsuario, tokenAux);
                }
                if (!tokenUsuario.Equals(tokenRequest))
                {
                    context.Rejected();
                    context.SetError("MENSAJE_ERROR_TOKEN_USUAIRO_INCONSISTENTE");
                    return(Task.FromResult <object>(null));
                }
            }


            return(base.ValidateIdentity(context));
        }
Exemplo n.º 2
0
        bool checkInjection(OAuthValidateIdentityContext context)
        {
            bool isInvalid = false;

            foreach (string key in HttpContext.Current.Request.QueryString)
            {
                if (CheckInput(HttpContext.Current.Request.QueryString[key], key, context))
                {
                    isInvalid = true;
                    break;
                }
            }
            foreach (string key in HttpContext.Current.Request.Form)
            {
                if (CheckInput(HttpContext.Current.Request.Form[key], key, context))
                {
                    isInvalid = true;
                    break;
                }
            }

            foreach (string key in HttpContext.Current.Request.Cookies)
            {
                if (CheckInput(HttpContext.Current.Request.Cookies[key].Value, key, context))
                {
                    isInvalid = true;
                    break;
                }
            }
            return(isInvalid);
        }
Exemplo n.º 3
0
        /// <summary>
        /// Handles processing OAuth bearer token.
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public virtual Task RequestToken(OAuthRequestTokenContext context)
        {
            var idContext = new OAuthValidateIdentityContext(context.OwinContext, null, null);

            this.ValidateIdentity(idContext);
            return(Task.FromResult <int>(0));
        }
Exemplo n.º 4
0
        private Task AddClaim(OAuthValidateIdentityContext context)
        {
            var userName = context.Ticket.Identity.Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier).Value;

            context.Ticket.Identity.AddClaim(new Claim(ClaimTypes.Name, userName));
            return(Task.CompletedTask);
        }
Exemplo n.º 5
0
    public override Task ValidateIdentity(OAuthValidateIdentityContext context)
    {
        var claims = context.Ticket.Identity.Claims;         //examine claims here

        base.ValidateIdentity(context);
        return(Task.FromResult <object>(null));
    }
        public override async Task ValidateIdentity(OAuthValidateIdentityContext context)
        {
            var result = base.ValidateIdentity(context);


            if (context.IsValidated)
            {
                var ticket = context.Ticket;
                if (ticket != null && ticket.Identity.IsAuthenticated && ticket.Properties.ExpiresUtc > DateTime.UtcNow)
                {
                    string name = ticket.Identity.Name;
                    if (!string.IsNullOrEmpty(name))
                    {
                        ApplicationUser u = await _repo.FindUserByUserName(name);

                        if (u == null)//TODO: put your server side condition here
                        {
                            context.SetError("User Not found!");
                        }
                        else if (u.IsSuspend.HasValue && u.IsSuspend.Value)
                        {
                            context.SetError("User Has Suspended!");
                        }
                    }
                }
            }



            //return result;
        }
        public Task ValidateIdentity(OAuthValidateIdentityContext context)
        {
            //為了回傳Task void, 隨便傳入一個值
            return(Task.FromResult(0));

            //.net framework 4.6才有
            //return Task.CompletedTask
        }
        /// <summary>
        /// Called each time a request identity has been validated by the middleware. By implementing this method the
        /// application may alter or reject the identity which has arrived with the request.
        /// </summary>
        /// <param name="context">Contains information about the login session as well as the user <see cref="T:System.Security.Claims.ClaimsIdentity" />.</param>
        /// <returns>
        /// A <see cref="T:System.Threading.Tasks.Task" /> representing the completed operation.
        /// </returns>
        public Task ValidateIdentity(OAuthValidateIdentityContext context)
        {
            if (_inner != null)
            {
                return(_inner.ValidateIdentity(context));
            }

            return(Task.FromResult(0));
        }
        private static Task OnValidateIdentity(OAuthValidateIdentityContext context)
        {
            var calimsIdentity = context.Ticket.Identity;

            //Add custom claim if needed
            calimsIdentity.AddClaim(new Claim("ClaimType", "ClaimValue"));

            return(Task.FromResult <int>(0));
        }
Exemplo n.º 10
0
            public override Task ValidateIdentity(OAuthValidateIdentityContext context)
            {
                var claims = context.Ticket.Identity.Claims;

                if (claims.Count() == 0 || claims.Any(claim => claim.Issuer != "Facebook" && claim.Issuer != "Twitter" && claim.Issuer != "LOCAL_AUTHORITY"))
                {
                    context.Rejected();
                }
                return(Task.FromResult <object>(null));
            }
Exemplo n.º 11
0
        // This validates the identity based on the issuer of the claim.
        // The issuer is set in the API endpoint that logs the user in
        public override Task ValidateIdentity(OAuthValidateIdentityContext context)
        {
            IEnumerable <Claim> claims = context.Ticket.Identity.Claims;

            if (null == claims || 0 == claims.Count() || claims.Any(claim => claim.Issuer.ToString() != "Facebook" && claim.Issuer.ToString() != "Google" && claim.Issuer.ToString() != "LOCAL_AUTHORITY"))
            {
                context.Rejected();
            }
            return(Task.FromResult <object>(null));
        }
Exemplo n.º 12
0
            /// <summary>
            /// Handles validating the identity produced from an OAuth bearer token.
            /// </summary>
            /// <param name="context">The identity context.</param>
            /// <returns>The task for asynchronous operations.</returns>
            public override Task ValidateIdentity(OAuthValidateIdentityContext context)
            {
                // Get Claims to find out if user actually is permitted to actual api
                // Then you can add an attribute over the api method to define what role
                // the user needs to that funtionality
                var claims = context.Ticket.Identity.Claims;


                return(base.ValidateIdentity(context));
            }
        // This validates the identity based on the issuer of the claim.
        // The issuer is set in the API endpoint that logs the user in
        public override Task ValidateIdentity(OAuthValidateIdentityContext context)
        {
            IEnumerable <Claim> claims = context.Ticket.Identity.Claims;

            if (!claims.Any() || claims.Any(claim => claim.Type != "GoogleAccessToken")) // modify claim name
            {
                context.Rejected();
            }
            return(Task.FromResult <object>(null));
        }
Exemplo n.º 14
0
        // This validates the identity based on the issuer of the claim.
        // The issuer is set in the API endpoint that logs the user in
        public override Task ValidateIdentity(OAuthValidateIdentityContext context)
        {
            var claims     = context.Ticket.Identity.Claims;
            var enumerable = claims as Claim[] ?? claims.ToArray();

            if (!enumerable.Any() || enumerable.Any(claim => claim.Issuer != "Facebook" && claim.Issuer != "LOCAL_AUTHORITY"))
            {
                context.Rejected();
            }
            return(Task.FromResult <object>(null));
        }
 public override Task ValidateIdentity(OAuthValidateIdentityContext context)
 {
     base.OnValidateIdentity(context);
     _oidcNotificationHandlerService.OnAuthenticationSuccess(
         new AuthenticationSuccessMessage()
     {
         Identity = context.Ticket.Identity
     }
         );
     return(Task.FromResult(0));
 }
 public override Task ValidateIdentity(OAuthValidateIdentityContext context)
 {
     if (context == null)
     {
         throw new ArgumentNullException("context");
     }
     if (context.Ticket.Identity.Claims.Any(c => c.Issuer != ClaimsIdentity.DefaultIssuer))
     {
         context.Rejected();
     }
     return(Task.FromResult <object>(null));
 }
Exemplo n.º 17
0
        public override Task ValidateIdentity(OAuthValidateIdentityContext context)
        {
            var identity    = context.Ticket?.Identity;
            var userIdClaim = identity?.Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier);

            if (userIdClaim == null)
            {
                context.Rejected();
            }

            return(base.ValidateIdentity(context));
        }
Exemplo n.º 18
0
        public override Task ValidateIdentity(OAuthValidateIdentityContext context)
        {
            var claims     = context.Ticket.Identity.Claims;
            var enumerable = claims as IList <Claim> ?? claims.ToList();

            if (!enumerable.Any() || enumerable.Any(claim => claim.Issuer != ClaimsIdentity.DefaultIssuer))
            {
                context.Rejected();
            }

            return(Task.FromResult <object>(null));
        }
Exemplo n.º 19
0
        /// <summary>
        /// Handles validating the identity produced from an OAuth bearer token.
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public virtual Task ValidateIdentity(OAuthValidateIdentityContext context)
        {
            try
            {
                if (!context.Request.Headers.ContainsKey("Authorization"))
                {
                    return(Task.FromResult <object>(null));
                }

                // Retrieve the JWT token in Authorization Header
                var jwt = context.Request.Headers["Authorization"].Replace("Bearer ", string.Empty);

                var handler = new JwtSecurityTokenHandler();

                var token = new JwtSecurityToken(jwt);

                var claimIdentity = new ClaimsIdentity(token.Claims, DefaultAuthenticationTypes.ExternalBearer);

                var param = new TokenValidationParameters
                {
                    ValidateAudience = true,                               // Make this false if token was generated without clientId
                    ValidAudience    = "8ebd73587a354f948ec-93260410010c", //Replace with Client Id Registered on CRM. Token should have been fetched with the same clientId.
                    ValidateIssuer   = true,
                    IssuerSigningKey = _signingKey,
                    IssuerValidator  = (issuer, securityToken, parameters) =>
                    {
                        var allowed = GetAllowedPortal().Trim().ToLowerInvariant();

                        if (issuer.ToLowerInvariant().Equals(allowed))
                        {
                            return(issuer);
                        }

                        throw new Exception("Token Issuer is not a known Portal");
                    }
                };

                SecurityToken validatedToken = null;

                handler.ValidateToken(token.RawData, param, out validatedToken);

                var claimPrincipal = new ClaimsPrincipal(claimIdentity);
                context.Response.Context.Authentication.User = claimPrincipal;
                context.Validated(claimIdentity);
            }
            catch (Exception exception)
            {
                System.Diagnostics.Debug.WriteLine(exception);
                return(null);
            }
            return(Task.FromResult <object>(null));
        }
        public override Task ValidateIdentity(OAuthValidateIdentityContext context)
        {
            var wispContext = context.GetWispContext();

            wispContext.SetIdentity(context);
            if (wispContext.CurrentUser == null || !wispContext.CurrentUser.Active)
            {
                throw new WispHttpException(System.Net.HttpStatusCode.Unauthorized);
            }

            context.Validated();
            return(Task.FromResult(0));
        }
Exemplo n.º 21
0
        private bool CheckInput(string parameter, string KEY, OAuthValidateIdentityContext context)
        {
            bool isInvalid = false;

            for (int i = 0; i < blackList.Length; i++)
            {
                if ((parameter.IndexOf(blackList[i], StringComparison.OrdinalIgnoreCase) >= 0))
                {
                    isInvalid = true;
                    break;
                }
            }
            return(isInvalid);
        }
        public Task ValidateIdentity(OAuthValidateIdentityContext context)
        {
            // if token valid

            var userGuid = context.Ticket.Identity.Claims.Where(c => c.Type == "UserGuid").First().Value;

            if (!memCache.Contains(userGuid, null))
            {
                context.Rejected(); // if i want to reject the token
                return(null);
            }

            return(Task.FromResult <object>(null));
        }
        public override System.Threading.Tasks.Task ValidateIdentity(OAuthValidateIdentityContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            if (context.Ticket.Identity.Claims.Any(c => c.Issuer != "LOCAL AUTHORITY"))
            {
                context.Rejected();
            }

            return(Task.FromResult <object>((object)null));
        }
        // This validates the identity based on the issuer of the claim.
        // The issuer is set in the API endpoint that logs the user in
        public override Task ValidateIdentity(OAuthValidateIdentityContext context)
        {
            UserManager <ApplicationUser> userManager = context.OwinContext.GetUserManager <ApplicationUserManager>();
            var user = userManager.FindById(context.Ticket.Identity.GetUserId());

            var claims = context.Ticket.Identity.Claims;

            if (user == null || (claims.FirstOrDefault(claim => claim.Type == "AspNet.Identity.SecurityStamp") == null || claims.Any(claim => claim.Type == "AspNet.Identity.SecurityStamp" && !claim.Value.Equals(user.SecurityStamp))))
            {
                // Client could not be validated.
                context.SetError("invalid_token", "Client token is invalid.");
                context.Rejected();
            }

            return(Task.FromResult <object>(null));
            //return Simple.FromResult(0);
        }
Exemplo n.º 25
0
 public Task ValidateIdentity(OAuthValidateIdentityContext context)
 {
     System.Security.Claims.Claim claim = context.Ticket.Identity.Claims.Where(x => x.Type == "userGetwayIP" && x.Value.ToString() == HttpContext.Current.Request.UserHostAddress.ToString()).FirstOrDefault();
     if (claim == null)
     {
         context.SetError("Inform that you are a good boy :) don't try this step again");
         context.Rejected();
         context.Response.StatusCode = 400;
     }
     else if (checkInjection(context))
     {
         context.SetError("Not acceptable input");
         context.Rejected();
         context.Response.StatusCode = 406;
     }
     return(Task.FromResult <object>(null));
 }
        public async Task ValidateIdentity(OAuthValidateIdentityContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            if (context.Ticket.Identity.Claims.Count() == 0)
            {
                context.Rejected();
            }
            else if (context.Ticket.Identity.Claims.All(c => c.Issuer == ClaimsIdentity.DefaultIssuer))
            {
                context.Rejected();
            }
            else
            {
                var accessToken = context.Ticket.Identity.FindFirst(Security.ClaimTypes.AccessToken);
                if (accessToken != null && !string.IsNullOrEmpty(accessToken.Value))
                {
                    try
                    {
                        var response = await "https://www.googleapis.com/oauth2/v3/tokeninfo"
                                       .SetQueryParam("access_token", accessToken.Value)
                                       .GetAsync();

                        if (!response.IsSuccessStatusCode)
                        {
                            context.Rejected();
                        }
                        else
                        {
                            context.Validated();
                        }
                    }
                    catch (FlurlHttpException ex)
                    {
                        context.Rejected();
                    }
                }
                else
                {
                    context.Rejected();
                }
            }
        }
        public Task ValidateIdentity(OAuthValidateIdentityContext context)
        {
            if (!string.IsNullOrEmpty(token))
            {
                var tokenHandler         = new JwtSecurityTokenHandler();
                var validationParameters = new TokenValidationParameters()
                {
                    ValidAudience      = "all",
                    IssuerSigningToken = new BinarySecretSecurityToken(Convert.FromBase64String("KJiuweUH2234KJBJbkjk234234fgdfc56566")),
                    ValidIssuer        = "http://vcdbpoc-staging.azurewebsites.net"
                };
                try
                {
                    SecurityToken securityToken;
                    var           claimsPrinciple = tokenHandler.ValidateToken(token, validationParameters, out securityToken);

                    context.Validated(new ClaimsIdentity(claimsPrinciple.Claims, OAuthDefaults.AuthenticationType));
                    return(Task.FromResult(0));
                }
                catch (Exception ex)
                {
                    context.Rejected();
                    return(Task.FromResult(0));
                }

                //var notPadded = token.Split('.')[1];
                //var padded = notPadded.PadRight(notPadded.Length + (4 - notPadded.Length % 4) % 4, '=');
                //var urlUnescaped = padded.Replace('-', '+').Replace('_', '/');
                //var claimsPart = Convert.FromBase64String(urlUnescaped);

                //var obj = JObject.Parse(Encoding.UTF8.GetString(claimsPart, 0, claimsPart.Length));

                //// simple, not handling specific types, arrays, etc.
                //foreach (var prop in obj.Properties().AsJEnumerable())
                //{
                //    if (!context.Ticket.Identity.HasClaim(prop.Name, prop.Value.Value<string>()))
                //    {
                //        context.Ticket.Identity.AddClaim(new Claim(prop.Name, prop.Value.Value<string>()));
                //    }
                //}
            }

            context.Rejected();
            return(Task.FromResult(0));
        }
Exemplo n.º 28
0
        public override Task ValidateIdentity(OAuthValidateIdentityContext context)
        {
            var identity      = context.Ticket?.Identity;
            var masterIdClaim = identity?.Claims.FirstOrDefault(x => x.Type == "masterId");

            if (masterIdClaim == null)
            {
                context.Rejected();
            }
            else
            {
                var storedIdentity = this.principalStorage[masterIdClaim.Value];
                if (storedIdentity == null)
                {
                    context.Rejected();
                }
            }
            return(base.ValidateIdentity(context));
        }
Exemplo n.º 29
0
        private Task OnValidateIdentityHandle(OAuthValidateIdentityContext context)
        {
            var Db = new WIKIDbContext();

            var             cache  = MemoryCache.Default;
            CacheItemPolicy policy = new CacheItemPolicy();

            policy.AbsoluteExpiration = DateTimeOffset.FromUnixTimeSeconds(60 * 30);

            var userId = Guid.Parse(context.Ticket.Identity.FindFirst("sub").Value);

            var obj = cache.Get(userId.ToString());

            if (obj == null)
            {
                var entity = Db.Account.Where(m => m.WUCC_UserId == userId).FirstOrDefault();
                if (entity == null)
                {
                    entity = new Account
                    {
                        WUCC_UserId = userId,
                        Department  = context.Ticket.Identity.Claims.FirstOrDefault(m => m.Type == "SalesDepartment").Value,
                        UserName    = context.Ticket.Identity.Name,
                        FullName    = context.Ticket.Identity.Claims.FirstOrDefault(m => m.Type == "FullName").Value,
                    };
                    Db.Account.Add(entity);
                }
                else
                {
                    entity.Department = context.Ticket.Identity.Claims.FirstOrDefault(m => m.Type == "SalesDepartment").Value;
                    entity.UserName   = context.Ticket.Identity.Name;
                    entity.FullName   = context.Ticket.Identity.Claims.FirstOrDefault(m => m.Type == "FullName").Value;
                }

                Db.SaveChanges();

                cache.Add(userId.ToString(), entity, policy);
            }



            return(Task.FromResult(0));
        }
Exemplo n.º 30
0
    public override Task ValidateIdentity(OAuthValidateIdentityContext context)
    {
        var result = base.ValidateIdentity(context);

        if (context.IsValidated)
        {
            var ticket = context.Ticket;

            if (ticket != null && ticket.Identity.IsAuthenticated && ticket.Properties.ExpiresUtc > DateTime.UtcNow)
            {
                if (1 == 2)  //TODO: put your server side condition here
                {
                    context.SetError("HaHa!");
                }
            }
        }

        return(result);
    }