Example usage for org.springframework.security.web.authentication.session SessionAuthenticationException SessionAuthenticationException

List of usage examples for org.springframework.security.web.authentication.session SessionAuthenticationException SessionAuthenticationException

Introduction

In this page you can find the example usage for org.springframework.security.web.authentication.session SessionAuthenticationException SessionAuthenticationException.

Prototype

public SessionAuthenticationException(String msg) 

Source Link

Usage

From source file:org.messic.server.facade.security.TokenManagementFilter.java

/**
* 
*//*from w  w  w  . j av  a2  s.  c  o  m*/
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
        throws AuthenticationException {

    String token = obtainToken(request, tokenParameter);

    Authentication auth = AuthenticationSessionManager.authenticate(token);
    if (auth != null) {
        setDetails(request, (UsernamePasswordAuthenticationToken) auth);

        return this.getAuthenticationManager().authenticate(auth);
    } else {
        // lets try at the dlna tokens
        auth = AuthenticationSessionManager.authenticateDLNA(token);
        if (auth != null) {
            setDetails(request, (UsernamePasswordAuthenticationToken) auth);
            return auth;
        }
    }

    throw new SessionAuthenticationException("not valid token");

}

From source file:com.rockagen.gnext.service.spring.security.extension.BasicConcurrentSessionControlStrategy.java

/**
 * Allowable sessions exceeded.//w ww  . ja  va2s. co m
 * 
 * @param sessions
 *            the sessions
 * @param allowableSessions
 *            the allowable sessions
 * @param sameIp
 *            the same ip
 * @param registry
 *            the registry
 * @throws SessionAuthenticationException
 *             the session authentication exception
 */
protected void allowableSessionsExceeded(java.util.List<SessionInformation> sessions, int allowableSessions,
        boolean sameIp, SessionRegistry registry) throws SessionAuthenticationException {
    // new IP handle
    if (!sameIp) {
        // deny login if exceptionIfMaximumExceeded
        if (exceptionIfMaximumExceeded || (sessions == null)) {
            throw new SessionAuthenticationException(
                    messages.getMessage("ConcurrentSessionControllerImpl.exceededAllowed",
                            new Object[] { Integer.valueOf(allowableSessions) },
                            "Maximum sessions of {0} for this principal exceeded"));
        }
    }
    // Determine least recently used session, and mark it for invalidation
    SessionInformation leastRecentlyUsed = null;

    for (int i = 0; i < sessions.size(); i++) {
        if ((leastRecentlyUsed == null)
                || sessions.get(i).getLastRequest().before(leastRecentlyUsed.getLastRequest())) {
            leastRecentlyUsed = sessions.get(i);
        }
    }

    if (sessions.size() > allowableSessions && !sameIp) {

        BasicPrincipal basicPrincipal = (BasicPrincipal) leastRecentlyUsed.getPrincipal();

        for (int i = 0; i < sessions.size(); i++) {
            if (sessions.get(i).getPrincipal().equals(leastRecentlyUsed.getPrincipal())) {
                if (basicPrincipal.equalsIp((BasicPrincipal) (sessions.get(i).getPrincipal()))) {
                    sessions.get(i).expireNow();
                }
            }
        }
        leastRecentlyUsed.expireNow();
    } else if (!sameIp) {
        leastRecentlyUsed.expireNow();
    } else {
        // TODO
    }

}

From source file:com.liangc.hq.base.service.permissions.BaseSessionInitializationStrategy.java

public void onAuthentication(Authentication authentication, HttpServletRequest request,
        HttpServletResponse response) throws SessionAuthenticationException {
    final boolean debug = log.isDebugEnabled();

    if (debug)//  w w  w . j av a2  s  .  c  o  m
        log.debug("Initializing UI session parameters...");
    boolean updateRoles = false;
    String username = authentication.getName();

    //If this is an organization authentication (ldap\kerberos) we will add a 'org\' prefix to the
    //user name so we will know it's an organization user
    if (null != authentication.getDetails()
            && (authentication.getDetails() instanceof HQAuthenticationDetails)) {
        HQAuthenticationDetails authDetails = (HQAuthenticationDetails) authentication.getDetails();
        if (authDetails.isUsingExternalAuth()) {
            username = HQConstants.ORG_AUTH_PREFIX + username;
            //If this is a Ldap user we will update his roles
            if (null != authentication.getPrincipal()
                    && authentication.getPrincipal().getClass().getName().contains("Ldap")) {
                updateRoles = true;
            }
        }
    }
    try {
        // The following is logic taken from the old HQ Authentication Filter
        int sessionId = sessionManager.put(authzSubjectManager.findSubjectByName(username));
        HttpSession session = request.getSession();
        ServletContext ctx = session.getServletContext();

        // look up the subject record
        AuthzSubject subj = authzBoss.getCurrentSubject(sessionId);
        boolean needsRegistration = false;

        if (subj == null || updateRoles) {
            try {
                AuthzSubject overlord = authzSubjectManager.getOverlordPojo();
                if (null == subj) {
                    needsRegistration = true;
                    subj = authzSubjectManager.createSubject(overlord, username, true,
                            HQConstants.ApplicationName, "", "", "", "", "", "", false);
                }
                //For LDAP users we first want to remove all the existing 'LDAP' roles and then add the current roles he belongs to.
                //We are doing that because for LDAP users we do an automatic mapping of the roles according to the group the
                //user belongs to, and if the user has been removed or added from some group we want this to be reflected in his roles.
                if (updateRoles) {
                    Collection<RoleValue> roles = roleManager.getRoles(subj, PageControl.PAGE_ALL);
                    for (RoleValue role : roles) {
                        String roleName = role.getName().toLowerCase();
                        if (roleName.startsWith(HQConstants.ORG_AUTH_PREFIX)) {
                            roleManager.removeSubjects(authzSubjectManager.getOverlordPojo(), role.getId(),
                                    new Integer[] { subj.getId() });
                        }
                    }
                }
                //every user has ROLE_HQ_USER.  If other roles assigned, automatically assign them to new user
                if (authentication.getAuthorities().size() > 1) {
                    Collection<Role> roles = roleManager.getAllRoles();
                    for (GrantedAuthority authority : authentication.getAuthorities()) {
                        if (authority.getAuthority().equals("ROLE_HQ_USER")) {
                            continue;
                        }
                        for (Role role : roles) {
                            String roleName = role.getName().toLowerCase();
                            String ldapRoleName = "";
                            if (roleName.startsWith(HQConstants.ORG_AUTH_PREFIX)) {
                                ldapRoleName = roleName.substring(roleName.indexOf(HQConstants.ORG_AUTH_PREFIX)
                                        + HQConstants.ORG_AUTH_PREFIX.length()).trim();
                            }
                            if ((("ROLE_" + role.getName()).equalsIgnoreCase(authority.getAuthority()))
                                    || (("ROLE_" + ldapRoleName).equalsIgnoreCase(authority.getAuthority()))) {
                                roleManager.addSubjects(authzSubjectManager.getOverlordPojo(), role.getId(),
                                        new Integer[] { subj.getId() });
                            }
                        }
                    }
                }
            } catch (ApplicationException e) {
                throw new SessionAuthenticationException("Unable to add user to authorization system");
            }

            sessionId = sessionManager.put(subj);
        } else {
            needsRegistration = subj.getEmailAddress() == null || subj.getEmailAddress().length() == 0;
        }

        userAuditFactory.loginAudit(subj);
        AuthzSubjectValue subject = subj.getAuthzSubjectValue();

        // figure out if the user has a principal
        boolean hasPrincipal = authBoss.isUser(sessionId, subject.getName());
        ConfigResponse preferences = needsRegistration ? new ConfigResponse()
                : getUserPreferences(ctx, sessionId, subject.getId(), authzBoss);
        WebUser webUser = new WebUser(subject, sessionId, preferences, hasPrincipal);

        // Add WebUser to Session
        session.setAttribute(Constants.WEBUSER_SES_ATTR, webUser);

        if (debug)
            log.debug("WebUser object created and stashed in the session");

        // TODO - We should use Spring Security for handling user
        // permissions...
        Map<String, Boolean> userOperationsMap = new HashMap<String, Boolean>();

        if (webUser.getPreferences().getKeys().size() > 0) {
            userOperationsMap = loadUserPermissions(webUser.getSessionId(), authzBoss);
        }

        session.setAttribute(Constants.USER_OPERATIONS_ATTR, userOperationsMap);

        if (debug)
            log.debug("Stashing user operations in the session");

        if (debug && needsRegistration) {
            log.debug("Authentic user but no HQ entity, must have authenticated outside of "
                    + "HQ...needs registration");
        }
    } catch (SessionException e) {
        if (debug) {
            log.debug("Authentication of user {" + username + "} failed due to an session error.");
        }

        throw new SessionAuthenticationException("login.error.application");
    } catch (PermissionException e) {
        if (debug) {
            log.debug("Authentication of user {" + username + "} failed due to an permissions error.");
        }

        throw new SessionAuthenticationException("login.error.application");
    }
}