Rectangle 27 86

  • Create a custom_failure.rb in your lib directory, with: class CustomFailure < Devise::FailureApp def redirect_url your_path end def respond if http_auth? http_auth else redirect end end end
config.warden do |manager|
    manager.failure_app = CustomFailure
  end

Make sure Rails is loadin your lib files, in your application.rb :

config.autoload_paths += %W(#{config.root}/lib)

This didn't work. I know it's the stock answer from the devise wiki.

This worked for me using Devise 3.2.4. Make sure when you include or change any of these files that you restart the server. You'll probably get an error like this: NameError - undefined local variable or method 'login' for #<CustomFailure:0x007ffc4aeb9328>if you don't.

ruby on rails - Devise redirect after login fail - Stack Overflow

ruby-on-rails redirect login devise
Rectangle 27 1

I think you can try like this Just save whatever path you want to redirect user after sign_out based on the role after login in session and use that session in after_sign_out_path_for method

after_filter :store_location

def store_location
  return unless session[:login_url].blank? 
  session[:login_url] = current_user.admin? ? admin_path : other_user_path
end

def after_sign_out_path_for(resource) 
  session[:login_url] || request.referer || root_path
end

there are one other way just overwrite devise sessoin controller and redirect user from there based on role

# routes.rb
devise_for :users, :controllers => { :sessions => "sessions" } # etc

# sessions_controller.rb
class SessionsController < Devise::SessionsController

  def destroy
    #login_path = set path in a variable based on user role before sing_out
    #code to sign out 
    #
   redirect_to login_path
  end

end

thanks man, but I tried this type of solution, it seems them devise signout cleared all sessions

@shadow solution works for you, I have not tested my solution just added code based on the knowledge, Yes you are right device remove all session on signout

No, Shadow solution is also not working because at that time I just have a symbol of user in form of resource_or_scope instead of user's object. So can't check role

Admin have access of those pages those are not accessible by other user ?

ruby - Conditional Route on sign_out using Devise with Rails - Stack O...

ruby-on-rails ruby ruby-on-rails-3 devise
Rectangle 27 11

SessionsController
:recall
auth_options
controller#method
warden.authenticate!(auth_options)

in app/controllers/users/sessions_controller.rb

class Users::SessionsController < Devise::SessionsController
  #...
  def create
    #...
    auth_options = { :recall => 'site#index', :scope => :user }
    resource = warden.authenticate!(auth_options)
    #...
  end
  #...
end

With this way, you don't need to create the customized FailureApp and modify the configs.

ruby on rails - Devise redirect after login fail - Stack Overflow

ruby-on-rails redirect login devise
Rectangle 27 1

http://localhost:3000/users/sign_in.json

If we look at the given gist https://gist.github.com/afiq90/2d3f02878cf9c23a03b1 It will take html format and as a response, it will redirect you to root page.

ruby - How To Prevent Redirect After Succesfully Login With CURL in ra...

ruby-on-rails ruby curl
Rectangle 27 2

Started POST "/users/sign_in"
Processing by Devise::SessionsController#create
Completed 401 Unauthorized
Processing by Devise::SessionsController#new

new gets called because of the auth_options defined at the end of gems/devise-3.1.0/app/controllers/devise/sessions_controller.rb

You should redefine the auth_options used in the create action. I copied the controller in app/controllers/devise/sessions_controller.rb of my Rails application and replaced the auth_options method like this

def auth_options
  { :scope => resource_name, :recall => "Home#new" }
end

It does the trick, but the url is still /users/sign_in

I'll try to fix that as well.

I'm on devise 3.2.2 now. The solution of Marcao works perfectly. No need to copy and patch devise controllers or set auth_options.

ruby on rails - Devise redirect after login fail - Stack Overflow

ruby-on-rails redirect login devise
Rectangle 27 1

You can change the default sign_in path.

Thanks @MikeH, I tried this. devise_for :users do get 'users', :to => 'site#index', :as => :user_root # Rails 3 end Works perfect redirecting to my index for all cases, except when a login fails. In this case it redirect to user/sign_in, and I want to be redirected to "site#index".

Hmm. When the login fails, devise's failure app redirects to new_#{scope}_session_path (new_user_session_path in your case). When you do rake routes, what controller/action is shown for this resource path?

ruby on rails - Devise redirect after login fail - Stack Overflow

ruby-on-rails redirect login devise
Rectangle 27 1

For what I've understood you must implement some mechanism to redirect to the login page after any ajax request with an expired session.

I would start to have a respond_to version for JSON and let the client know the session is expired.

respond_to do |format|
  format.html {
    redirect_to 'users/login'
  }
  format.json {
    render json: {error: 'session_expired'}
  }
end

At the client side you must intercept those errors. One easy way to do that would be to use http://api.jquery.com/ajaxComplete (assuming here that you are using jQuery).

$( document ).ajaxComplete(function( event, xhr, settings ) {
  if(settings.dataType == "json") {
    var data = $.parseJSON(xhr.responseText);
    if(data && data.error && data.error == 'session_expired') {
      window.location.reload();
    }
  }
});

javascript - How reload or refresh page when session has expired with ...

javascript ruby-on-rails ruby ruby-on-rails-3 session
Rectangle 27 19

in application_controller.rb

def after_sign_in_path_for(resource_or_scope)
   if request.env['omniauth.origin']
      request.env['omniauth.origin']
    end
end

Rails 3 - Devise With OmniAuth - Redirect after signing in goes to /us...

ruby-on-rails redirect login devise omniauth
Rectangle 27 4

first of all I completely removed the interceptor I was using before. then I made a function inside my Routing .config to use with every resolve for the authentication. finally to handle my resolve I'm using $stateChangeError to redirect to the login state

.config(function ($stateProvider, $urlRouterProvider) {

    // function to check the authentication //
    var Auth = ["$q", "authService", function ($q, authService) {
        authService.fillAuthData;
        if (authService.authentication.isAuth) {
            return $q.when(authService.authentication);
        } else {
            return $q.reject({ authenticated: false });
        }
    }];

    /* if the state does not exist */
    $urlRouterProvider
        .otherwise('/page-not-found'); 

    $stateProvider

        // state that allows non authenticated users //
        .state('home', {
            url: '/',
            templateUrl: '/Content/partials/home.html',
        })

        // state that needs authentication //
        .state('smo-dashboard', {
            url: '/dashboard',
            templateUrl: '/Content/partials/dashboard.html',
            resolve: {
                auth: Auth
            }
        })

        // errors //
         .state('page-not-found', {
             url: '/page-not-found',
             templateUrl: '/Content/partials/error/404.html'
         })

        // accounts //
        .state('login', {
            url: '/accounts/login',
            templateUrl: '/Content/partials/account/login.html'
        })

        // OTHER STATES //
    }
);

in the MainController

$scope.$on("$stateChangeError", function (event, toState, toParams, fromState, fromParams, error) {
    $state.go("login");
});

authentication - angularjs redirect to login page if not authenticated...

angularjs authentication redirect routing
Rectangle 27 5

Spring Security implements this logic for you in the AbstractAuthenticationProcessingFilter (typically using the concrete implementation of UsernamePasswordAuthenticationFilter) by using the SavedRequestAwareAuthenticationSuccessHandler (which uses the HttpSessionRequestCache under the covers). Since you have written a controller to authenticate (rather than using the built in support) you will need to implement this logic yourself. Rather than implementing all of the logic yourself, you can reuse the same classes Spring Security does.

For example, your LoginController might be updated as follows:

public class LoginController implements Serializable {
    // ... same as before ...
    private RequestCache requestCache = new HttpSessionRequestCache();

    public String loginUsingSpringAuthenticationManager() {
        // ... just as you had been doing ...

        if (authenticationResponseToken.isAuthenticated()) {
            HttpServletRequest request = (HttpServletRequest)         
              FacesContext.getCurrentInstance().getExternalContext().getRequest();
            HttpServletResponse response = (HttpServletResponse)         
              FacesContext.getCurrentInstance().getExternalContext().getResponse();

            SavedRequest savedRequest = requestCache.getRequest(request, response);

            return savedRequest.getRedirectUrl();
        }

        // ... same as you had ...
   }
}
savedRequest.getRedirectUrl
http://localhost:8080/APP/javax.faces.resource/jquery/jquery.js.xhtml?ln=primefaces
<script type="text/javascript" src="/APP/javax.faces.resource/jquery/jquery.js.xhtml?ln=primefaces">

Is there any reason that you need this to be private? Unless you have a reason to secure the javascript (which is probably just a copy of jquery library), it seems as though you should probably make this URL public. Perhaps you meant to configure all resources as public (i.e. <security:intercept-url pattern="/javax.faces.resource/**" access="IS_AUTHENTICATED_ANONYMOUSLY"/>)?

/javax.faces.resource/*
/javax.faces.resource/jquery/jquery.js.xhtml?ln=primefaces
<security:http pattern="/javax.faces.resource/**" security="none"/>
/javax.faces.resource/**

JSF with Spring security - Redirect to specified page after login - St...

spring jsf jsf-2 spring-security
Rectangle 27 1

You set this path with the following code inside your confirmations_controller:

def after_resending_confirmation_instructions_path_for
    login_path # or whatever you want
end
new_session_path(resource_name)

Maybe it depends on the version of devise.

that simple i looked everywhere thanks a lot!

ruby on rails - Devise : How to redirect to login page after user requ...

ruby-on-rails ruby-on-rails-3 redirect devise confirmation
Rectangle 27 3

sign_in_and_redirect(resource_or_scope, *args)
sign_out_and_redirect(resource_or_scope)
session[:return_to]
nil

Rails 3 - Devise With OmniAuth - Redirect after signing in goes to /us...

ruby-on-rails redirect login devise omniauth
Rectangle 27 1

By default if default-target-url is not defined Spring Security tries to redirect to previous url, so you just need to remove default-target-url attribute from form-login tag.

<security:form-login login-page="/login.xhtml" />

If your filter chain has the ExceptionTranslationFilter in it then it should cache HTTP request. So in your custom loginController you could try to get redirect url from this cached request.

RequestCache requestCache = new HttpSessionRequestCache();
SavedRequest savedRequest = requestCache.getRequest(request, response);
String targetUrl = savedRequest.getRedirectUrl();
private @Autowired HttpServletRequest request;
HttpServletRequest curRequest = ((ServletRequestAttributes) 
           RequestContextHolder.currentRequestAttributes()) .getRequest();

Which version of spring-security are you using? Also are you using default filter stack?

I'm using spring security 3.1.1. I'm not sure what is the default filter stack, I am using some <security:intercept-url> patterns to protect the pages and paths.

Problem is, I don't have the "request" and "response" params in my loginController

JSF with Spring security - Redirect to specified page after login - St...

spring jsf jsf-2 spring-security
Rectangle 27 1

Best practice though, would be to add the ReturnUrl to a model, and pass that to the view:

@Html.ActionLink("Log in", "Login", "Account", new { returnUrl = Model.ReturnUrl }, new { id = "loginLink" })

How do I pass info to route values so I can redirect back after I logi...

asp.net-mvc asp.net-mvc-routing html.actionlink routevalues
Rectangle 27 1

/auth/facebook?referrer=/path/to/redirect
env["omniauth.params"]

Rails 3 - Devise With OmniAuth - Redirect after signing in goes to /us...

ruby-on-rails redirect login devise omniauth
Rectangle 27 2

sign_in_and_redirect is going to set the current user in session, and whatever else you want to do on sign in, then redirect to the homepage, or whatever you set as the page after successful login.

Instead, do that yourself here, like this perhaps:

def create
    authentication = Authentication.find_by_provider_and_uid(omniauth['provider'], omniauth['uid'])
    if authentication
      flash[:notice] = "Signed in successfully."
      session[:user_id] = authentication.user.id  
      redirect_to root_url, notice: "Signed in!"
    end
  end

Then, in application controller, something like:

def current_user
    User.find(session[:user_id]) if logged_in?
end

def logged_in?
    !!session[:user_id]
end

hey thanks for the suggestion but that does not sign the user in it just redirects to the homepage

setting the session[:user_id] is what sets the user as logged in.

thanks for the links though im gonna run through them and try a different approach.

omniauth without devise rails cast 236 - Stack Overflow

ruby-on-rails-3 omniauth
Rectangle 27 0

maybe you can catch the route change and when the target is your login page, it could save the old route. After the Login you can redirect to the old route

angular.module('appName')
  .run(['$rootScope','$location', '$routeParams', function($rootScope, $location, $routeParams) {
    $rootScope.$on('$routeChangeSuccess', function(e, next, cur) {
       if (next.path() == 'your/login/path') {
          $rootScope.savedRoute = $location.path());
          $rootScope.savedParams = $routeParams;
       }
    }
  }]);

I'm not sure if path() is the correct function, but i think you can see what i mean

Angularjs how to get URL referer? - Stack Overflow

angularjs
Rectangle 27 0

By default if default-target-url is not defined Spring Security tries to redirect to previous url, so you just need to remove default-target-url attribute from form-login tag.

<security:form-login login-page="/login.xhtml" />

If your filter chain has the ExceptionTranslationFilter in it then it should cache HTTP request. So in your custom loginController you could try to get redirect url from this cached request.

RequestCache requestCache = new HttpSessionRequestCache();
SavedRequest savedRequest = requestCache.getRequest(request, response);
String targetUrl = savedRequest.getRedirectUrl();
private @Autowired HttpServletRequest request;
HttpServletRequest curRequest = ((ServletRequestAttributes) 
           RequestContextHolder.currentRequestAttributes()) .getRequest();

Which version of spring-security are you using? Also are you using default filter stack?

I'm using spring security 3.1.1. I'm not sure what is the default filter stack, I am using some <security:intercept-url> patterns to protect the pages and paths.

Problem is, I don't have the "request" and "response" params in my loginController

JSF with Spring security - Redirect to specified page after login - St...

spring jsf jsf-2 spring-security
Rectangle 27 0

SessionsController
:recall
auth_options
controller#method
warden.authenticate!(auth_options)

in app/controllers/users/sessions_controller.rb

class Users::SessionsController < Devise::SessionsController
  #...
  def create
    #...
    auth_options = { :recall => 'site#index', :scope => :user }
    resource = warden.authenticate!(auth_options)
    #...
  end
  #...
end

With this way, you don't need to create the customized FailureApp and modify the configs.

ruby on rails - Devise redirect after login fail - Stack Overflow

ruby-on-rails redirect login devise
Rectangle 27 0

In your controller, detect if there is already a signed in user on the login page. If there is, redirect to where they should go after the login. This prevents any logged in use from seeing the login page.

This works if the user is already logged in and then manually visit the login page. But if the user logs in and presses back. Then when you press back none of the controller methods get fired at all.

authentication - How to handle additional login after pressing back wi...

ruby-on-rails authentication devise