Shiro redirecting to login page after successful login when added Hazlecast

classic Classic list List threaded Threaded
6 messages Options
Reply | Threaded
Open this post in threaded view
|

Shiro redirecting to login page after successful login when added Hazlecast

trinadhm
Hello,
I was able to successfully login with Shiro and do all the actions associated with that user.

In the below shiro.in, I do not configured below:
# use native session management so we can configure our own session clustering:
sessionDAO = org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO
sessionManager = org.apache.shiro.web.session.mgt.DefaultWebSessionManager
sessionManager.sessionDAO = $sessionDAO
# We have configured Hazelcast to enforce a TTL for the activeSessions Map. No need for Shiro to invalidate!
sessionManager.sessionValidationSchedulerEnabled = false
securityManager.sessionManager = $sessionManager
 
# Configure Hazelcast as our Shiro CacheManager. Adding session capacity is as easy as adding Hazelcast nodes!
cacheManager = org.apache.shiro.hazelcast.cache.HazelcastCacheManager
securityManager.cacheManager = $cacheManager

When I tried to add Shiro Hazlecast, every time user login shiro redirecting back to login page.

JSF + Primefaces + JPA + JBoss 7.1

shiro.ini
------------
[main]
# set custom authenticator
authenticator = gov.ga.sbwc.icms.core.auth.realm.MultiTenantAuthenticator
securityManager.authenticator = $authenticator

# set custom authorizer
authorizer = gov.ga.sbwc.icms.core.auth.realm.MultiTenantAuthorizer
securityManager.authorizer = $authorizer

# Set Authentication Strategy
#authcStrategy = org.apache.shiro.authc.pam.FirstSuccessfulStrategy

# set JPA Realm
jpaRealm = gov.ga.sbwc.icms.core.auth.realm.JpaRealm
jpaRealm.authorizationCachingEnabled = false

# set LDAP Realm
ldapRealm = gov.ga.sbwc.icms.core.auth.realm.LdapRealm
ldapRealm.authorizationCachingEnabled = false

# Set the order in which the Realm are initiated
securityManager.realms = $jpaRealm, $ldapRealm
#securityManager.authenticator.authenticationStrategy = $authcStrategy

# Configure JPA realm password hashing.
passwordService = org.apache.shiro.authc.credential.DefaultPasswordService
passwordMatcher = org.apache.shiro.authc.credential.PasswordMatcher
passwordMatcher.passwordService = $passwordService
jpaRealm.credentialsMatcher = $passwordMatcher

# use native session management so we can configure our own session clustering:
sessionDAO = org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO
sessionManager = org.apache.shiro.web.session.mgt.DefaultWebSessionManager
sessionManager.sessionDAO = $sessionDAO
# We have configured Hazelcast to enforce a TTL for the activeSessions Map. No need for Shiro to invalidate!
sessionManager.sessionValidationSchedulerEnabled = false
securityManager.sessionManager = $sessionManager
 
# Configure Hazelcast as our Shiro CacheManager. Adding session capacity is as easy as adding Hazelcast nodes!
cacheManager = org.apache.shiro.hazelcast.cache.HazelcastCacheManager
securityManager.cacheManager = $cacheManager

user.loginUrl = /pages/public/login/login.xhtml

# roles filter: redirect to error page if user does not have access rights
roles.unauthorizedUrl = /pages/errorpages/accessdenied.xhtml

[urls]
# enable authc filter for all application pages
/pages/public/login/login.xhtml = user
/pages/public/** = anon
/logout = logout
/pages/forms/** = user
/pages/external/** = user
/pages/internal/** = user
/pages/common/** = user

Custom Filter
----------------
public class IcmsFilter implements Filter {
       
        private static final String AJAX_REDIRECT_XML = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
                + "<partial-response><redirect url=\"%s\"></redirect></partial-response>";
       
        private static long maxAge = 86400 * 30;
       
        public void init(FilterConfig config) throws ServletException {
        }

        public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
                HttpServletResponse response = (HttpServletResponse) res;
                HttpServletRequest request = (HttpServletRequest) req;
                String loginURL = request.getContextPath() + "/" + IcmsConstants.LOGIN_PAGE;

                try {
                        HttpSession session = request.getSession(false);
                       
                        String uri = request.getRequestURI();
                boolean loggedIn = session != null && isLoggedIn();
                        boolean loginRequest = request.getRequestURI().equals(loginURL);
                boolean resourceRequest = request.getRequestURI().startsWith(request.getContextPath() + ResourceHandler.RESOURCE_IDENTIFIER + "/");
                boolean ajaxRequest = "partial/ajax".equals(request.getHeader("Faces-Request"));
                boolean recoveryRequest = request.getRequestURI().equals(request.getContextPath() + "/" + IcmsConstants.ID_RECOVERY_PAGE) || request.getRequestURI().equals(request.getContextPath() + "/" + IcmsConstants.PASSWORD_RECOVERY_PAGE);
                boolean registerRequest = request.getRequestURI().equals(request.getContextPath() + "/" + IcmsConstants.TERMS_CONDITIONS_PAGE) || request.getRequestURI().equals(request.getContextPath() + "/" + IcmsConstants.REGISTER_PAGE);
                boolean captchaRequest = request.getRequestURI().equals(request.getContextPath() + "/" + IcmsConstants.SIMPLE_CAPTCHA_PAGE);

                        if (loggedIn || loginRequest || resourceRequest || recoveryRequest || registerRequest || captchaRequest) {
                                if (!resourceRequest) { // Prevent browser from caching restricted resources. See also http://stackoverflow.com/q/4194207/157882
                        response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.
                        response.setHeader("Pragma", "no-cache"); // HTTP 1.0.
                        response.setDateHeader("Expires", 0); // Proxies.
                    } else if (uri.contains(".js") || uri.contains(".css") || uri.contains(".svg") || uri.contains(".gif")
                                || uri.contains(".woff") || uri.contains(".png")) {
                    response.setHeader("Cache-Control", "max-age=" + maxAge);
                    }
                                chain.doFilter(request, response);
                        } else if (ajaxRequest) {
                    response.setContentType("text/xml");
                    response.setCharacterEncoding("UTF-8");
                    response.getWriter().printf(AJAX_REDIRECT_XML, loginURL); // So, return special XML response instructing JSF ajax to send a redirect.
                } else {
                response.sendRedirect(loginURL);
                        }
                } catch (FileNotFoundException e) {
                        response.sendError(HttpServletResponse.SC_NOT_FOUND, request.getRequestURI());
                } catch (ServletException e) {
                        response.sendRedirect(loginURL);
                } catch (Exception e) {
                        response.sendRedirect(loginURL);
                }
        }

        public void destroy() {

        }

        public boolean isLoggedIn() {
                try {
                        Subject currentUser = SecurityUtils.getSubject();
                        if (currentUser != null && currentUser.isAuthenticated()) {
                                return true;
                        }
                        return false;

                } catch (Exception ex) {
                        return false;
                }
        }
}
Reply | Threaded
Open this post in threaded view
|

Re: Shiro redirecting to login page after successful login when added Hazlecast

Brian Demers
If you haven't already seen this take a look at this blog/example:

If I had to guess I would say your cache is out of sync between nodes?

On Wed, Jun 7, 2017 at 12:27 PM, trinadhm <[hidden email]> wrote:
Hello,
I was able to successfully login with Shiro and do all the actions
associated with that user.

In the below shiro.in, I do not configured below:
# use native session management so we can configure our own session
clustering:
sessionDAO = org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO
sessionManager = org.apache.shiro.web.session.mgt.DefaultWebSessionManager
sessionManager.sessionDAO = $sessionDAO
# We have configured Hazelcast to enforce a TTL for the activeSessions Map.
No need for Shiro to invalidate!
sessionManager.sessionValidationSchedulerEnabled = false
securityManager.sessionManager = $sessionManager

# Configure Hazelcast as our Shiro CacheManager. Adding session capacity is
as easy as adding Hazelcast nodes!
cacheManager = org.apache.shiro.hazelcast.cache.HazelcastCacheManager
securityManager.cacheManager = $cacheManager

When I tried to add Shiro Hazlecast, every time user login shiro redirecting
back to login page.

JSF + Primefaces + JPA + JBoss 7.1

shiro.ini
------------
[main]
# set custom authenticator
authenticator = gov.ga.sbwc.icms.core.auth.realm.MultiTenantAuthenticator
securityManager.authenticator = $authenticator

# set custom authorizer
authorizer = gov.ga.sbwc.icms.core.auth.realm.MultiTenantAuthorizer
securityManager.authorizer = $authorizer

# Set Authentication Strategy
#authcStrategy = org.apache.shiro.authc.pam.FirstSuccessfulStrategy

# set JPA Realm
jpaRealm = gov.ga.sbwc.icms.core.auth.realm.JpaRealm
jpaRealm.authorizationCachingEnabled = false

# set LDAP Realm
ldapRealm = gov.ga.sbwc.icms.core.auth.realm.LdapRealm
ldapRealm.authorizationCachingEnabled = false

# Set the order in which the Realm are initiated
securityManager.realms = $jpaRealm, $ldapRealm
#securityManager.authenticator.authenticationStrategy = $authcStrategy

# Configure JPA realm password hashing.
passwordService = org.apache.shiro.authc.credential.DefaultPasswordService
passwordMatcher = org.apache.shiro.authc.credential.PasswordMatcher
passwordMatcher.passwordService = $passwordService
jpaRealm.credentialsMatcher = $passwordMatcher

# use native session management so we can configure our own session
clustering:
sessionDAO = org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO
sessionManager = org.apache.shiro.web.session.mgt.DefaultWebSessionManager
sessionManager.sessionDAO = $sessionDAO
# We have configured Hazelcast to enforce a TTL for the activeSessions Map.
No need for Shiro to invalidate!
sessionManager.sessionValidationSchedulerEnabled = false
securityManager.sessionManager = $sessionManager

# Configure Hazelcast as our Shiro CacheManager. Adding session capacity is
as easy as adding Hazelcast nodes!
cacheManager = org.apache.shiro.hazelcast.cache.HazelcastCacheManager
securityManager.cacheManager = $cacheManager

user.loginUrl = /pages/public/login/login.xhtml

# roles filter: redirect to error page if user does not have access rights
roles.unauthorizedUrl = /pages/errorpages/accessdenied.xhtml

[urls]
# enable authc filter for all application pages
/pages/public/login/login.xhtml = user
/pages/public/** = anon
/logout = logout
/pages/forms/** = user
/pages/external/** = user
/pages/internal/** = user
/pages/common/** = user

Custom Filter
----------------
public class IcmsFilter implements Filter {

        private static final String AJAX_REDIRECT_XML = "<?xml version=\"1.0\"
encoding=\"UTF-8\"?>"
                + "<partial-response><redirect
url=\"%s\"></redirect></partial-response>";

        private static long maxAge = 86400 * 30;

        public void init(FilterConfig config) throws ServletException {
        }

        public void doFilter(ServletRequest req, ServletResponse res, FilterChain
chain) throws IOException, ServletException {
                HttpServletResponse response = (HttpServletResponse) res;
                HttpServletRequest request = (HttpServletRequest) req;
                String loginURL = request.getContextPath() + "/" +
IcmsConstants.LOGIN_PAGE;

                try {
                        HttpSession session = request.getSession(false);

                        String uri = request.getRequestURI();
                boolean loggedIn = session != null && isLoggedIn();
                        boolean loginRequest = request.getRequestURI().equals(loginURL);
                boolean resourceRequest =
request.getRequestURI().startsWith(request.getContextPath() +
ResourceHandler.RESOURCE_IDENTIFIER + "/");
                boolean ajaxRequest =
"partial/ajax".equals(request.getHeader("Faces-Request"));
                boolean recoveryRequest =
request.getRequestURI().equals(request.getContextPath() + "/" +
IcmsConstants.ID_RECOVERY_PAGE) ||
request.getRequestURI().equals(request.getContextPath() + "/" +
IcmsConstants.PASSWORD_RECOVERY_PAGE);
                boolean registerRequest =
request.getRequestURI().equals(request.getContextPath() + "/" +
IcmsConstants.TERMS_CONDITIONS_PAGE) ||
request.getRequestURI().equals(request.getContextPath() + "/" +
IcmsConstants.REGISTER_PAGE);
                boolean captchaRequest =
request.getRequestURI().equals(request.getContextPath() + "/" +
IcmsConstants.SIMPLE_CAPTCHA_PAGE);

                        if (loggedIn || loginRequest || resourceRequest || recoveryRequest ||
registerRequest || captchaRequest) {
                                if (!resourceRequest) { // Prevent browser from caching restricted
resources. See also http://stackoverflow.com/q/4194207/157882
                        response.setHeader("Cache-Control", "no-cache, no-store,
must-revalidate"); // HTTP 1.1.
                        response.setHeader("Pragma", "no-cache"); // HTTP 1.0.
                        response.setDateHeader("Expires", 0); // Proxies.
                    } else if (uri.contains(".js") || uri.contains(".css") ||
uri.contains(".svg") || uri.contains(".gif")
                                || uri.contains(".woff") || uri.contains(".png")) {
                        response.setHeader("Cache-Control", "max-age=" + maxAge);
                    }
                                chain.doFilter(request, response);
                        } else if (ajaxRequest) {
                    response.setContentType("text/xml");
                    response.setCharacterEncoding("UTF-8");
                    response.getWriter().printf(AJAX_REDIRECT_XML, loginURL); //
So, return special XML response instructing JSF ajax to send a redirect.
                } else {
                        response.sendRedirect(loginURL);
                        }
                } catch (FileNotFoundException e) {
                        response.sendError(HttpServletResponse.SC_NOT_FOUND,
request.getRequestURI());
                } catch (ServletException e) {
                        response.sendRedirect(loginURL);
                } catch (Exception e) {
                        response.sendRedirect(loginURL);
                }
        }

        public void destroy() {

        }

        public boolean isLoggedIn() {
                try {
                        Subject currentUser = SecurityUtils.getSubject();
                        if (currentUser != null && currentUser.isAuthenticated()) {
                                return true;
                        }
                        return false;

                } catch (Exception ex) {
                        return false;
                }
        }
}



--
View this message in context: http://shiro-user.582556.n2.nabble.com/Shiro-redirecting-to-login-page-after-successful-login-when-added-Hazlecast-tp7581628.html
Sent from the Shiro User mailing list archive at Nabble.com.

Reply | Threaded
Open this post in threaded view
|

Re: Shiro redirecting to login page after successful login when added Hazlecast

trinadhm
Hi Brain,

Followed the same blog attached to add Shiro-Hazelcast to the existing application to cluster web session, then I am facing this issue of redirecting to login page even after user successfully logged in using credentials. When I debugged the subject pulled as SecurityUtils.getSubject(); always returning false for subject.isAuthenticated().

I previous post I copied shiro.ini and CustomFilter for my frontend.
Reply | Threaded
Open this post in threaded view
|

Re: Shiro redirecting to login page after successful login when added Hazlecast

Brian Demers
Does your setup work for a single application node?

On Thu, Jun 8, 2017 at 11:22 AM, trinadhm <[hidden email]> wrote:
Hi Brain,

Followed the same blog attached to add Shiro-Hazelcast to the existing
application to cluster web session, then I am facing this issue of
redirecting to login page even after user successfully logged in using
credentials. When I debugged the subject pulled as
SecurityUtils.getSubject(); always returning false for
subject.isAuthenticated().

I previous post I copied shiro.ini and CustomFilter for my frontend.



--
View this message in context: http://shiro-user.582556.n2.nabble.com/Shiro-redirecting-to-login-page-after-successful-login-when-added-Hazlecast-tp7581628p7581632.html
Sent from the Shiro User mailing list archive at Nabble.com.

Reply | Threaded
Open this post in threaded view
|

Re: Shiro redirecting to login page after successful login when added Hazlecast

trinadhm
Currently I am trying on single node. Once it is success, I will deploy on another node.
Reply | Threaded
Open this post in threaded view
|

Re: Shiro redirecting to login page after successful login when added Hazlecast

trinadhm
In reply to this post by Brian Demers
Hi Brain,

I am able to successfully login after changing map name from "default" to "shiro-activeSessionCache". After login, when I try to click on any of the actions, taking me back to login page which is caused due to SecurityUtils.getSubject() is always returning false for subject.isAuthenticated()