Example #1
0
        public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            string clientId     = string.Empty;
            string clientSecret = string.Empty;
            Client client       = null;

            if (!context.TryGetBasicCredentials(out clientId, out clientSecret))
            {
                context.TryGetFormCredentials(out clientId, out clientSecret);
            }

            if (context.ClientId == null)
            {
                //Remove the comments from the below line context.SetError, and invalidate context
                //if you want to force sending clientId/secrects once obtain access tokens.
                context.Validated();
                //context.SetError("invalid_clientId", "ClientId should be sent.");
                return(Task.FromResult <object>(null));
            }

            using (AuthRepository _repo = new AuthRepository())
            {
                client = _repo.FindClient(context.ClientId);
            }

            if (client == null)
            {
                context.SetError("invalid_clientId", string.Format("Client '{0}' is not registered in the system.", context.ClientId));
                return(Task.FromResult <object>(null));
            }

            if (client.ApplicationType == ApplicationType.NativeConfidential)
            {
                if (string.IsNullOrWhiteSpace(clientSecret))
                {
                    context.SetError("invalid_clientId", "Client secret should be sent.");
                    return(Task.FromResult <object>(null));
                }
                else
                {
                    if (client.Secret != HashHelper.GetSHA256(clientSecret))
                    {
                        context.SetError("invalid_clientId", "Client secret is invalid.");
                        return(Task.FromResult <object>(null));
                    }
                }
            }

            if (!client.Active)
            {
                context.SetError("invalid_clientId", "Client is inactive.");
                return(Task.FromResult <object>(null));
            }

            context.OwinContext.Set <string>("as:clientAllowedOrigin", client.AllowedOrigin);
            context.OwinContext.Set <string>("as:clientRefreshTokenLifeTime", client.RefreshTokenLifeTime.ToString());

            context.Validated();
            return(Task.FromResult <object>(null));
        }
Example #2
0
        public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            string clientId     = string.Empty;
            string clientSecret = string.Empty;

            // The TryGetBasicCredentials method checks the Authorization header and
            // Return the ClientId and clientSecret
            if (!context.TryGetBasicCredentials(out clientId, out clientSecret))
            {
                context.SetError("invalid_client", "Client credentials could not be retrieved through the Authorization header.");
                context.Rejected();
                return;
            }
            //Check the existence of by calling the ValidateClient method
            ClientMaster client = (new ClientMasterRepository()).ValidateClient(clientId, clientSecret);

            if (client != null)
            {
                // Client has been verified.
                context.OwinContext.Set <ClientMaster>("oauth:client", client);
                context.Validated(clientId);
            }
            else
            {
                // Client could not be validated.
                context.SetError("invalid_client", "Client credentials are invalid.");
                context.Rejected();
            }
            context.Validated();
        }
        public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            try
            {
                var username = context.Parameters["username"];
                var password = context.Parameters["password"];

                if (username == password)
                {
                    context.OwinContext.Set(DLearnConstants.DefaultClaimName + DLearnConstants.ClaimsUsername, username);
                    context.Validated();
                }
                else
                {
                    context.SetError("Invalid credentials");
                    context.Rejected();
                }
            }
            catch
            {
                context.SetError("Server error");
                context.Rejected();
            }
            return(Task.FromResult(0));
        }
Example #4
0
        public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            string clientId             = string.Empty;
            string clientSecret         = string.Empty;
            string symmetricKeyAsBase64 = string.Empty;

            if (!context.TryGetBasicCredentials(out clientId, out clientSecret))
            {
                context.TryGetFormCredentials(out clientId, out clientSecret);
            }

            if (context.ClientId == null)
            {
                context.SetError("ClientId inválido", "ClientId não informado");
                return(Task.FromResult <object>(null));
            }

            var audience = AudiencesStore.FindAudience(context.ClientId);

            if (audience == null)
            {
                context.SetError("ClientId inválido", string.Format("ClientId inválido '{0}'", context.ClientId));
                return(Task.FromResult <object>(null));
            }

            context.Validated();

            return(Task.FromResult <object>(null));
        }
Example #5
0
        public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            try
            {
                var username = context.Parameters["username"];
                var password = context.Parameters["password"];

                if (_identityService.AuthenticateUser(username, password))
                {
                    context.OwinContext.Set($"{_authConfiguration.AuthType}:username", username);
                    context.Validated();
                }
                else
                {
                    context.SetError("Invalid credentials");
                    context.Rejected();
                }
            }
            catch (Exception exception)
            {
                context.SetError(exception.Message);
                context.Rejected();
            }
            return(Task.FromResult(0));
        }
Example #6
0
        private System.Threading.Tasks.Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            string clientId;
            string clientSecret;

            if (context.TryGetBasicCredentials(out clientId, out clientSecret) ||
                context.TryGetFormCredentials(out clientId, out clientSecret))
            {
                try
                {
                    ClientService clientService = new ClientService(new OAuthContext());
                    Client        client        = clientService.Queryable().Where(c => c.ApiKey.ToString() == clientId && c.ApiSecret.ToString() == clientSecret).FirstOrDefault();

                    if (client != null && client.Active)
                    {
                        context.Validated();
                    }
                    else
                    {
                        context.Rejected();
                        context.SetError("Authentication Error", "Client is not active.");
                    }
                }
                catch (System.Security.Authentication.AuthenticationException authEx)
                {
                    context.Rejected();
                    context.SetError("Authentication Error", authEx.Message);
                }
            }
            return(System.Threading.Tasks.Task.FromResult(0));
        }
Example #7
0
        public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            string clientId;
            string clientSecret;

            if (!context.TryGetBasicCredentials(out clientId, out clientSecret))
            {
                context.TryGetFormCredentials(out clientId, out clientSecret);
            }

            if (context.ClientId == null)
            {
                context.SetError("invalid_audienceId", "audience_Id is not set");
                return(Task.FromResult <object>(null));
            }

            var audience = AudienceStore.FindAudience(context.ClientId);

            if (audience == null)
            {
                context.SetError("audience_clientId", $"Invalid audience_id '{context.ClientId}'");
                return(Task.FromResult <object>(null));
            }

            context.Validated();
            return(Task.FromResult <object>(null));
        }
Example #8
0
        public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            string clientId     = string.Empty;
            string clientSecret = string.Empty;

            if (!context.TryGetBasicCredentials(out clientId, out clientSecret))
            {
                context.TryGetFormCredentials(out clientId, out clientSecret);
            }

            if (context.ClientId == null)
            {
                context.SetError(Constants.Constants.InvalidClientId, Constants.Constants.ClientIdIsNotSet);
            }

            var audience = AudiencesStore.FindAudience(context.ClientId);

            if (audience == null)
            {
                context.SetError(Constants.Constants.InvalidClientId, $"{Constants.Constants.InvalidClientId} '{context.ClientId}'");
                return(Task.FromResult <object>(null));
            }
            context.Validated();
            return(Task.FromResult <object>(null));
        }
        /// <summary>
        /// 验证 client 信息
        /// </summary>
        public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            //验证 client 信息
            string clientId;
            string clientSecret;

            if (!context.TryGetBasicCredentials(out clientId, out clientSecret))
            {
                context.TryGetFormCredentials(out clientId, out clientSecret);
            }

            string grant_type = context.Parameters.Get(Constants.Parameters.GrantType);

            if (grant_type == Constants.GrantTypes.ClientCredentials)
            {
                if (string.IsNullOrEmpty(clientId))
                {
                    context.SetError("invalid_client", "client is not valid");
                    return;
                }
                if (string.IsNullOrEmpty(clientSecret))
                {
                    context.SetError("invalid_client", "clientSecret is not valid");
                    return;
                }
                if (clientId != "jmai" || clientSecret != "9ICvhE0Yr3T3gg3trm4zWo8XLvakcCu4i9R2l1m_3xh")
                {
                    context.SetError("invalid_client", "client or clientSecret is not valid");
                    return;
                }
            }
            context.Validated();
        }
Example #10
0
        /// <summary>
        /// Validates a client thats tries to access the server.
        /// Exepts all clients, the api is the onlyclient available and do not allow adding additional clients
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            string clientId;
            string clientSecret;
            Client client = null;

            if (!context.TryGetBasicCredentials(out clientId, out clientSecret))
            {
                context.TryGetFormCredentials(out clientId, out clientSecret);
            }

            if (context.ClientId == null || context.ClientId == CustomRefreshTokenProvider.DUMMY_CLIENT)
            {
                //Remove the comments from the below line context.SetError, and invalidate context
                //if you want to force sending clientId/secrects once obtain access tokens.
                context.Validated();
                //context.SetError("invalid_clientId", "ClientId should be sent.");
                return;
            }

            using (IRepository repo = new ApplicationRepository())
            {
                client = await repo.Clients.FindAsync(context.ClientId);
            }

            if (client == null)
            {
                context.SetError("invalid_clientId", string.Format("Client '{0}' is not registered in the system.", context.ClientId));
                return;
            }

            if (client.ApplicationType == ApplicationTypes.NativeConfidential)
            {
                if (string.IsNullOrWhiteSpace(clientSecret))
                {
                    context.SetError("invalid_clientId", "Client secret should be sent.");
                    return;
                }
                else
                {
                    if (client.Secret != Helper.GetHash(clientSecret))
                    {
                        context.SetError("invalid_clientId", "Client secret is invalid.");
                        return;
                    }
                }
            }

            if (!client.Active)
            {
                context.SetError("invalid_clientId", "Client is inactive.");
                return;
            }

            context.OwinContext.Set("as:clientAllowedOrigin", client.AllowedOrigin);
            context.OwinContext.Set("as:clientRefreshTokenLifeTime", client.RefreshTokenLifeTime.ToString());

            context.Validated();
        }
Example #11
0
        public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            _iAuthorizationBus = (IAuthorizationBus)GlobalConfiguration.Configuration.DependencyResolver.GetService(typeof(IAuthorizationBus));

            string    clientId     = string.Empty;
            string    clientSecret = string.Empty;
            ClientDTO client       = null;

            if (!context.TryGetBasicCredentials(out clientId, out clientSecret))
            {
                context.TryGetFormCredentials(out clientId, out clientSecret);
            }

            if (context.ClientId == null)
            {
                context.Validated();
                return(Task.FromResult <object>(null));
            }

            client = _iAuthorizationBus.FindClient(context.ClientId);


            if (client == null)
            {
                context.SetError("invalid_clientId");
                return(Task.FromResult <object>(null));
            }

            if (client.ApplicationType == ApplicationTypes.Client_NativeConfidentialApplication)
            {
                if (string.IsNullOrWhiteSpace(clientSecret))
                {
                    context.SetError("invalid_clientId", Resources.ClientSecretShouldBeSent);
                    return(Task.FromResult <object>(null));
                }
                else
                {
                    if (client.Secret != Helper.GetHash(clientSecret))
                    {
                        context.SetError("invalid_clientId", Resources.InvalidClientSecret);
                        return(Task.FromResult <object>(null));
                    }
                }
            }

            if (!client.Active)
            {
                context.SetError("invalid_clientId", Resources.ClientInactive);
                return(Task.FromResult <object>(null));
            }

            context.OwinContext.Set <string>("as:clientAllowedOrigin", client.AllowedOrigin);
            context.OwinContext.Set <string>("as:clientRefreshTokenLifeTime", client.RefreshTokenLifeTime.ToString());

            context.Validated();

            return(Task.FromResult <object>(null));
        }
Example #12
0
        /* Ese método irá validar o cliente. E retornará se a validação foi
         * realizada com sucesso */
        public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            var     clientId     = string.Empty;
            var     clientSecret = string.Empty;
            Cliente client       = null;

            if (!context.TryGetBasicCredentials(out clientId, out clientSecret))
            {
                context.TryGetFormCredentials(out clientId, out clientSecret);
            }

            if (context.ClientId == null)
            {
                context.Validated();
                return(Task.FromResult <object>(null));
            }

            using (var repository = new AuthRepository())
            {
                client = repository.EncontrarCliente(context.ClientId);
            }

            if (client == null)
            {
                context.SetError("invalid_clientId", string.Format("Cliente '{0}' não está registrado no sistema", context.ClientId));
                return(Task.FromResult <object>(null));
            }

            if (client.ApplicationType == ApplicationTypes.NativeConfidential)
            {
                if (string.IsNullOrWhiteSpace(clientSecret))
                {
                    context.SetError("invalid_clientId", "O segredo do cliente deve ser enviado.");
                    return(Task.FromResult <object>(null));
                }
                else
                {
                    if (client.Secret != Helper.GetHash(clientSecret))
                    {
                        context.SetError("invalid_clientId", "Segredo do cliente é inválido.");
                        return(Task.FromResult <object>(null));
                    }
                }
            }

            if (!client.Active)
            {
                context.SetError("invalid_clientId", "Cliente está inativo");
                return(Task.FromResult <object>(null));
            }

            context.OwinContext.Set("as:clientAllowedOrigin", client.AllowedOrigin);
            context.OwinContext.Set("as:clientRefreshTokenLifeTime", client.RefreshTokenLifeTime.ToString());

            context.Validated();

            return(Task.FromResult <object>(null));
        }
Example #13
0
        public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            string        clientId     = string.Empty;
            string        clientSecret = string.Empty;
            OpenAPIClient client       = null;

            if (!context.TryGetBasicCredentials(out clientId, out clientSecret))
            {
                context.TryGetFormCredentials(out clientId, out clientSecret);
            }

            if (context.ClientId == null)
            {
                context.Validated();
                context.SetError("invalid_clientId", "ClientId should be sent.");
                return(Task.FromResult <object>(null));
            }

            using (AuthenticationRepository _repo = new AuthenticationRepository())
            {
                client = _repo.Find_Client(context.ClientId);
            }

            if (client == null)
            {
                context.SetError("invalid_clientId", string.Format("Client '{0}' is not registered in the system.", context.ClientId));
                return(Task.FromResult <object>(null));
            }

            if (client.AppType == ApplicationTypes.AppTypes.NativeConfidential)
            {
                if (string.IsNullOrWhiteSpace(clientSecret))
                {
                    context.SetError("invalid_clientId", "Client secret should be sent.");
                    return(Task.FromResult <object>(null));
                }
                else
                {
                    if (client.Secret != Hasher.GetHash(clientSecret))
                    {
                        context.SetError("invalid_clientId", "Client secret is invalid.");
                        return(Task.FromResult <object>(null));
                    }
                }
            }

            if (!client.Active_Flag)
            {
                context.SetError("invalid_clientId", "Client is inactive.");
                return(Task.FromResult <object>(null));
            }

            context.OwinContext.Set <string>("clientAllowedOrigin", client.Allowed_Origin);
            context.OwinContext.Set <string>("clientRefreshTokenLifeSpan", client.RefreshToken_LifeSpan.ToString());

            context.Validated();
            return(Task.FromResult <object>(null));
        }
        public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            string clientId;
            string clientSecret;
            Client client;

            if (!context.TryGetBasicCredentials(out clientId, out clientSecret))
            {
                context.TryGetFormCredentials(out clientId, out clientSecret);
            }

            if (context.ClientId == null)
            {
                context.Validated();

                return(Task.FromResult <object>(null));
            }

            using (var repo = new AuthRepository())
            {
                client = repo.FindClient(context.ClientId);
            }

            if (client == null)
            {
                context.SetError("invalid_clientId", $"Client '{context.ClientId}' is not registered in the system.");
                return(Task.FromResult <object>(null));
            }

            if (client.ApplicationType == Models.ApplicationTypes.Console)
            {
                if (string.IsNullOrWhiteSpace(clientSecret))
                {
                    context.SetError("invalid_clientId", "Client secret should be sent.");
                    return(Task.FromResult <object>(null));
                }
                else
                {
                    if (client.Secret != Helper.GetHash(clientSecret))
                    {
                        context.SetError("invalid_clientId", "Client secret is invalid.");
                        return(Task.FromResult <object>(null));
                    }
                }
            }

            if (!client.Active)
            {
                context.SetError("invalid_clientId", "Client is inactive.");
                return(Task.FromResult <object>(null));
            }

            context.OwinContext.Set <string>("as:clientAllowedOrigin", client.AllowedOrigin);
            context.OwinContext.Set <string>("as:clientRefreshTokenLifeTime", client.RefreshTokenLifeTime.ToString());

            context.Validated();
            return(Task.FromResult <object>(null));
        }
Example #15
0
        public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            string          clientId     = string.Empty;
            string          clientSecret = string.Empty;
            ClientViewModel client       = null;

            if (!context.TryGetBasicCredentials(out clientId, out clientSecret))
            {
                context.TryGetFormCredentials(out clientId, out clientSecret);
            }

            if (context.ClientId == null)
            {
                //Remove the comments from the below line context.SetError, and invalidate context
                //if you want to force sending clientId/secrects once obtain access tokens.
                context.Validated();
                //context.SetError("invalid_clientId", "ClientId should be sent.");
                return(Task.FromResult <object>(null));
            }
            var clientService = StructuremapMvc.StructureMapDependencyScope.Container.GetInstance <IClientService>();

            client = clientService.FindClient(context.ClientId);

            if (client == null)
            {
                context.SetError("invalid_clientId", string.Format("Client '{0}' is not registered in the system.", context.ClientId));
                return(Task.FromResult <object>(null));
            }

            if (client.ApplicationType == ApplicationTypes.NativeConfidential)
            {
                if (string.IsNullOrWhiteSpace(clientSecret))
                {
                    context.SetError("invalid_clientId", "Client secret should be sent.");
                    return(Task.FromResult <object>(null));
                }
                else
                {
                    if (client.Secret != AppMethods.GetHash(clientSecret))
                    {
                        context.SetError("invalid_clientId", "Client secret is invalid.");
                        return(Task.FromResult <object>(null));
                    }
                }
            }

            if (!client.Active)
            {
                context.SetError("invalid_clientId", "Client is inactive.");
                return(Task.FromResult <object>(null));
            }

            context.OwinContext.Set <string>("as:clientAllowedOrigin", client.AllowedOrigin);
            context.OwinContext.Set <string>("as:clientRefreshTokenLifeTime", client.RefreshTokenLifeTime.ToString());

            context.Validated();
            return(Task.FromResult <object>(null));
        }
Example #16
0
        public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            string        clientId     = string.Empty;
            string        clientSecret = string.Empty;
            SYS_ClientApp client       = null;

            if (!context.TryGetBasicCredentials(out clientId, out clientSecret))
            {
                context.TryGetFormCredentials(out clientId, out clientSecret);
            }

            using (AuthRepository _repo = new AuthRepository())
            {
                client = _repo.FindClient(context.ClientId);
            }

            if (client == null)
            {
                context.SetError("invalid_clientId", string.Format("El cliente '{0}' es invalido.", context.ClientId));
                return(Task.FromResult <object>(null));
            }

            if (client.ApplicationType == Models.ApplicationTypes.NativeConfidential)
            {
                if (string.IsNullOrWhiteSpace(clientSecret))
                {
                    context.SetError("invalid_clientId", "No se recibió el secreto del cliente.");
                    return(Task.FromResult <object>(null));
                }
                else
                {
                    if (client.Secret != Helper.GetHash(clientSecret))
                    {
                        context.SetError("invalid_clientId", "El secreto del cliente es invalido.");
                        return(Task.FromResult <object>(null));
                    }
                }
            }

            if (!client.Active)
            {
                context.SetError("invalid_clientId", "El cliente se encuentra inactivo.");
                return(Task.FromResult <object>(null));
            }

            if (context.Parameters["company_code"] == null)
            {
                context.SetError("invalid_companyCode", "No se ha proporcionado un código de compañia.");
                return(Task.FromResult <object>(null));
            }

            context.OwinContext.Set("as:companyCode", context.Parameters["company_code"]);
            context.OwinContext.Set("as:clientAllowedOrigin", client.AllowedOrigin);
            context.OwinContext.Set("as:clientRefreshTokenLifeTime", client.RefreshTokenLifeTime.ToString());

            context.Validated();
            return(Task.FromResult <object>(null));
        }
        public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            string clientId            = string.Empty;
            string clientSecret        = string.Empty;
            RestfullAPI_Clients client = null;

            if (!context.TryGetBasicCredentials(out clientId, out clientSecret))
            {
                context.TryGetFormCredentials(out clientId, out clientSecret);
            }

            if (context.ClientId == null)
            {
                //Remove the comments from the below line context.SetError, and invalidate context
                //if you want to force sending clientId/secrects once obtain access tokens.
                context.SetError("Invalid_ClientId", "ClientId should be provided!");
                return(Task.FromResult <object>(null));
            }

            using (DataManagerService _repo = new DataManagerService())
            {
                client = _repo.FindClient(context.ClientId);
            }

            if (client == null)
            {
                context.SetError("Invalid_ClientId", string.Format("Client '{0}' is not registered in the system.", context.ClientId));
                return(Task.FromResult <object>(null));
            }

            if (client.ApplicationType == (int)AppTypes.AngularApp)
            {
                if (string.IsNullOrWhiteSpace(clientSecret))
                {
                    context.SetError("invalid_clientId", "Client secret should be sent.");
                    return(Task.FromResult <object>(null));
                }
                else
                {
                    if (client.Secret != clientSecret)
                    {
                        context.SetError("invalid_clientId", "Client secret is invalid.");
                        return(Task.FromResult <object>(null));
                    }
                }
            }

            if (!client.Active)
            {
                context.SetError("Error", "Provided ClientId is currently inactive.");
                return(Task.FromResult <object>(null));
            }
            context.OwinContext.Set <string>("as:clientAllowedOrigin", client.AllowedOrigin);
            context.OwinContext.Set <string>("as:clientRefreshTokenLifeTime", client.RefreshTokenLifeTime.ToString());
            context.Validated();
            return(Task.FromResult <object>(null));
        }
        /// <summary>
        /// 验证clientId与clientSecret
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            logger.Debug("ValidateClientAuthentication");
            string clientId;
            string clientSecret;
            int    code             = 0;
            string error            = "invalid_client";
            string errorDescription = "";

            if (!context.TryGetBasicCredentials(out clientId, out clientSecret))
            {
                context.TryGetFormCredentials(out clientId, out clientSecret);
            }
            if (string.IsNullOrEmpty(clientId) || string.IsNullOrEmpty(clientSecret))
            {
                errorDescription = "参数有误";
            }
            else
            {
                //获取附加的请求参数
                IReadableStringCollection parameters = context.Parameters;
                OauClient client = Clients.ApiClients.FirstOrDefault(a => a.AppId == clientId && a.AppSecret == clientSecret);
                if (client == null)
                {
                    errorDescription = "无效clientId或者无效的clientSecret";
                }
                else
                {
                    code = 1;
                    if (parameters != null)
                    {
                        //在OWIN环境中添加附加的请求参数
                        foreach (var item in parameters)
                        {
                            context.OwinContext.Set(OAuthKeys.Prefix + item.Key, string.Join(",", item.Value));
                        }
                        logger.Debug("ValidateClientAuthentication,context.Parameters:" + JsonConvert.SerializeObject(parameters));
                    }
                }
            }
            if (code == 1)
            {
                //设置客户机id并标记应用程序验证的上下文
                bool validateResult = context.Validated(clientId);
                logger.Debug("ValidateClientAuthentication,validateResult:" + validateResult);
                if (!validateResult)
                {
                    context.SetError(error, "validate 失败");
                }
            }
            else
            {
                //设置错误的响应信息
                context.SetError(error, errorDescription);
            }
            await base.ValidateClientAuthentication(context);
        }
Example #19
0
        public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext ctx)
        {
            string clientId     = string.Empty;
            string clientSecret = string.Empty;
            Client client       = null;

            if (!ctx.TryGetBasicCredentials(out clientId, out clientSecret))
            {
                ctx.TryGetFormCredentials(out clientId, out clientSecret);
            }

            if (ctx.ClientId == null)
            {
                ctx.SetError("No clientId specified ! ");
                return(Task.FromResult <object>(null));
            }

            using (AuthRepository _repo = new AuthRepository())
            {
                client = _repo.FindClient(clientId);
            }

            if (client == null)
            {
                ctx.SetError("clientId not found !");
                return(Task.FromResult <object>(null));
            }

            if (client.ApplicationType == ApplicationTypes.Native)
            {
                if (string.IsNullOrWhiteSpace(clientSecret))
                {
                    ctx.SetError("invalid_clientId", "Client secret should be sent.");
                    return(Task.FromResult <object>(null));
                }
                else
                {
                    if (client.Secret != GetHash(clientSecret))
                    {
                        ctx.SetError("invalid_clientId", "Client secret is invalid.");
                        return(Task.FromResult <object>(null));
                    }
                }
            }

            if (!client.Active)
            {
                ctx.SetError("invalid_clientId", "Client is inactive.");
                return(Task.FromResult <object>(null));
            }

            ctx.OwinContext.Set <string>("as:clientAllowedOrigin", client.AllowedOrigin);
            ctx.OwinContext.Set <string>("as:clientRefreshTokenLifeTime", client.RefreshTokenLifeTime.ToString());

            ctx.Validated();
            return(Task.FromResult <object>(null));
        }
Example #20
0
        /// <inheritdoc />
        public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            var    clientId     = string.Empty;
            var    clientSecret = string.Empty;
            Client client       = null;

            if (!context.TryGetBasicCredentials(out clientId, out clientSecret))
            {
                context.TryGetFormCredentials(out clientId, out clientSecret);
            }

            if (context.ClientId == null)
            {
                context.Validated( );
                context.SetError("invalid_clientId", "ClientId should be sent.");
                return(Task.FromResult <object> (null));
            }

            using (var _repo = new AuthRepository( ))
            {
                client = _repo.FindClient(context.ClientId);
            }

            if (client == null)
            {
                context.SetError(
                    "invalid_clientId",
                    string.Format("Client '{0}' is not registered in the system.", context.ClientId));
                return(Task.FromResult <object> (null));
            }

            //if (client.ApplicationType == ApplicationTypes.NativeConfidential) ;
            //{
            //    if (string.IsNullOrWhiteSpace(clientSecret))
            //    {
            //        context.SetError("invalid_clientId", "Client secret should be sent.");
            //        return Task.FromResult<object>(null);
            //    }
            //    if (client.Secret != Crypto.GetHash(clientSecret))
            //    {
            //        context.SetError("invalid_clientId", "Client secret is invalid.");
            //        return Task.FromResult<object>(null);
            //    }
            //}

            if (!client.Active)
            {
                context.SetError("invalid_clientId", "Client is inactive.");
                return(Task.FromResult <object> (null));
            }

            context.OwinContext.Set("as:clientAllowedOrigin", client.AllowedOrigin);
            context.OwinContext.Set("as:clientRefreshTokenLifeTime", client.RefreshTokenLifeTime.ToString( ));

            context.Validated( );
            return(Task.FromResult <object> (null));
        }
        // OAuthAuthorizationServerProvider sınıfının client erişimine izin verebilmek için ilgili ValidateClientAuthentication metotunu override ediyoruz.
        //public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        //{
        //    context.Validated();
        //    return Task.FromResult<object>(null);
        //}

        // OAuthAuthorizationServerProvider sınıfının kaynak erişimine izin verebilmek için ilgili GrantResourceOwnerCredentials metotunu override ediyoruz.
        //public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        //{
        //    // CORS ayarlarını set ediyoruz.
        //    context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

        //    _kullanici = await _kullanicilarService.GetKullanicilarByKullaniciAdiAsync(context.UserName);
        //    if (_kullanici == null)
        //    {
        //        context.SetError("invalid_grant", "Sistemde kayıtlı böyle bir kullanıcı bulunmamaktadır.");
        //        return;
        //    }

        //    if (_kullanici != null)
        //    {
        //        byte[] salt = Convert.FromBase64String(_kullanici.Salt);

        //        byte[] passwordSaltedHash = Utility.Hash(context.Password, salt);

        //        if (Convert.ToBase64String(passwordSaltedHash).Equals(_kullanici.SifreHash, StringComparison.InvariantCulture))
        //        {
        //            var identity = new ClaimsIdentity(context.Options.AuthenticationType);
        //            identity.AddClaim(new Claim("userName", _kullanici.KullaniciAdi));
        //            identity.AddClaim(new Claim("email", _kullanici.Email));
        //            identity.AddClaim(new Claim("userID", _kullanici.Id.ToString()));

        //            context.Validated(identity);
        //            context.Request.Context.Authentication.SignIn(identity);
        //        }
        //        else
        //            context.SetError("invalid_grant", "Kullanıcı adı veya şifre yanlış.");
        //    }
        //}

        //public override Task TokenEndpointResponse(OAuthTokenEndpointResponseContext context)
        //{
        //    var accessToken = context.AccessToken;
        //    _kullanicilarService.InsertKullaniciOturumAsync(new KullaniciOturumModel
        //    {
        //        AuthToken = context.AccessToken,
        //        KullaniciId = _kullanici.Id,
        //        SonlanmaTarihi = DateTime.Now.AddMinutes(2)
        //    });

        //    return Task.FromResult<object>(null);
        //}
        #endregion

        #region v.2.0.0
        //public override async Task ValidateClientRedirectUri(OAuthValidateClientRedirectUriContext context)
        //{
        //    //if (context.ClientId == Clients.Client1.Id)
        //    //{
        //    //    context.Validated(Clients.Client1.RedirectUrl);
        //    //}
        //    //else if (context.ClientId == Clients.Client2.Id)
        //    //{
        //    //    context.Validated(Clients.Client2.RedirectUrl);
        //    //}
        //    //return Task.FromResult(0);
        //}

        /// <summary>
        /// ValidateClientAuthentication
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            //context.Validated();
            string clientId;
            string clientSecret;

            _logger.Debug(GetType(), null, "Checking clientId & clientSecret");
            if (!context.TryGetBasicCredentials(out clientId, out clientSecret))
            {
                context.TryGetFormCredentials(out clientId, out clientSecret);
            }

            _logger.Debug(GetType(), null, "Is ClientId null");
            if (context.ClientId == null)
            {
                context.SetError("invalid_clientId", "ClientId parametre olarak gönderilmelidir.");
                return;
            }

            _logger.Debug(GetType(), null, "GetByClientIdAsync({0})", context.ClientId);
            _client = await _clientService.GetByClientIdAsync(context.ClientId);

            if (_client == null)
            {
                context.SetError("invalid_clientId", string.Format("Sistemde kayıtlı böyle bir client bulunmamaktadır.", context.ClientId));
                return;
            }

            //Client Secret ile işlem yapılmak istenirse açılmalıdır.
            //if (_client.ApplicationType == ApplicationTypes.WebDevelopment)
            //{
            //    if (string.IsNullOrWhiteSpace(clientSecret))
            //    {
            //        context.SetError("invalid_clientId", "Client secret should be sent.");
            //        return Task.FromResult<object>(null);
            //    }
            //    else
            //    {
            //        if (client.Secret != Helper.GetHash(clientSecret))
            //        {
            //            context.SetError("invalid_clientId", "Client secret is invalid.");
            //            return Task.FromResult<object>(null);
            //        }
            //    }
            //}

            if (!_client.Active)
            {
                context.SetError("invalid_clientId", "Client aktif değildir.");
                return;
            }

            context.OwinContext.Set <string>("as:clientAllowedOrigin", _client.AllowedOrigin);
            context.OwinContext.Set <string>("as:clientRefreshTokenLifeTime", _client.RefreshTokenLifeTime.ToString());

            context.Validated();
        }
Example #22
0
        public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            string clientId     = string.Empty;
            string clientSecret = string.Empty;
            Client client       = null;

            if (!context.TryGetBasicCredentials(out clientId, out clientSecret))
            {
                context.TryGetFormCredentials(out clientId, out clientSecret);
            }

            if (string.IsNullOrWhiteSpace(clientId))
            {
                context.Validated();
                context.SetError("invalid_clientId", "Client secret should be sent.");
                return(Task.FromResult <object>(null));
            }

            if (string.IsNullOrWhiteSpace(clientSecret))
            {
                context.SetError("invalid_clientId", "Client secret should be sent.");
                return(Task.FromResult <object>(null));
            }

            using (ClientRepository _clientRepository = new ClientRepository())
            {
                client = _clientRepository.FindClient(context.ClientId);
            }

            if (client == null)
            {
                context.SetError("invalid_clientId", string.Format("Client '{0}' is not registered in the system.", context.ClientId));
                return(Task.FromResult <object>(null));
            }

            if (client.ApplicationType == ApplicationTypes.WebApp)
            {
                if (client.Secret != Utility.GetHash(clientSecret))
                {
                    context.SetError("invalid_clientId", "Client secret is invalid.");
                    return(Task.FromResult <object>(null));
                }
            }

            if (!client.IsActive)
            {
                context.SetError("invalid_clientId", "Client is inactive.");
                return(Task.FromResult <object>(null));
            }

            context.OwinContext.Set <string>("ou:clientAllowedOrigin", client.AllowedOrigin);
            context.OwinContext.Set <string>("ou:clientRefreshTokenLifeTime", client.RefreshTokenLifeTime.ToString());

            context.Validated();
            return(Task.FromResult <object>(null));
        }
        public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            string      clientId;
            string      clientSecret;
            OAuthClient client = null;

            if (!context.TryGetBasicCredentials(out clientId, out clientSecret))
            {
                context.TryGetFormCredentials(out clientId, out clientSecret);
            }

            if (context.ClientId == null)
            {
                context.SetError("invalid_clientId", "ClientId should be sent.");
                return(Task.FromResult <object>(null));
            }

            var clientService = mobSocialEngine.ActiveEngine.Resolve <IClientService>();

            client = clientService.FirstOrDefault(x => x.Guid == clientId);

            if (client == null)
            {
                context.SetError("invalid_clientId", $"Client '{context.ClientId}' is not registered in the system.");
                return(Task.FromResult <object>(null));
            }
            //native applications should also pass client secret
            if (client.ApplicationType == ApplicationType.NativeConfidential || client.ApplicationType == ApplicationType.NativeFullControl)
            {
                if (string.IsNullOrWhiteSpace(clientSecret))
                {
                    context.SetError("invalid_clientId", "Client secret should be sent.");
                    return(Task.FromResult <object>(null));
                }
                else
                {
                    if (client.Secret != Helper.GetHash(clientSecret))
                    {
                        context.SetError("invalid_clientId", "Client secret is invalid.");
                        return(Task.FromResult <object>(null));
                    }
                }
            }

            if (!client.Active)
            {
                context.SetError("invalid_clientId", "Client is inactive.");
                return(Task.FromResult <object>(null));
            }

            context.OwinContext.Set <string>("as:clientAllowedOrigin", client.AllowedOrigin);
            context.OwinContext.Set <string>("as:clientRefreshTokenLifeTime", client.RefreshTokenLifeTime.ToString());

            context.Validated();
            return(Task.FromResult <object>(null));
        }
Example #24
0
        public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            string clientId;
            string clientSecret;

            if (!context.TryGetBasicCredentials(out clientId, out clientSecret))
            {
                context.TryGetFormCredentials(out clientId, out clientSecret);
            }

            if (context.ClientId == null)
            {
                context.Validated();
                context.SetError("invalid_clientId", "ClientId should be sent.");
                return;
            }

            var client = await _oauthDataManager.GetApplication(context.ClientId);

            if (client == null)
            {
                context.SetError("invalid_clientId",
                                 string.Format("Client '{0}' is not registered in the system.", context.ClientId));

                return;
            }

            if (!string.IsNullOrEmpty(client.Secret))
            {
                if (string.IsNullOrWhiteSpace(clientSecret))
                {
                    context.SetError("invalid_clientId", "Client secret should be sent.");
                    return;
                }

                if (client.Secret != _oauthSecurity.GetHash(clientSecret))
                {
                    context.SetError("invalid_clientId", "Client secret is invalid.");
                    return;
                }
            }

            if (!client.Active)
            {
                context.SetError("invalid_clientId", "Client is inactive.");
                return;
            }

            context.OwinContext.Set("as:clientAllowedOrigin", client.AllowedOrigin);
            if (_settings.RefresherTokenEnabled)
            {
                context.OwinContext.Set("as:clientRefreshTokenLifeTime",
                                        client.RefreshTokenLifeTime.ToString(CultureInfo.InvariantCulture));
            }
            context.Validated();
        }
        public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            string clientId     = string.Empty;
            string clientSecret = string.Empty;
            Client client       = null;

            if (!context.TryGetBasicCredentials(out clientId, out clientSecret))
            {
                context.TryGetFormCredentials(out clientId, out clientSecret);
            }

            if (context.ClientId == null)
            {
                context.Validated();
                return;
            }

            var repository = kernel.Get <ISecurityRepository>();

            client = await repository.FindClient(context.ClientId);

            if (client == null)
            {
                context.SetError("invalid_clientId", string.Format("Client '{0}' is not registered in the system.", context.ClientId));
                return;
            }

            if (client.ApplicationType == ApplicationType.NativeConfidential)
            {
                if (string.IsNullOrWhiteSpace(clientSecret))
                {
                    context.SetError("invalid_clientId", "Client secret should be sent.");
                    return;
                }
                else
                {
                    if (client.Secret != HashingHelper.GetHash(clientSecret))
                    {
                        context.SetError("invalid_clientId", "Client secret is invalid.");
                        return;
                    }
                }
            }

            if (!client.Active)
            {
                context.SetError("invalid_clientId", "Client is inactive.");
                return;
            }

            context.OwinContext.Set("clientAllowedOrigin", client.AllowedOrigin);
            context.OwinContext.Set("clientRefreshTokenLifeTime", client.RefreshTokenLifeTime.ToString());

            context.Validated();
            return;
        }
        /// <summary>The validate client authentication.</summary>
        /// <param name="context">The context.</param>
        /// <returns>The <see cref="Task"/>.</returns>
        public async override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            // Initiate and start a diagnostic stopwatch
            string clientId;
            string clientSecret;

            if (!context.TryGetBasicCredentials(out clientId, out clientSecret))
            {
                context.TryGetFormCredentials(out clientId, out clientSecret);
            }

            if (context.ClientId == null)
            {
                // Remove the comments from the below line context.SetError, and invalidate context
                // if you want to force sending clientId/secrects once obtain access tokens.
                context.Validated();

                // context.SetError("invalid_clientId", "ClientId should be sent.");
                // return Task.FromResult<object>(null);
            }

            // TODO Change the Input to pass contect.ClientId
            // var inputparam = new AuthorizationInput { ClientAppName = context.ClientId };

            // var authorizationJson = JsonConvert.SerializeObject(inputparam);

            // Create Dictionary with Key : filter and Value is JSON String
            var clientController = AuthHelper.FindClientController(context.ClientId);

            var client = await this.authFacade.FindClient(clientController);

            // TODO this may cause issue due to longer run of code, if fail first check here. make this func aysnc
            if (client == null)
            {
                context.SetError("invalid_clientId", $"Client '{context.ClientId}' is not registered in the system.");
                //  return Task.FromResult<object>(null);
            }

            var b = !client.IsActive;

            if (b != null && (bool)b)
            {
                context.SetError("invalid_clientId", "Client is inactive.");
                // return Task.FromResult<object>(null);
            }

            context.OwinContext.Set <string>("as:clientAllowedOrigin", client.AllowedOrigin);
            context.OwinContext.Set <string>(
                "as:clientRefreshTokenLifeTime",
                client.RefreshTokenLifeTime.ToString(CultureInfo.InvariantCulture));

            context.Validated();

            // return Task.FromResult<object>(null);
        }
Example #27
0
        public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            EventLogger.Log("APIVoucherUpdate.PostAPIVoucherUpdateControl", "ValidateClientAuthentication", EventLogger.Event.START, "ValidateClientAuthentication method called :");
            string clientId     = string.Empty;
            string clientSecret = string.Empty;

            if (!context.TryGetBasicCredentials(out clientId, out clientSecret))
            {
                context.TryGetFormCredentials(out clientId, out clientSecret);
            }

            if (context.ClientId == null)
            {
                context.Rejected();
                context.SetError("invalid_client", "Client credentials could not be retrieved through the Authorization header.");

                return;
            }

            try
            {
                if (clientId == ConfigurationManager.AppSettings["client_id"].ToString() && clientSecret == ConfigurationManager.AppSettings["client_secret"].ToString())
                {
                    context.Validated(clientId);
                }
                else
                {
                    context.Rejected();
                    context.SetError("invalid_client", "Client credentials are invalid.");
                }
            }
            catch (Exception ex)
            {
                string errorMessage = ex.Message;
                context.Rejected();
                context.SetError("server_error");
            }

            string resource = context.Parameters.Where(x => x.Key == "resource").Select(y => y.Value).FirstOrDefault()[0];

            if (resource == ConfigurationManager.AppSettings["resource"].ToString() && context.IsValidated)
            {
                context.Validated(clientId);
            }
            else
            {
                if (context.IsValidated)
                {
                    context.Rejected();
                    context.SetError("invalid_Resource", "Resource credentials are invalid.");
                }
            }
            EventLogger.Log("APIVoucherUpdate.PostAPIVoucherUpdateControl", "ValidateClientAuthentication", EventLogger.Event.END, "ValidateClientAuthentication method called :");
            return;
        }
        /// <summary>
        /// Called to validate that the origin of the request is a registered "client_id", and that the correct credentials for that client are
        /// present on the request.
        /// </summary>
        public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            string clientId;
            string clientSecret;

            if (!context.TryGetBasicCredentials(out clientId, out clientSecret))
            {
                context.TryGetFormCredentials(out clientId, out clientSecret);
            }

            if (context.ClientId == null)
            {
                //Remove the comments from the below line if not requiring clientId, and comment the call to SetError
                //context.Validated();
                context.SetError("invalid_clientId", "ClientId should be sent.");
                return;
            }

            //TODO: change to IoC instead of OwinContext
            var repo   = new AuthService(context.OwinContext.Get <ApplicationDbContext>());
            var client = await repo.FindClient(context.ClientId);

            if (client == null)
            {
                context.SetError(Constants.INVALID_CLIENT_ID, string.Format("Client '{0}' is not registered in the system.", context.ClientId));
                return;
            }

            if (client.ApplicationType == ApplicationTypes.NativeConfidential)
            {
                if (string.IsNullOrWhiteSpace(clientSecret))
                {
                    context.SetError(Constants.INVALID_CLIENT_ID, "Client secret should be sent.");
                    return;
                }

                if (client.Secret != Helper.GetHash(clientSecret))
                {
                    context.SetError(Constants.INVALID_CLIENT_ID, "Client secret is invalid.");
                    return;
                }
            }

            if (!client.Active)
            {
                context.SetError(Constants.INVALID_CLIENT_ID, "Client is inactive.");
                return;
            }

            context.OwinContext.Set(Constants.KEY_CLIENT_ALLOWED_ORIGIN, client.AllowedOrigin);
            context.OwinContext.Set(Constants.KEY_CLIENT_REFRESHTOKEN_LIFETIME, client.RefreshTokenLifeTime.ToString(CultureInfo.InvariantCulture));

            context.Validated();
        }
Example #29
0
        public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            string clientId     = string.Empty;
            string clientSecret = string.Empty;
            Client client       = null;

            if (!context.TryGetBasicCredentials(out clientId, out clientSecret))
            {
                context.TryGetFormCredentials(out clientId, out clientSecret);
            }

            if (context.ClientId == null)
            {
                context.Validated();
                return(Task.FromResult <object>(null));
            }

            client = _identityService.FindClient(context.ClientId);

            if (client == null)
            {
                context.SetError("invalid_clientId", string.Format($"Client {context.ClientId} is not registered in the system"));
                return(Task.FromResult <object>(null));
            }

            if (client.ApplicationType == ApplicationTypes.NativeConfidential)
            {
                if (string.IsNullOrWhiteSpace(clientSecret))
                {
                    context.SetError("invalid_clientId", "Client secret should be sent");
                    return(Task.FromResult <object>(null));
                }
                else
                {
                    if (client.Secret != Helper.GetHash(clientSecret))
                    {
                        context.SetError("invalid_clientId", "Client secret is invalid");
                        return(Task.FromResult <object>(null));
                    }
                }
            }

            if (!client.Active)
            {
                context.SetError("invalid_clientId", "Client is inactive.");
                return(Task.FromResult <object>(null));
            }

            context.OwinContext.Set("as:clientAllowedOrigin", client.AllowedOrigin);
            context.OwinContext.Set("as:clientRefreshTokenLifeTime", client.RefreshTokenLifeTime.ToString());

            context.Validated();
            return(Task.FromResult <object>(null));
        }
Example #30
0
        public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            string clientId             = string.Empty;
            string clientSecret         = string.Empty;
            string symmetricKeyAsBase64 = string.Empty; //TODO: implement this

            if (!context.TryGetBasicCredentials(out clientId, out clientSecret))
            {
                context.TryGetFormCredentials(out clientId, out clientSecret);
            }

            if (context.ClientId == null)
            {
                context.SetError("invalid_clientId", "client_Id is not set");
                return(Task.FromResult <object>(null));
            }

            var audience = AudienceRepository.FindAudience(context.ClientId);

            if (audience == null)
            {
                context.SetError("invalid_clientId", string.Format("Invalid client_id '{0}'", context.ClientId));
                return(Task.FromResult <object>(null));
            }

            if (audience.ApplicationType == ApplicationTypes.NativeConfidential)
            {
                if (string.IsNullOrWhiteSpace(clientSecret))
                {
                    context.SetError("invalid_clientId", "Client/Audeince secret should be sent.");
                    return(Task.FromResult <object>(null));
                }
                else
                {
                    if (audience.Base64Secret != Helper.GetHash(clientSecret))
                    {
                        context.SetError("invalid_clientId", "Client/Audeience secret is invalid.");
                        return(Task.FromResult <object>(null));
                    }
                }
            }

            if (!audience.Active)
            {
                context.SetError("invalid_clientId", "Client is inactive.");
                return(Task.FromResult <object>(null));
            }

            context.OwinContext.Set <string>("as:clientAllowedOrigin", audience.AllowedOrigin);
            context.OwinContext.Set <string>("as:clientRefreshTokenLifeTime", audience.RefreshTokenLifeTime.ToString());

            context.Validated();
            return(Task.FromResult <object>(null));
        }