Web Api Interceptor










0















I have created a custom authorize attribute on my web api. My goal is to check if the user has permission to access the web api url directly else redirect him to an unauthorized page.This process requires me to add [CustomAuthorize("modulename")] everywhere.Is there any other way I can do this? Probably by interceptors?.Any guidance would be greatly appreciated.



 Customised authorize attribute pseudo code snippet: 

public override void OnAuthorization(HttpActionContext context)
var username = HttpContext.Current.Request.LogonUserIdentity.Name;
var accesiblemodulelistforuser = GetPermissions(username );

if (user != null)

if (modulename does not exist in list )

var response =
context.Request.CreateResponse(HttpStatusCode.Forbidden);
context.Response = response;


else
return;




else
//redirect to unauthorized page











share|improve this question


























    0















    I have created a custom authorize attribute on my web api. My goal is to check if the user has permission to access the web api url directly else redirect him to an unauthorized page.This process requires me to add [CustomAuthorize("modulename")] everywhere.Is there any other way I can do this? Probably by interceptors?.Any guidance would be greatly appreciated.



     Customised authorize attribute pseudo code snippet: 

    public override void OnAuthorization(HttpActionContext context)
    var username = HttpContext.Current.Request.LogonUserIdentity.Name;
    var accesiblemodulelistforuser = GetPermissions(username );

    if (user != null)

    if (modulename does not exist in list )

    var response =
    context.Request.CreateResponse(HttpStatusCode.Forbidden);
    context.Response = response;


    else
    return;




    else
    //redirect to unauthorized page











    share|improve this question
























      0












      0








      0








      I have created a custom authorize attribute on my web api. My goal is to check if the user has permission to access the web api url directly else redirect him to an unauthorized page.This process requires me to add [CustomAuthorize("modulename")] everywhere.Is there any other way I can do this? Probably by interceptors?.Any guidance would be greatly appreciated.



       Customised authorize attribute pseudo code snippet: 

      public override void OnAuthorization(HttpActionContext context)
      var username = HttpContext.Current.Request.LogonUserIdentity.Name;
      var accesiblemodulelistforuser = GetPermissions(username );

      if (user != null)

      if (modulename does not exist in list )

      var response =
      context.Request.CreateResponse(HttpStatusCode.Forbidden);
      context.Response = response;


      else
      return;




      else
      //redirect to unauthorized page











      share|improve this question














      I have created a custom authorize attribute on my web api. My goal is to check if the user has permission to access the web api url directly else redirect him to an unauthorized page.This process requires me to add [CustomAuthorize("modulename")] everywhere.Is there any other way I can do this? Probably by interceptors?.Any guidance would be greatly appreciated.



       Customised authorize attribute pseudo code snippet: 

      public override void OnAuthorization(HttpActionContext context)
      var username = HttpContext.Current.Request.LogonUserIdentity.Name;
      var accesiblemodulelistforuser = GetPermissions(username );

      if (user != null)

      if (modulename does not exist in list )

      var response =
      context.Request.CreateResponse(HttpStatusCode.Forbidden);
      context.Response = response;


      else
      return;




      else
      //redirect to unauthorized page








      c# .net asp.net-web-api interceptor






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 16 '18 at 5:54









      RiddlerRiddler

      33




      33






















          1 Answer
          1






          active

          oldest

          votes


















          1














          There is no class definition in your's neither ASP.NET version, so I assume that you inherit the ActionFilterAttribute class . Just noticed, that you're not. See edited version. If so, than you can register your filter globally for all web api actions and controllers in WebApiConfig.cs like this:



          public static void Register(HttpConfiguration config)

          config.Filters.Add(new CustomAuthorize());



          Edit



          Totally misunderstood your's situation. So there is more info.
          You can use your own global authorization filters:



          public class CustomAuthorize : AuthorizeAttribute

          public override void OnAuthorization(AuthorizationContext filterContext)

          if (!filterContext.HttpContext.User.Identity.IsAuthenticated)

          // user not authorized, redirect to login page
          filterContext.Result = new HttpUnauthorizedResult();

          return;


          string roleName = GetModuleName(filterContext);
          var user = filterContext.HttpContext.User;


          // Chaeck user permissions
          if (!user.IsInRole(roleName))

          // Handle not authorized requests and redirect to error page
          filterContext.Result = new RedirectResult("~/Error/NotAuthorized");
          return;


          base.OnAuthorization(filterContext);


          string GetModuleName(AuthorizationContext filterContext)

          var controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerType.FullName;
          var actionName = filterContext.ActionDescriptor.ActionName;

          return controllerName; // or actionName




          Than you can register your filter globally for all actions and controllers in WebApiConfig.cs like this:



          public static void Register(HttpConfiguration config)

          filters.Add(new CustomAuthorize());



          or use only on specific controllers/actions.



          Just be careful, this approach doesnt work for web api, only mvc, as web api has it's own AuthorizeAttribute located in System.Web.Http (MVC version is located in System.Web.Mvc). Implementation is slightly different, but you can just looks for examples. So you will need to have who different attributes - one for MVC and one for WEB API. See original answer to know how to register WEB API filter globally, or use it only for specific controllers.






          share|improve this answer
























            Your Answer






            StackExchange.ifUsing("editor", function ()
            StackExchange.using("externalEditor", function ()
            StackExchange.using("snippets", function ()
            StackExchange.snippets.init();
            );
            );
            , "code-snippets");

            StackExchange.ready(function()
            var channelOptions =
            tags: "".split(" "),
            id: "1"
            ;
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function()
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled)
            StackExchange.using("snippets", function()
            createEditor();
            );

            else
            createEditor();

            );

            function createEditor()
            StackExchange.prepareEditor(
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader:
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            ,
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            );



            );













            draft saved

            draft discarded


















            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53332188%2fweb-api-interceptor%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            1














            There is no class definition in your's neither ASP.NET version, so I assume that you inherit the ActionFilterAttribute class . Just noticed, that you're not. See edited version. If so, than you can register your filter globally for all web api actions and controllers in WebApiConfig.cs like this:



            public static void Register(HttpConfiguration config)

            config.Filters.Add(new CustomAuthorize());



            Edit



            Totally misunderstood your's situation. So there is more info.
            You can use your own global authorization filters:



            public class CustomAuthorize : AuthorizeAttribute

            public override void OnAuthorization(AuthorizationContext filterContext)

            if (!filterContext.HttpContext.User.Identity.IsAuthenticated)

            // user not authorized, redirect to login page
            filterContext.Result = new HttpUnauthorizedResult();

            return;


            string roleName = GetModuleName(filterContext);
            var user = filterContext.HttpContext.User;


            // Chaeck user permissions
            if (!user.IsInRole(roleName))

            // Handle not authorized requests and redirect to error page
            filterContext.Result = new RedirectResult("~/Error/NotAuthorized");
            return;


            base.OnAuthorization(filterContext);


            string GetModuleName(AuthorizationContext filterContext)

            var controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerType.FullName;
            var actionName = filterContext.ActionDescriptor.ActionName;

            return controllerName; // or actionName




            Than you can register your filter globally for all actions and controllers in WebApiConfig.cs like this:



            public static void Register(HttpConfiguration config)

            filters.Add(new CustomAuthorize());



            or use only on specific controllers/actions.



            Just be careful, this approach doesnt work for web api, only mvc, as web api has it's own AuthorizeAttribute located in System.Web.Http (MVC version is located in System.Web.Mvc). Implementation is slightly different, but you can just looks for examples. So you will need to have who different attributes - one for MVC and one for WEB API. See original answer to know how to register WEB API filter globally, or use it only for specific controllers.






            share|improve this answer





























              1














              There is no class definition in your's neither ASP.NET version, so I assume that you inherit the ActionFilterAttribute class . Just noticed, that you're not. See edited version. If so, than you can register your filter globally for all web api actions and controllers in WebApiConfig.cs like this:



              public static void Register(HttpConfiguration config)

              config.Filters.Add(new CustomAuthorize());



              Edit



              Totally misunderstood your's situation. So there is more info.
              You can use your own global authorization filters:



              public class CustomAuthorize : AuthorizeAttribute

              public override void OnAuthorization(AuthorizationContext filterContext)

              if (!filterContext.HttpContext.User.Identity.IsAuthenticated)

              // user not authorized, redirect to login page
              filterContext.Result = new HttpUnauthorizedResult();

              return;


              string roleName = GetModuleName(filterContext);
              var user = filterContext.HttpContext.User;


              // Chaeck user permissions
              if (!user.IsInRole(roleName))

              // Handle not authorized requests and redirect to error page
              filterContext.Result = new RedirectResult("~/Error/NotAuthorized");
              return;


              base.OnAuthorization(filterContext);


              string GetModuleName(AuthorizationContext filterContext)

              var controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerType.FullName;
              var actionName = filterContext.ActionDescriptor.ActionName;

              return controllerName; // or actionName




              Than you can register your filter globally for all actions and controllers in WebApiConfig.cs like this:



              public static void Register(HttpConfiguration config)

              filters.Add(new CustomAuthorize());



              or use only on specific controllers/actions.



              Just be careful, this approach doesnt work for web api, only mvc, as web api has it's own AuthorizeAttribute located in System.Web.Http (MVC version is located in System.Web.Mvc). Implementation is slightly different, but you can just looks for examples. So you will need to have who different attributes - one for MVC and one for WEB API. See original answer to know how to register WEB API filter globally, or use it only for specific controllers.






              share|improve this answer



























                1












                1








                1







                There is no class definition in your's neither ASP.NET version, so I assume that you inherit the ActionFilterAttribute class . Just noticed, that you're not. See edited version. If so, than you can register your filter globally for all web api actions and controllers in WebApiConfig.cs like this:



                public static void Register(HttpConfiguration config)

                config.Filters.Add(new CustomAuthorize());



                Edit



                Totally misunderstood your's situation. So there is more info.
                You can use your own global authorization filters:



                public class CustomAuthorize : AuthorizeAttribute

                public override void OnAuthorization(AuthorizationContext filterContext)

                if (!filterContext.HttpContext.User.Identity.IsAuthenticated)

                // user not authorized, redirect to login page
                filterContext.Result = new HttpUnauthorizedResult();

                return;


                string roleName = GetModuleName(filterContext);
                var user = filterContext.HttpContext.User;


                // Chaeck user permissions
                if (!user.IsInRole(roleName))

                // Handle not authorized requests and redirect to error page
                filterContext.Result = new RedirectResult("~/Error/NotAuthorized");
                return;


                base.OnAuthorization(filterContext);


                string GetModuleName(AuthorizationContext filterContext)

                var controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerType.FullName;
                var actionName = filterContext.ActionDescriptor.ActionName;

                return controllerName; // or actionName




                Than you can register your filter globally for all actions and controllers in WebApiConfig.cs like this:



                public static void Register(HttpConfiguration config)

                filters.Add(new CustomAuthorize());



                or use only on specific controllers/actions.



                Just be careful, this approach doesnt work for web api, only mvc, as web api has it's own AuthorizeAttribute located in System.Web.Http (MVC version is located in System.Web.Mvc). Implementation is slightly different, but you can just looks for examples. So you will need to have who different attributes - one for MVC and one for WEB API. See original answer to know how to register WEB API filter globally, or use it only for specific controllers.






                share|improve this answer















                There is no class definition in your's neither ASP.NET version, so I assume that you inherit the ActionFilterAttribute class . Just noticed, that you're not. See edited version. If so, than you can register your filter globally for all web api actions and controllers in WebApiConfig.cs like this:



                public static void Register(HttpConfiguration config)

                config.Filters.Add(new CustomAuthorize());



                Edit



                Totally misunderstood your's situation. So there is more info.
                You can use your own global authorization filters:



                public class CustomAuthorize : AuthorizeAttribute

                public override void OnAuthorization(AuthorizationContext filterContext)

                if (!filterContext.HttpContext.User.Identity.IsAuthenticated)

                // user not authorized, redirect to login page
                filterContext.Result = new HttpUnauthorizedResult();

                return;


                string roleName = GetModuleName(filterContext);
                var user = filterContext.HttpContext.User;


                // Chaeck user permissions
                if (!user.IsInRole(roleName))

                // Handle not authorized requests and redirect to error page
                filterContext.Result = new RedirectResult("~/Error/NotAuthorized");
                return;


                base.OnAuthorization(filterContext);


                string GetModuleName(AuthorizationContext filterContext)

                var controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerType.FullName;
                var actionName = filterContext.ActionDescriptor.ActionName;

                return controllerName; // or actionName




                Than you can register your filter globally for all actions and controllers in WebApiConfig.cs like this:



                public static void Register(HttpConfiguration config)

                filters.Add(new CustomAuthorize());



                or use only on specific controllers/actions.



                Just be careful, this approach doesnt work for web api, only mvc, as web api has it's own AuthorizeAttribute located in System.Web.Http (MVC version is located in System.Web.Mvc). Implementation is slightly different, but you can just looks for examples. So you will need to have who different attributes - one for MVC and one for WEB API. See original answer to know how to register WEB API filter globally, or use it only for specific controllers.







                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Nov 16 '18 at 8:40

























                answered Nov 16 '18 at 8:02









                IvvanIvvan

                415513




                415513





























                    draft saved

                    draft discarded
















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid


                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.

                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function ()
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53332188%2fweb-api-interceptor%23new-answer', 'question_page');

                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Top Tejano songwriter Luis Silva dead of heart attack at 64

                    ReactJS Fetched API data displays live - need Data displayed static

                    Evgeni Malkin