internal void NotifyOfCallback(Intent intent)
        {
            try
            {
                if (!intent.HasExtra(Constants.AuthStateKey))
                {
                    _authState = null;
                }
                else
                {
                    try
                    {
                        _authState = AuthState.JsonDeserialize(intent.GetStringExtra(Constants.AuthStateKey));
                    }
                    catch (JSONException ex)
                    {
                        Console.WriteLine("Malformed AuthState JSON saved: " + ex);
                        _authState = null;
                    }
                }
                if (_authState != null)
                {
                    AuthorizationResponse  response = AuthorizationResponse.FromIntent(intent);
                    AuthorizationException authEx   = AuthorizationException.FromIntent(intent);
                    _authState.Update(response, authEx);

                    if (response != null)
                    {
                        Console.WriteLine("Received AuthorizationResponse.");
                        try
                        {
                            var clientAuthentication = _authState.ClientAuthentication;
                        }
                        catch (ClientAuthenticationUnsupportedAuthenticationMethod ex)
                        {
                            _loginResultWaitHandle.Set();

                            Console.WriteLine(
                                "Token request cannot be made, client authentication for the token endpoint could not be constructed: " +
                                ex);

                            return;
                        }
                        _authService.PerformTokenRequest(response.CreateTokenExchangeRequest(), ReceivedTokenResponse);
                    }
                    else
                    {
                        Console.WriteLine("Authorization failed: " + authEx);
                    }
                }
                else
                {
                    _loginResultWaitHandle.Set();
                }
            }
            catch (Exception)
            {
                _loginResultWaitHandle.Set();
            }
        }
        public void Read(TProtocol iprot)
        {
            TField field;

            iprot.ReadStructBegin();
            while (true)
            {
                field = iprot.ReadFieldBegin();
                if (field.Type == TType.Stop)
                {
                    break;
                }
                switch (field.ID)
                {
                case 1:
                    if (field.Type == TType.Struct)
                    {
                        Aze = new AuthorizationException();
                        Aze.Read(iprot);
                    }
                    else
                    {
                        TProtocolUtil.Skip(iprot, field.Type);
                    }
                    break;

                default:
                    TProtocolUtil.Skip(iprot, field.Type);
                    break;
                }
                iprot.ReadFieldEnd();
            }
            iprot.ReadStructEnd();
        }
Exemple #3
0
        protected virtual void HandleUnauthorizedRequest(
            AuthorizationContext filterContext,
            MethodInfo methodInfo,
            AuthorizationException ex)
        {
            filterContext.HttpContext.Response.StatusCode =
                filterContext.RequestContext.HttpContext.User?.Identity?.IsAuthenticated ?? false
                    ? (int)HttpStatusCode.Forbidden
                    : (int)HttpStatusCode.Unauthorized;

            var isJsonResult = MethodInfoHelper.IsJsonResult(methodInfo);

            if (isJsonResult)
            {
                filterContext.Result = CreateUnAuthorizedJsonResult(ex);
            }
            else
            {
                filterContext.Result = CreateUnAuthorizedNonJsonResult(filterContext, ex);
            }

            if (isJsonResult || filterContext.HttpContext.Request.IsAjaxRequest())
            {
                filterContext.HttpContext.Response.SuppressFormsAuthenticationRedirect = true;
            }
            _eventBus.Trigger(this, new HandledExceptionData(ex));
        }
Exemple #4
0
 public override T Execute <T>(ICommand <T> command)
 {
     try
     {
         Count++; // only catch exception if we are at the top of the command stack
         // (there may be multiple nested command invocations and we need
         // to prevent that this intercepter swallows an exception)
         var result = Next.Execute(command);
         Count--;
         return(result);
     }
     catch (AuthorizationException e)
     {
         Count--;
         if (Count == 0 && IsActive)
         {
             lastException = e;
             Console.WriteLine("Caught authorization exception; storing for Assertion in test", e);
         }
         else
         {
             throw e;
         }
     }
     return(default(T));
 }
Exemple #5
0
 public override T execute <T>(Command <T> command)
 {
     try
     {
         count++;   // only catch exception if we are at the top of the command stack
         // (there may be multiple nested command invocations and we need
         // to prevent that this intercepter swallows an exception)
         T result = next.execute(command);
         count--;
         return(result);
     }
     catch (AuthorizationException e)
     {
         count--;
         if (count == 0 && isActive)
         {
             lastException = e;
             LOG.info("Caught authorization exception; storing for assertion in test", e);
         }
         else
         {
             throw e;
         }
     }
     return(default(T));
 }
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            //SetContentView(Resource.Layout.activity_token);

            _authService = new AuthorizationService(this);

            if (savedInstanceState != null)
            {
                if (savedInstanceState.ContainsKey(KEY_AUTH_STATE))
                {
                    try
                    {
                        _authState = AuthState.JsonDeserialize(savedInstanceState.GetString(KEY_AUTH_STATE));
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Malformed authorization JSON saved: " + ex);
                    }
                }

                if (savedInstanceState.ContainsKey(KEY_USER_INFO))
                {
                    try
                    {
                        _userInfoJson = new JSONObject(savedInstanceState.GetString(KEY_USER_INFO));
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Failed to parse saved user info JSON: " + ex);
                    }
                }
            }

            if (_authState == null)
            {
                _authState = GetAuthStateFromIntent(Intent);
                var response = AuthorizationResponse.FromIntent(Intent);
                var ex       = AuthorizationException.FromIntent(Intent);
                _authState.Update(response, ex);

                if (response != null)
                {
                    Console.WriteLine("Received AuthorizationResponse");
                    PerformTokenRequest(response.CreateTokenExchangeRequest());
                }
                else
                {
                    Console.WriteLine("Authorization failed: " + ex);
                }
            }

            //RefreshUi();

            //var contactsViewController = App.GetContactsPage().CreateViewController();
            //NavigationController.PresentViewController(contactsViewController, true, null);
            Xamarin.Forms.Forms.Init(this, savedInstanceState);
            LoadApplication(new App());
        }
		protected string SignedPost (string url, IDictionary<string,string> parameters, OAuth.Token token) {			
			HttpWebRequest request = (HttpWebRequest)WebRequest.Create (url);
			request.Method = "POST";
			request.ContentType = "application/x-www-form-urlencoded";
			request.Headers.Add ("Authorization", OAuth.Sign (Consumer, url, parameters, token, "POST", null));
			StreamWriter streamWriter = new StreamWriter (request.GetRequestStream ());
			streamWriter.Write (OAuth.PercentEscape (parameters));
			streamWriter.Close ();
			
			HttpWebResponse response;
			try {
				response = (HttpWebResponse)request.GetResponse ();
			} catch(WebException e) {
				RdioException re;
				response = (HttpWebResponse)e.Response;
				if (response.StatusCode == HttpStatusCode.Forbidden ||
				    response.StatusCode == HttpStatusCode.Unauthorized) {
					re = new AuthorizationException();
				} else {
					re = new RdioException();
				}
				re.Request = request;
				re.Response = response;
				re.Exception = e;
				throw re;
			}
			StreamReader streamReader = new StreamReader (response.GetResponseStream ());
			return streamReader.ReadToEnd ();
		}
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            SetContentView(Resource.Layout.activity_token);

            if (savedInstanceState != null)
            {
                if (savedInstanceState.ContainsKey(KEY_AUTH_STATE))
                {
                    authState = AuthState.JsonDeserialize(savedInstanceState.GetString(KEY_AUTH_STATE));
                }

                if (savedInstanceState.ContainsKey(KEY_USER_INFO))
                {
                    userInfoJson = new JSONObject(savedInstanceState.GetString(KEY_USER_INFO));
                }
            }

            if (authState == null)
            {
                authState = GetAuthStateFromIntent(Intent);
                AuthorizationResponse  response = AuthorizationResponse.FromIntent(Intent);
                AuthorizationException ex       = AuthorizationException.FromIntent(Intent);
                authState.Update(response, ex);
                if (response != null)
                {
                    PerformTokenRequest(response.CreateTokenExchangeRequest());
                }
            }
        }
        protected override void OnCreate(Bundle savedInstanceState)
        {
            AuthorizationResponse  resp = AuthorizationResponse.FromIntent(Intent);
            AuthorizationException ex   = AuthorizationException.FromIntent(Intent);

            base.OnCreate(savedInstanceState);
        }
 public void OnTokenFailure(AuthorizationException ex)
 {
     Activity.RunOnUiThread(() =>
     {
         Activity.showMessage(Activity.GetString(Resource.String.init_failure) + ":" + ex.ErrorDescription);
     });
 }
Exemple #11
0
        internal static void AuthorizeAccion(IdAccion idAccion, int idUsuario, TipoPermiso eJECUCION)
        {
            var keyArray = new KeyArray();
            var tpAuth   = CachingManager.Instance.GetAutorizacion(idUsuario, (short)idAccion, eJECUCION).tipoAutorizacion;

            if (tpAuth == TipoAutorizacion.CON_PERMISOS || tpAuth == TipoAutorizacion.CON_DOBLE_CONTROL)
            {
                return;
            }

            AccionEntity accion = CachingManager.Instance.GetAccionById((short)idAccion);

            keyArray.Codigo = CodigosMensajes.FE_ERROR_FALTA_PERMISOS;
            if (accion != null)
            {
                keyArray.Parametros.Add(accion.Descripcion);
            }
            else
            {
                keyArray.Parametros.Add(string.Format("Acción {0} no encontrada", idAccion));
            }
            var fe = new AuthorizationException(001);

            fe.DataValidations.Add(keyArray);
            throw fe;
        }
Exemple #12
0
        public static void Authorize(Command command, int idUsuario)
        {
            var   keyArray = new KeyArray();
            short idAccion = Convert.ToInt16(command.GetIdAccion);
            var   tpAuth   = CachingManager.Instance.GetAutorizacion(idUsuario, idAccion, (TipoPermiso)command.GetIdPermiso).tipoAutorizacion;

            if (tpAuth == TipoAutorizacion.CON_PERMISOS || tpAuth == TipoAutorizacion.CON_DOBLE_CONTROL)
            {
                return;
            }

            AccionEntity accion = CachingManager.Instance.GetAccionById(idAccion);

            keyArray.Codigo = CodigosMensajes.FE_ERROR_FALTA_PERMISOS;
            if (accion != null)
            {
                keyArray.Parametros.Add(accion.Descripcion);
            }
            else
            {
                keyArray.Parametros.Add(string.Format("Acción {0} no encontrada", idAccion));
            }
            var fe = new AuthorizationException(001);

            fe.DataValidations.Add(keyArray);
            throw fe;
        }
Exemple #13
0
 protected override void HandleUnauthorizedRequest(
     AuthorizationContext filterContext,
     MethodInfo methodInfo,
     AuthorizationException ex)
 {
     base.HandleUnauthorizedRequest(filterContext, methodInfo, ex);
 }
        /// <summary>
        /// Handles the auth result.Should be called from <see cref="Activity.OnActivityResult(int, Result, Intent)">
        /// </summary>
        /// <returns>The auth result.</returns>
        /// <param name="intent">Intent.</param>
        public async Task HandleAuthResult(Intent intent)
        {
            NonNull(intent, "intent");
            NonNull(authenticateTaskComplete, "authenticateTaskComplete");

            AuthorizationResponse  response = AuthorizationResponse.FromIntent(intent);
            AuthorizationException error    = AuthorizationException.FromIntent(intent);

            authState.Update(response, error);

            if (response != null)
            {
                try
                {
                    User user = await exchangeTokens(response);

                    authenticateTaskComplete.TrySetResult(user);
                }
                catch (Exception ex)
                {
                    this.logger.Error("Unexpected error in token exchange", ex);
                    authenticateTaskComplete.TrySetException(ex);
                }
            }
            else
            {
                authenticateTaskComplete.TrySetException(error);
            }
        }
 /// <summary>
 /// Extension method that generates problem details for the exception.
 /// </summary>
 /// <param name="source">The exception to map to a <see cref="ProblemDetails"/></param>
 /// <param name="controller">The base controller the exception occured in. </param>
 /// <param name="type">Optional parameter that sets the URL for the human readable explanation for the status code. Default value is set to https://httpstatuses.com/403 </param>
 /// <param name="status">Optional parameter that sets the return status code for the problem. Default value is set to 403.</param>
 /// <param name="title">Optional parameter that sets the title for the problem. Default value is set to Forbidden.</param>
 /// <returns>Instance of the problem details.</returns>
 public static ProblemDetails GetProblemDetails(this AuthorizationException source,
                                                ControllerBase controller, string type = "https://httpstatuses.com/401",
                                                int?status = 401, string title = "UnAuthorized")
 {
     return(new ProblemDetails {
         Type = type, Status = status, Title = title, Instance = controller?.HttpContext?.Request?.Path, Detail = source?.Message
     });
 }
Exemple #16
0
 protected virtual InfrastructureJsonResult CreateUnAuthorizedJsonResult(AuthorizationException ex)
 {
     return(new InfrastructureJsonResult(
                new AjaxResponse(_errorInfoBuilder.BuildForException(ex), true))
     {
         JsonRequestBehavior = JsonRequestBehavior.AllowGet
     });
 }
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            AuthorizationResponse  resp = AuthorizationResponse.FromIntent(Intent);
            AuthorizationException ex   = AuthorizationException.FromIntent(Intent);

            AuthService.Instance.AuthActivityCreated(resp, ex);
            Finish();
        }
 public void OnTokenFailure(AuthorizationException p0)
 {
     // Handle a network error when fetching the user info data
     Activity.mUserInfoJson[KeyUserInfo] = null;
     Activity.RunOnUiThread(() => {
         Activity.displayAuthorizationInfo();
         Activity.showSnackbar(Activity.GetString(Resource.String.network_failure_message));
     });
 }
Exemple #19
0
    public virtual async Task HandleAsync(AuthorizationException exception, HttpContext httpContext)
    {
        var handlerOptions  = httpContext.RequestServices.GetRequiredService <IOptions <AuthorizationExceptionHandlerOptions> >().Value;
        var isAuthenticated = httpContext.User.Identity?.IsAuthenticated ?? false;
        var authenticationSchemeProvider = httpContext.RequestServices.GetRequiredService <IAuthenticationSchemeProvider>();

        AuthenticationScheme scheme = null;

        if (!handlerOptions.AuthenticationScheme.IsNullOrWhiteSpace())
        {
            scheme = await authenticationSchemeProvider.GetSchemeAsync(handlerOptions.AuthenticationScheme);

            if (scheme == null)
            {
                throw new Exception($"No authentication scheme named {handlerOptions.AuthenticationScheme} was found.");
            }
        }
        else
        {
            if (isAuthenticated)
            {
                scheme = await authenticationSchemeProvider.GetDefaultForbidSchemeAsync();

                if (scheme == null)
                {
                    throw new LinFxException($"There was no DefaultForbidScheme found.");
                }
            }
            else
            {
                scheme = await authenticationSchemeProvider.GetDefaultChallengeSchemeAsync();

                if (scheme == null)
                {
                    throw new LinFxException($"There was no DefaultChallengeScheme found.");
                }
            }
        }

        var handlers = httpContext.RequestServices.GetRequiredService <IAuthenticationHandlerProvider>();
        var handler  = await handlers.GetHandlerAsync(httpContext, scheme.Name);

        if (handler == null)
        {
            throw new LinFxException($"No handler of {scheme.Name} was found.");
        }

        if (isAuthenticated)
        {
            await handler.ForbidAsync(null);
        }
        else
        {
            await handler.ChallengeAsync(null);
        }
    }
Exemple #20
0
        public static void AddSecurityServices(this IServiceCollection services,
                                               IConfiguration configuration)
        {
            services.AddAuthentication(opts =>
            {
                opts.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                opts.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(opts =>
            {
                opts.Authority                 = configuration.GetValue <string>("SSoSetting:SSOIdentityUrl") + "/identity";
                opts.RequireHttpsMetadata      = false;
                opts.TokenValidationParameters = new TokenValidationParameters()
                {
                    ValidateAudience = false,
                    ValidAudiences   = new[]
                    {
                        $"{opts.Authority}/resources"
                    }
                };
                opts.IncludeErrorDetails = true;
                opts.Events = new JwtBearerEvents
                {
                    OnAuthenticationFailed = async context =>
                    {
                        Exception ex = context.Exception;
                        Log.Error(ex);

                        var result = GlobalExceptionFilter.GetStatusCode <object>(ex);
                        context.Response.StatusCode  = (int)result.statusCode;
                        context.Response.ContentType = "application/json";

                        var responseJson = JsonConvert.SerializeObject(result.responseModel, new JsonSerializerSettings()
                        {
                            NullValueHandling = NullValueHandling.Ignore
                        });
                        await context.Response.WriteAsync(responseJson);
                    }
                };
                opts.Events.OnChallenge = async context =>
                {
                    context.HandleResponse();
                    Exception ex = new AuthorizationException(context.ErrorDescription ?? "User is unauthorised");
                    Log.Error(ex);

                    var result = GlobalExceptionFilter.GetStatusCode <object>(ex);
                    context.Response.StatusCode  = (int)result.statusCode;
                    context.Response.ContentType = "application/json";

                    var responseJson = JsonConvert.SerializeObject(result.responseModel, new JsonSerializerSettings()
                    {
                        NullValueHandling = NullValueHandling.Ignore
                    });
                    await context.Response.WriteAsync(responseJson);
                };
            });
        }
        public virtual void AssertAuthorizationException(AuthorizationException e)
        {
            if (missingAuthorizations.Count > 0 && e != null)
            {
                var message = e.Message;
                var AssertionFailureMessage =
                    DescribeScenarioFailure("Expected an authorization exception but the message was wrong: " +
                                            e.Message);

                IList <MissingAuthorization> actualMissingAuthorizations =
                    new List <MissingAuthorization>(e.MissingAuthorizations);
                //IList<MissingAuthorization> expectedMissingAuthorizations = MissingAuthorizationMatcher.asMissingAuthorizations(missingAuthorizations);

                //Assert.That(actualMissingAuthorizations, Is.EquivalentTo(expectedMissingAuthorizations));

                foreach (var missingAuthorization in missingAuthorizations)
                {
                    Assert.True(message.Contains(missingAuthorization.UserId), AssertionFailureMessage);
                    Assert.AreEqual(missingAuthorization.UserId, e.UserId);

                    foreach (var permission in missingAuthorization.GetPermissions((Permissions[])typeof(Permissions).GetEnums()))
                    {
                        if (permission != Permissions.None)
                        {
                            Assert.True(message.Contains(permission.ToString()), AssertionFailureMessage);
                        }
                    }

                    if (!AuthorizationFields.Any.Equals(missingAuthorization.ResourceId))
                    {
                        Assert.True(message.Contains(missingAuthorization.ResourceId), AssertionFailureMessage);
                    }

                    //Resources resource = AuthorizationTestUtil.GetResourceByType(missingAuthorization.ResourceType);
                    //Assert.True( message.Contains(resource.ToString()/*.ResourceName()*/), AssertionFailureMessage);
                }
            }
            else if (missingAuthorizations.Count == 0 && e == null)
            {
                // nothing to do
            }
            else
            {
                if (e != null)
                {
                    Assert.Fail(DescribeScenarioFailure("Expected no authorization exception but got one: " + e.Message));
                }
                else
                {
                    Assert.Fail(
                        DescribeScenarioFailure(
                            "Expected failure due to missing authorizations but code under test was successful"));
                }
            }
        }
 public void it_can_be_caught_as_a_security_exception()
 {
     var exception = new AuthorizationException();
     try
     {
         throw exception;
     }
     catch (SecurityException exc)
     {
         Expect(exc, Is.SameAs(exception));
     }
 }
Exemple #23
0
        public virtual void assertAuthorizationException(AuthorizationException e)
        {
            if (missingAuthorizations.Count > 0 && e != null)
            {
                string message = e.Message;
                string assertionFailureMessage = describeScenarioFailure("Expected an authorization exception but the message was wrong: " + e.Message);

                IList <MissingAuthorization> actualMissingAuthorizations   = new List <MissingAuthorization>(e.MissingAuthorizations);
                IList <MissingAuthorization> expectedMissingAuthorizations = MissingAuthorizationMatcher.asMissingAuthorizations(missingAuthorizations);

                Assert.assertThat(actualMissingAuthorizations, containsInAnyOrder(MissingAuthorizationMatcher.asMatchers(expectedMissingAuthorizations)));

                foreach (Authorization missingAuthorization in missingAuthorizations)
                {
                    Assert.assertTrue(assertionFailureMessage, message.Contains(missingAuthorization.UserId));
                    Assert.assertEquals(missingAuthorization.UserId, e.UserId);

                    Permission[] permissions = AuthorizationTestUtil.getPermissions(missingAuthorization);
                    foreach (Permission permission in permissions)
                    {
                        if (permission.Value != Permissions.NONE.Value)
                        {
                            Assert.assertTrue(assertionFailureMessage, message.Contains(permission.Name));
                            break;
                        }
                    }

                    if (!org.camunda.bpm.engine.authorization.Authorization_Fields.ANY.Equals(missingAuthorization.ResourceId))
                    {
                        // missing ANY authorizations are not explicitly represented in the error message
                        Assert.assertTrue(assertionFailureMessage, message.Contains(missingAuthorization.ResourceId));
                    }

                    Resource resource = AuthorizationTestUtil.getResourceByType(missingAuthorization.ResourceType);
                    Assert.assertTrue(assertionFailureMessage, message.Contains(resource.resourceName()));
                }
            }
            else if (missingAuthorizations.Count == 0 && e == null)
            {
                // nothing to do
            }
            else
            {
                if (e != null)
                {
                    Assert.fail(describeScenarioFailure("Expected no authorization exception but got one: " + e.Message));
                }
                else
                {
                    Assert.fail(describeScenarioFailure("Expected failure due to missing authorizations but code under test was successful"));
                }
            }
        }
Exemple #24
0
 private void ReceivedTokenResponse(TokenResponse tokenResponse, AuthorizationException authException)
 {
     try
     {
         _authState.Update(tokenResponse, authException);
     }
     catch (Exception) { }
     finally
     {
         SetWaitHandle();
     }
 }
Exemple #25
0
        public static Neo4jException ParseServerException(string code, string message)
        {
            Neo4jException error;
            var            parts          = code.Split('.');
            var            classification = parts[1].ToLowerInvariant();

            switch (classification)
            {
            case "clienterror":
                if (AuthenticationException.IsAuthenticationError(code))
                {
                    error = new AuthenticationException(message);
                }
                else if (AuthorizationException.IsAuthorizationError(code))
                {
                    error = new AuthorizationException(message);
                }
                else if (ProtocolException.IsProtocolError(code))
                {
                    error = new ProtocolException(code, message);
                }
                else if (FatalDiscoveryException.IsFatalDiscoveryError(code))
                {
                    error = new FatalDiscoveryException(message);
                }
                else if (TokenExpiredException.IsTokenExpiredError(code))
                {
                    error = new TokenExpiredException(message);
                }
                else if (InvalidBookmarkException.IsInvalidBookmarkException(code))
                {
                    error = new InvalidBookmarkException(message);
                }
                else
                {
                    error = new ClientException(code, message);
                }

                break;

            case "transienterror":
                error = new TransientException(code, message);
                break;

            default:
                error = new DatabaseException(code, message);
                break;
            }

            return(error);
        }
     public async Task OnExceptionAsync(ExceptionContext context)
     {
         context.Result = context.Exception switch
         {
             ValidationException ex => new BadRequestObjectResult(ex.Message),
             NoFoundException ex => new NotFoundObjectResult(ex.Message),
             AuthorizationException ex => new ObjectResult(ex.Message)
             {
                 StatusCode = StatusCodes.Status403Forbidden
             },
             _ => new BadRequestObjectResult(context.Exception.Message)
         };
     }
 }
Exemple #27
0
        public IActionResult HandleException(ActionContext context, Exception exception)
        {
            try
            {
                var errorInfo = errorInfoBuilder.BuildInfo(exception);

                if (ActionResultHelper.IsObjectResult(context.ActionDescriptor.GetMethodInfo().ReturnType))
                {
                    return(exception switch
                    {
                        AuthorizationException _ => CreateFromAuthorizationException(context, errorInfo),
                        ValidationException _ => CreateFromValidationException(errorInfo),
                        _ => CreateFromGenericException(errorInfo),
                    });
                }
 private void ReceivedTokenResponse(TokenResponse tokenResponse, AuthorizationException authException)
 {
     try
     {
         _authState.Update(tokenResponse, authException);
     }
     catch (Exception ex)
     {
         Console.WriteLine($"Exception: {ex.Message}");
     }
     finally
     {
         _loginResultWaitHandle.Set();
     }
 }
Exemple #29
0
        // transformer /////////////////////////////

        public static AuthorizationExceptionDto fromException(AuthorizationException e)
        {
            AuthorizationExceptionDto dto = new AuthorizationExceptionDto();

            dto.Message = e.Message;
            dto.Type    = typeof(AuthorizationException).Name;

            dto.UserId = e.UserId;
            dto.MissingAuthorizations = MissingAuthorizationDto.fromInfo(e.MissingAuthorizations);
            dto.PermissionName        = e.ViolatedPermissionName;
            dto.ResourceId            = e.ResourceId;
            dto.ResourceName          = e.ResourceType;

            return(dto);
        }
Exemple #30
0
        public static void AuthorizeQuery(string query, int idUsuario, int tipo_permiso)
        {
            bool sinPermisos = false;
            // hasta que no se carguen todas las grillas tiene el try/catch
            var         keyArray = new KeyArray();
            QRYIdAccion?idAccion = null;

            try
            {
                idAccion = (QRYIdAccion)Enum.Parse(typeof(QRYIdAccion), query.ToUpper());
            }
            catch
            {
                sinPermisos = true;
            }

            if (!sinPermisos)
            {
                var tpAuth = CachingManager.Instance.GetAutorizacion(idUsuario, (short)idAccion.Value.GetHashCode(), (TipoPermiso)tipo_permiso).tipoAutorizacion;

                if (tpAuth == TipoAutorizacion.CON_PERMISOS || tpAuth == TipoAutorizacion.CON_DOBLE_CONTROL)
                {
                    return;
                }

                keyArray.Codigo = CodigosMensajes.FE_ERROR_FALTA_PERMISOS;
                AccionEntity accion = CachingManager.Instance.GetAccionById((short)idAccion.Value);

                if (accion != null)
                {
                    keyArray.Parametros.Add(accion.Descripcion);
                }
                else
                {
                    keyArray.Parametros.Add(string.Format("Acción {0} no encontrada", idAccion.Value));
                }
            }
            else
            {
                keyArray.Parametros.Add(string.Format("No se encontró el QueryName {0}", query));
            }
            keyArray.Codigo = CodigosMensajes.FE_ERROR_FALTA_PERMISOS;

            var fe = new AuthorizationException(001);

            fe.DataValidations.Add(keyArray);
            throw fe;
        }
            protected ObjectResult GenerateAuthExceptionResult(AuthorizationException exception)
            {
                var result = new ObjectResult(null)
                {
                    StatusCode = ExtractStatusCode(exception),
                    Value      = new
                    {
                        exception.Login,
                        exception.RequestPath,
                        exception.StringArguments,
                        exception.Status
                    }
                };

                return(GenerateExceptionResult(result));
            }
Exemple #32
0
 private void ReceivedTokenResponse(TokenResponse tokenResponse, AuthorizationException authException)
 {
     try
     {
         Console.WriteLine("Token request complete");
         _authState.Update(tokenResponse, authException);
     }
     catch (Exception ex)
     {
         Console.WriteLine($"Exception: {ex.Message}");
     }
     finally
     {
         //We need this line to tell the Login method to return the result
         _loginResultWaitHandle.Set();
     }
 }
Exemple #33
0
 public void Read (TProtocol iprot)
 {
   TField field;
   iprot.ReadStructBegin();
   while (true)
   {
     field = iprot.ReadFieldBegin();
     if (field.Type == TType.Stop) { 
       break;
     }
     switch (field.ID)
     {
       case 1:
         if (field.Type == TType.Struct) {
           E = new NotAliveException();
           E.Read(iprot);
         } else { 
           TProtocolUtil.Skip(iprot, field.Type);
         }
         break;
       case 2:
         if (field.Type == TType.Struct) {
           Ite = new InvalidTopologyException();
           Ite.Read(iprot);
         } else { 
           TProtocolUtil.Skip(iprot, field.Type);
         }
         break;
       case 3:
         if (field.Type == TType.Struct) {
           Aze = new AuthorizationException();
           Aze.Read(iprot);
         } else { 
           TProtocolUtil.Skip(iprot, field.Type);
         }
         break;
       default: 
         TProtocolUtil.Skip(iprot, field.Type);
         break;
     }
     iprot.ReadFieldEnd();
   }
   iprot.ReadStructEnd();
 }
 public void Read (TProtocol iprot)
 {
   TField field;
   iprot.ReadStructBegin();
   while (true)
   {
     field = iprot.ReadFieldBegin();
     if (field.Type == TType.Stop) { 
       break;
     }
     switch (field.ID)
     {
       case 0:
         if (field.Type == TType.String) {
           Success = iprot.ReadString();
         } else { 
           TProtocolUtil.Skip(iprot, field.Type);
         }
         break;
       case 1:
         if (field.Type == TType.Struct) {
           E = new DRPCExecutionException();
           E.Read(iprot);
         } else { 
           TProtocolUtil.Skip(iprot, field.Type);
         }
         break;
       case 2:
         if (field.Type == TType.Struct) {
           Aze = new AuthorizationException();
           Aze.Read(iprot);
         } else { 
           TProtocolUtil.Skip(iprot, field.Type);
         }
         break;
       default: 
         TProtocolUtil.Skip(iprot, field.Type);
         break;
     }
     iprot.ReadFieldEnd();
   }
   iprot.ReadStructEnd();
 }