Devise: how to return 401 Unauthorized without redirect if user is not signed in2019 Community Moderator ElectionRails Devise not detecting user as logged inRails: Calling Devise authenticate_user! and handling invalid user/password exceptionRedirect Devise before_filter :authenticate_user to sign in pathDevise not authenticating in Rails 3.2.8 or without account_id fieldDevise logged in but unauthorizedrails devise 401 unauthorized for a specific page401 Unauthorized with rails 4.1.4 and devise 3.2.4Rails / Devise bounces between unauthorized and already-signed-inRails Devise confirmable don't redirect to confirmationsDevise 401 unauthorized only when the application is accessed over https

Is honey really a supersaturated solution? Does heating to un-crystalize redissolve it or melt it?

What can I do if I am asked to learn different programming languages very frequently?

Recruiter wants very extensive technical details about all of my previous work

Have the tides ever turned twice on any open problem?

In the 1924 version of The Thief of Bagdad, no character is named, right?

I got the following comment from a reputed math journal. What does it mean?

What (if any) is the reason to buy in small local stores?

What does Jesus mean regarding "Raca," and "you fool?" - is he contrasting them?

What is the relationship between relativity and the Doppler effect?

Relation between independence and correlation of uniform random variables

Can a wizard cast a spell during their first turn of combat if they initiated combat by releasing a readied spell?

Variable completely messes up echoed string

Print last inputted byte

In Aliens, how many people were on LV-426 before the Marines arrived​?

Knife as defense against stray dogs

Writing in a Christian voice

Four married couples attend a party. Each person shakes hands with every other person, except their own spouse, exactly once. How many handshakes?

Generic TVP tradeoffs?

Suggestions on how to spend Shaabath (constructively) alone

Does the attack bonus from a Masterwork weapon stack with the attack bonus from Masterwork ammunition?

What does Deadpool mean by "left the house in that shirt"?

Worshiping one God at a time?

A Ri-diddley-iley Riddle

Existence of a celestial body big enough for early civilization to be thought of as a second moon



Devise: how to return 401 Unauthorized without redirect if user is not signed in



2019 Community Moderator ElectionRails Devise not detecting user as logged inRails: Calling Devise authenticate_user! and handling invalid user/password exceptionRedirect Devise before_filter :authenticate_user to sign in pathDevise not authenticating in Rails 3.2.8 or without account_id fieldDevise logged in but unauthorizedrails devise 401 unauthorized for a specific page401 Unauthorized with rails 4.1.4 and devise 3.2.4Rails / Devise bounces between unauthorized and already-signed-inRails Devise confirmable don't redirect to confirmationsDevise 401 unauthorized only when the application is accessed over https










0















Rails version: 4.0.13



Devise version: 3.2.0



When a user tries to view a page which they are not authorized to view, my application redirects them to a sign in page.



If the user is not signed in, I want to:




  1. Not redirect the user to a new URL and

  2. Return a '401 Unauthorized' response with an empty body

So far, I tried to override authenticate_user! like so:



class BaseApiController < ActionController::Base
before_filter :authenticate_user!

def authenticate_user!
head :unauthorized
end
end


However, while this does return a '401 Unauthorized', it also redirects to the sign in URL first.










share|improve this question


























    0















    Rails version: 4.0.13



    Devise version: 3.2.0



    When a user tries to view a page which they are not authorized to view, my application redirects them to a sign in page.



    If the user is not signed in, I want to:




    1. Not redirect the user to a new URL and

    2. Return a '401 Unauthorized' response with an empty body

    So far, I tried to override authenticate_user! like so:



    class BaseApiController < ActionController::Base
    before_filter :authenticate_user!

    def authenticate_user!
    head :unauthorized
    end
    end


    However, while this does return a '401 Unauthorized', it also redirects to the sign in URL first.










    share|improve this question
























      0












      0








      0








      Rails version: 4.0.13



      Devise version: 3.2.0



      When a user tries to view a page which they are not authorized to view, my application redirects them to a sign in page.



      If the user is not signed in, I want to:




      1. Not redirect the user to a new URL and

      2. Return a '401 Unauthorized' response with an empty body

      So far, I tried to override authenticate_user! like so:



      class BaseApiController < ActionController::Base
      before_filter :authenticate_user!

      def authenticate_user!
      head :unauthorized
      end
      end


      However, while this does return a '401 Unauthorized', it also redirects to the sign in URL first.










      share|improve this question














      Rails version: 4.0.13



      Devise version: 3.2.0



      When a user tries to view a page which they are not authorized to view, my application redirects them to a sign in page.



      If the user is not signed in, I want to:




      1. Not redirect the user to a new URL and

      2. Return a '401 Unauthorized' response with an empty body

      So far, I tried to override authenticate_user! like so:



      class BaseApiController < ActionController::Base
      before_filter :authenticate_user!

      def authenticate_user!
      head :unauthorized
      end
      end


      However, while this does return a '401 Unauthorized', it also redirects to the sign in URL first.







      ruby-on-rails ruby devise






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Mar 6 at 21:45









      Ceasar BautistaCeasar Bautista

      8,59994362




      8,59994362






















          2 Answers
          2






          active

          oldest

          votes


















          1














          Is this what you're looking for?



          https://github.com/plataformatec/devise/wiki/How-To:-Redirect-to-a-specific-page-when-the-user-can-not-be-authenticated



          This still redirects a user, although you can control where that redirect goes.






          share|improve this answer























          • This looks like it's in the right direction, but is not enough for me to solve my issue. I'm investigating it more closely though.

            – Ceasar Bautista
            Mar 6 at 22:17











          • I'm curious what you're expecting a user to see/experience when they try to access a URL protected by authentication if there's no redirect. Are you working with an API only codebase?

            – vinyl
            Mar 6 at 22:24











          • No, some routes are API routes (begin with /api/v1/) and other routes are a normal Rails app. If a user is not logged in and tries to access an API route, I want them to see a 401 and not be redirected anywhere.

            – Ceasar Bautista
            Mar 6 at 22:28












          • Makes sense. Hope that points you in the right direction!

            – vinyl
            Mar 6 at 22:31


















          0














          Building off @vinyl's answer, the following will return a 401 without redirecting if the user is not signed in:



          # lib/custom_failure.rb
          class CustomFailure < Devise::FailureApp
          def respond
          http_auth
          end
          end

          # config/initializers/devise.rb
          config.warden do |manager|
          manager.failure_app = CustomFailure
          end


          You can customize respond to redirect in some cases and throw 401 cases in others. For my use case, the following was sufficient:



          class CustomFailure < Devise::FailureApp
          def respond
          if request.env['REQUEST_PATH'].start_with?('/api')
          http_auth
          else
          redirect
          end
          end
          end


          I don't understand why overriding authenticate_user! did not work here.






          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%2f55032668%2fdevise-how-to-return-401-unauthorized-without-redirect-if-user-is-not-signed-in%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            1














            Is this what you're looking for?



            https://github.com/plataformatec/devise/wiki/How-To:-Redirect-to-a-specific-page-when-the-user-can-not-be-authenticated



            This still redirects a user, although you can control where that redirect goes.






            share|improve this answer























            • This looks like it's in the right direction, but is not enough for me to solve my issue. I'm investigating it more closely though.

              – Ceasar Bautista
              Mar 6 at 22:17











            • I'm curious what you're expecting a user to see/experience when they try to access a URL protected by authentication if there's no redirect. Are you working with an API only codebase?

              – vinyl
              Mar 6 at 22:24











            • No, some routes are API routes (begin with /api/v1/) and other routes are a normal Rails app. If a user is not logged in and tries to access an API route, I want them to see a 401 and not be redirected anywhere.

              – Ceasar Bautista
              Mar 6 at 22:28












            • Makes sense. Hope that points you in the right direction!

              – vinyl
              Mar 6 at 22:31















            1














            Is this what you're looking for?



            https://github.com/plataformatec/devise/wiki/How-To:-Redirect-to-a-specific-page-when-the-user-can-not-be-authenticated



            This still redirects a user, although you can control where that redirect goes.






            share|improve this answer























            • This looks like it's in the right direction, but is not enough for me to solve my issue. I'm investigating it more closely though.

              – Ceasar Bautista
              Mar 6 at 22:17











            • I'm curious what you're expecting a user to see/experience when they try to access a URL protected by authentication if there's no redirect. Are you working with an API only codebase?

              – vinyl
              Mar 6 at 22:24











            • No, some routes are API routes (begin with /api/v1/) and other routes are a normal Rails app. If a user is not logged in and tries to access an API route, I want them to see a 401 and not be redirected anywhere.

              – Ceasar Bautista
              Mar 6 at 22:28












            • Makes sense. Hope that points you in the right direction!

              – vinyl
              Mar 6 at 22:31













            1












            1








            1







            Is this what you're looking for?



            https://github.com/plataformatec/devise/wiki/How-To:-Redirect-to-a-specific-page-when-the-user-can-not-be-authenticated



            This still redirects a user, although you can control where that redirect goes.






            share|improve this answer













            Is this what you're looking for?



            https://github.com/plataformatec/devise/wiki/How-To:-Redirect-to-a-specific-page-when-the-user-can-not-be-authenticated



            This still redirects a user, although you can control where that redirect goes.







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Mar 6 at 22:06









            vinylvinyl

            36618




            36618












            • This looks like it's in the right direction, but is not enough for me to solve my issue. I'm investigating it more closely though.

              – Ceasar Bautista
              Mar 6 at 22:17











            • I'm curious what you're expecting a user to see/experience when they try to access a URL protected by authentication if there's no redirect. Are you working with an API only codebase?

              – vinyl
              Mar 6 at 22:24











            • No, some routes are API routes (begin with /api/v1/) and other routes are a normal Rails app. If a user is not logged in and tries to access an API route, I want them to see a 401 and not be redirected anywhere.

              – Ceasar Bautista
              Mar 6 at 22:28












            • Makes sense. Hope that points you in the right direction!

              – vinyl
              Mar 6 at 22:31

















            • This looks like it's in the right direction, but is not enough for me to solve my issue. I'm investigating it more closely though.

              – Ceasar Bautista
              Mar 6 at 22:17











            • I'm curious what you're expecting a user to see/experience when they try to access a URL protected by authentication if there's no redirect. Are you working with an API only codebase?

              – vinyl
              Mar 6 at 22:24











            • No, some routes are API routes (begin with /api/v1/) and other routes are a normal Rails app. If a user is not logged in and tries to access an API route, I want them to see a 401 and not be redirected anywhere.

              – Ceasar Bautista
              Mar 6 at 22:28












            • Makes sense. Hope that points you in the right direction!

              – vinyl
              Mar 6 at 22:31
















            This looks like it's in the right direction, but is not enough for me to solve my issue. I'm investigating it more closely though.

            – Ceasar Bautista
            Mar 6 at 22:17





            This looks like it's in the right direction, but is not enough for me to solve my issue. I'm investigating it more closely though.

            – Ceasar Bautista
            Mar 6 at 22:17













            I'm curious what you're expecting a user to see/experience when they try to access a URL protected by authentication if there's no redirect. Are you working with an API only codebase?

            – vinyl
            Mar 6 at 22:24





            I'm curious what you're expecting a user to see/experience when they try to access a URL protected by authentication if there's no redirect. Are you working with an API only codebase?

            – vinyl
            Mar 6 at 22:24













            No, some routes are API routes (begin with /api/v1/) and other routes are a normal Rails app. If a user is not logged in and tries to access an API route, I want them to see a 401 and not be redirected anywhere.

            – Ceasar Bautista
            Mar 6 at 22:28






            No, some routes are API routes (begin with /api/v1/) and other routes are a normal Rails app. If a user is not logged in and tries to access an API route, I want them to see a 401 and not be redirected anywhere.

            – Ceasar Bautista
            Mar 6 at 22:28














            Makes sense. Hope that points you in the right direction!

            – vinyl
            Mar 6 at 22:31





            Makes sense. Hope that points you in the right direction!

            – vinyl
            Mar 6 at 22:31













            0














            Building off @vinyl's answer, the following will return a 401 without redirecting if the user is not signed in:



            # lib/custom_failure.rb
            class CustomFailure < Devise::FailureApp
            def respond
            http_auth
            end
            end

            # config/initializers/devise.rb
            config.warden do |manager|
            manager.failure_app = CustomFailure
            end


            You can customize respond to redirect in some cases and throw 401 cases in others. For my use case, the following was sufficient:



            class CustomFailure < Devise::FailureApp
            def respond
            if request.env['REQUEST_PATH'].start_with?('/api')
            http_auth
            else
            redirect
            end
            end
            end


            I don't understand why overriding authenticate_user! did not work here.






            share|improve this answer



























              0














              Building off @vinyl's answer, the following will return a 401 without redirecting if the user is not signed in:



              # lib/custom_failure.rb
              class CustomFailure < Devise::FailureApp
              def respond
              http_auth
              end
              end

              # config/initializers/devise.rb
              config.warden do |manager|
              manager.failure_app = CustomFailure
              end


              You can customize respond to redirect in some cases and throw 401 cases in others. For my use case, the following was sufficient:



              class CustomFailure < Devise::FailureApp
              def respond
              if request.env['REQUEST_PATH'].start_with?('/api')
              http_auth
              else
              redirect
              end
              end
              end


              I don't understand why overriding authenticate_user! did not work here.






              share|improve this answer

























                0












                0








                0







                Building off @vinyl's answer, the following will return a 401 without redirecting if the user is not signed in:



                # lib/custom_failure.rb
                class CustomFailure < Devise::FailureApp
                def respond
                http_auth
                end
                end

                # config/initializers/devise.rb
                config.warden do |manager|
                manager.failure_app = CustomFailure
                end


                You can customize respond to redirect in some cases and throw 401 cases in others. For my use case, the following was sufficient:



                class CustomFailure < Devise::FailureApp
                def respond
                if request.env['REQUEST_PATH'].start_with?('/api')
                http_auth
                else
                redirect
                end
                end
                end


                I don't understand why overriding authenticate_user! did not work here.






                share|improve this answer













                Building off @vinyl's answer, the following will return a 401 without redirecting if the user is not signed in:



                # lib/custom_failure.rb
                class CustomFailure < Devise::FailureApp
                def respond
                http_auth
                end
                end

                # config/initializers/devise.rb
                config.warden do |manager|
                manager.failure_app = CustomFailure
                end


                You can customize respond to redirect in some cases and throw 401 cases in others. For my use case, the following was sufficient:



                class CustomFailure < Devise::FailureApp
                def respond
                if request.env['REQUEST_PATH'].start_with?('/api')
                http_auth
                else
                redirect
                end
                end
                end


                I don't understand why overriding authenticate_user! did not work here.







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Mar 6 at 22:44









                Ceasar BautistaCeasar Bautista

                8,59994362




                8,59994362



























                    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%2f55032668%2fdevise-how-to-return-401-unauthorized-without-redirect-if-user-is-not-signed-in%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

                    AWS Lex not identifying response if by a variable The 2019 Stack Overflow Developer Survey Results Are In Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern) The Ask Question Wizard is Live! Data science time! April 2019 and salary with experienceEnforcing custom enumeration in AWS LEX for slot valuesHow to give response based on user response in Amazon Lex?Intercepting AWS Lambda Response to a AWS Lex QueryLex chat bot error: Reached second execution of fulfillment lambda on the same utteranceamazon lex showing invalid responseLambda response send back to Lex slot?Response card in Amazon lexAmazon Lex - Lambda response return HTML to botHow can I solve 424 (Failed Dependency) (python) obtained from Amazon lex?

                    Алба-Юлія

                    Захаров Федір Захарович