Example usage for javax.security.auth Subject getPrincipals

List of usage examples for javax.security.auth Subject getPrincipals

Introduction

In this page you can find the example usage for javax.security.auth Subject getPrincipals.

Prototype

public Set<Principal> getPrincipals() 

Source Link

Document

Return the Set of Principals associated with this Subject .

Usage

From source file:org.infoscoop.web.SessionManagerFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest httpReq = (HttpServletRequest) request;
    if (log.isDebugEnabled()) {
        log.debug("Enter SessionManagerFilter form " + httpReq.getRequestURI());
    }//from ww w .  j a  va  2  s .  c o  m

    if (request instanceof javax.servlet.http.HttpServletRequest) {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        String uid = null;
        if (SessionCreateConfig.doLogin()) {
            uid = getUidFromSession(httpReq);

            if (uid != null) {
                addUidToSession(uid, request);
            }

            if (redirectPaths.contains(httpReq.getServletPath())) {
                httpResponse.addCookie(new Cookie("redirect_path", httpReq.getServletPath()));
            }
            if (uid == null && !isExcludePath(httpReq.getServletPath())) {
                if (httpRequest.getHeader("MSDPortal-Ajax") != null) {
                    if (log.isInfoEnabled())
                        log.info("session timeout has occured. logoff automatically.");
                    httpResponse.setHeader(HttpStatusCode.HEADER_NAME, HttpStatusCode.MSD_SESSION_TIMEOUT);
                    httpResponse.sendError(500);
                    return;
                }
            }
        } else {
            uid = getUidFromHeader(httpReq);
            if (uid == null)
                uid = getUidFromSession(httpReq);
            if (uid != null) {
                addUidToSession(uid, request);
            }
        }

        if (uid == null) {
            Cookie[] cookies = httpReq.getCookies();
            if (cookies != null) {
                for (Cookie cookie : cookies) {
                    if (cookie.getName().equals("portal-credential")) {
                        int keepPeriod = 7;
                        try {
                            keepPeriod = Integer.parseInt(PropertiesDAO.newInstance()
                                    .findProperty("loginStateKeepPeriod").getValue());
                        } catch (Exception ex) {
                            log.warn("", ex);
                        }

                        if (keepPeriod <= 0) {
                            Cookie credentialCookie = new Cookie("portal-credential", "");
                            credentialCookie.setMaxAge(0);
                            credentialCookie.setPath("/");
                            httpResponse.addCookie(credentialCookie);

                            log.info("clear auto login credential [" + credentialCookie.getValue() + "]");
                        } else {
                            try {
                                uid = tryAutoLogin(cookie);
                                httpReq.getSession().setAttribute("Uid", uid);

                                log.info("auto login success.");
                            } catch (Exception ex) {
                                log.info("auto login failed.", ex);
                            }
                        }
                    }
                }
            }
        }

        if (uid == null && SessionCreateConfig.doLogin() && !isExcludePath(httpReq.getServletPath())) {
            String requestUri = httpReq.getRequestURI();
            String loginUrl = requestUri.lastIndexOf("/manager/") > 0
                    ? requestUri.substring(0, requestUri.lastIndexOf("/")) + "/../login.jsp"
                    : "login.jsp";

            httpResponse.sendRedirect(loginUrl);
            return;
        }

        if (log.isInfoEnabled())
            log.info("### Access from user " + uid + " to " + httpReq.getRequestURL());

        // fix #42
        //         setUserInfo2Cookie(httpReq, (HttpServletResponse)response, uid);
        HttpSession session = httpRequest.getSession();

        Subject loginUser = (Subject) session.getAttribute(LOGINUSER_SUBJECT_ATTR_NAME);

        if (loginUser == null || (isChangeLoginUser(uid, loginUser)
                && !(session instanceof PreviewImpersonationFilter.PreviewHttpSession))) {
            if (!SessionCreateConfig.getInstance().hasUidHeader() && uid != null) {
                AuthenticationService service = AuthenticationService.getInstance();
                try {
                    if (service != null)
                        loginUser = service.getSubject(uid);
                } catch (Exception e) {
                    log.error("", e);
                }
            }

            if (loginUser == null || isChangeLoginUser(uid, loginUser)) {
                loginUser = new Subject();
                loginUser.getPrincipals().add(new ISPrincipal(ISPrincipal.UID_PRINCIPAL, uid));
            }

            setLoginUserName(httpRequest, loginUser);

            for (Map.Entry entry : SessionCreateConfig.getInstance().getRoleHeaderMap().entrySet()) {
                String headerName = (String) entry.getKey();
                String roleType = (String) entry.getValue();
                Enumeration headerValues = httpRequest.getHeaders(headerName);
                while (headerValues.hasMoreElements()) {
                    String headerValue = (String) headerValues.nextElement();
                    try {
                        Set principals = loginUser.getPrincipals();
                        principals.add(new ISPrincipal(roleType, headerValue));
                        //                     loginUser.getPrincipals().add( roleType.getConstructor(paramTypes).newInstance(initArgs) );
                        if (log.isInfoEnabled())
                            log.info("Set principal to login subject: " + roleType + "=" + headerValue);
                    } catch (IllegalArgumentException e) {
                        log.error("", e);
                    } catch (SecurityException e) {
                        log.error("", e);
                    }
                }

            }
            session.setAttribute(LOGINUSER_SUBJECT_ATTR_NAME, loginUser);
        }
        SecurityController.registerContextSubject(loginUser);
        if (httpRequest.getHeader("X-IS-TIMEZONE") != null) {
            int timeZoneOffset = 0;
            try {
                timeZoneOffset = Integer.parseInt(httpRequest.getHeader("X-IS-TIMEZONE"));
            } catch (NumberFormatException e) {
                if (log.isDebugEnabled())
                    log.debug(httpRequest.getHeader("X-IS-TIMEZONE"), e);
            } finally {
                UserContext.instance().getUserInfo().setClientTimezoneOffset(timeZoneOffset);
            }
        }
    }
    chain.doFilter(request, response);

    if (log.isDebugEnabled()) {
        log.debug("Exit SessionManagerFilterform " + httpReq.getRequestURI());
    }

}

From source file:org.tolven.web.RegisterAction.java

public String getUserRoleString() throws PolicyContextException {
    Subject subject = (Subject) PolicyContext.getContext("javax.security.auth.Subject.container");
    StringBuffer buff = new StringBuffer();
    if (subject != null) {
        for (Principal principal : subject.getPrincipals()) {
            if (principal instanceof Group && "Roles".equals(principal.getName())) {
                java.util.Enumeration<?> enumeration = ((Group) principal).members();
                Principal rolePrincipal = null;
                while (enumeration.hasMoreElements()) {
                    rolePrincipal = (Principal) enumeration.nextElement();
                    buff.append(rolePrincipal.getName());
                    if (enumeration.hasMoreElements()) {
                        buff.append(", ");
                    }// w w w  .  j  a  v  a 2s .c o  m
                }
                break;
            }
        }
    }
    return buff.toString();
}

From source file:org.alfresco.web.site.servlet.SSOAuthenticationFilter.java

/**
 * Initialize the filter/*from   ww w . ja  va 2  s.co  m*/
 */
public void init(FilterConfig args) throws ServletException {
    if (logger.isDebugEnabled())
        logger.debug("Initializing the SSOAuthenticationFilter.");

    // get reference to our ServletContext
    this.servletContext = args.getServletContext();

    ApplicationContext context = getApplicationContext();

    this.loginController = (SlingshotLoginController) context.getBean("loginController");

    // retrieve the connector service
    this.connectorService = (ConnectorService) context.getBean("connector.service");

    ConfigService configService = (ConfigService) context.getBean("web.config");

    // Retrieve the remote configuration
    RemoteConfigElement remoteConfig = (RemoteConfigElement) configService.getConfig("Remote")
            .getConfigElement("remote");
    if (remoteConfig == null) {
        logger.error(
                "There is no Remote configuration element. This is required to use SSOAuthenticationFilter.");
        return;
    }

    // get the endpoint id to use
    String endpoint = args.getInitParameter("endpoint");
    if (endpoint == null) {
        logger.error(
                "There is no 'endpoint' id in the SSOAuthenticationFilter init parameters. Cannot initialise filter.");
        return;
    }

    // Get the endpoint descriptor and check if external auth is enabled
    EndpointDescriptor endpointDescriptor = remoteConfig.getEndpointDescriptor(endpoint);
    if (endpointDescriptor == null || !endpointDescriptor.getExternalAuth()) {
        if (logger.isDebugEnabled())
            logger.debug("No External Auth endpoint configured for " + endpoint);
        return;
    }

    try {
        Connector conn = this.connectorService.getConnector(endpoint);

        // Save the endpoint, activating the filter
        this.endpoint = endpoint;
        if (logger.isDebugEnabled())
            logger.debug("Endpoint is " + endpoint);

        // Obtain the userHeader (if configured) from the alfresco connector
        this.userHeader = conn.getConnectorSession()
                .getParameter(SlingshotAlfrescoConnector.CS_PARAM_USER_HEADER);
        String userIdPattern = conn.getConnectorSession()
                .getParameter(SlingshotAlfrescoConnector.CS_PARAM_USER_ID_PATTERN);
        if (userIdPattern != null) {
            this.userIdPattern = Pattern.compile(userIdPattern);
        }
        if (logger.isDebugEnabled()) {
            logger.debug("userHeader is " + userHeader);
            logger.debug("userIdPattern is " + userIdPattern);
        }
    } catch (ConnectorServiceException e) {
        logger.error("Unable to find connector " + endpointDescriptor.getConnectorId() + " for the endpoint "
                + endpoint, e);
    }

    // retrieve the optional kerberos configuration
    KerberosConfigElement krbConfig = (KerberosConfigElement) configService.getConfig("Kerberos")
            .getConfigElement("kerberos");
    if (krbConfig != null) {
        if (logger.isDebugEnabled())
            logger.debug("Found configuration for Kerberos authentication.");
        // Get the Kerberos realm

        String krbRealm = krbConfig.getRealm();
        if (krbRealm != null && krbRealm.length() > 0) {
            if (logger.isDebugEnabled())
                logger.debug("Found Kerberos realm: " + krbRealm);
            // Set the Kerberos realm

            this.krbRealm = krbRealm;
        } else
            throw new ServletException("Kerberos realm not specified");

        // Get the HTTP service account password

        String srvPassword = krbConfig.getPassword();
        if (srvPassword != null && srvPassword.length() > 0) {
            // Set the HTTP service account password

            this.krbPassword = srvPassword;
        } else
            throw new ServletException("HTTP service account password not specified");

        String krbEndpointSPN = krbConfig.getEndpointSPN();
        if (krbEndpointSPN != null && krbEndpointSPN.length() > 0) {
            // Set the Service Principal Name to use on the endpoint
            if (logger.isDebugEnabled())
                logger.debug("The Service Principal Name to use on the endpoint: " + krbEndpointSPN);
            this.krbEndpointSPN = krbEndpointSPN;
        } else
            throw new ServletException("endpoint service principal name not specified");

        // Get the login configuration entry name

        String loginEntry = krbConfig.getLoginEntryName();

        if (loginEntry != null) {
            if (loginEntry.length() > 0) {
                // Set the login configuration entry name to use
                if (logger.isDebugEnabled())
                    logger.debug("The login configuration entry name to use: " + loginEntry);
                jaasLoginEntryName = loginEntry;
            } else
                throw new ServletException("Invalid login entry specified");
        }

        // Get the login stripUserNameSuffix property

        boolean stripUserNameSuffix = krbConfig.getStripUserNameSuffix();

        // Set the login configuration entry name to use
        if (logger.isDebugEnabled())
            logger.debug("The stripUserNameSuffix property is set to: " + stripUserNameSuffix);
        this.stripUserNameSuffix = stripUserNameSuffix;

        // Create a login context for the HTTP server service

        try {
            // Login the HTTP server service

            jaasLoginContext = new LoginContext(jaasLoginEntryName, this);
            jaasLoginContext.login();

            // DEBUG

            if (logger.isDebugEnabled())
                logger.debug("HTTP Kerberos login successful");
        } catch (LoginException ex) {
            // Debug

            if (logger.isErrorEnabled())
                logger.error("HTTP Kerberos web filter error", ex);

            throw new ServletException("Failed to login HTTP server service");
        }

        // Get the HTTP service account name from the subject

        Subject subj = jaasLoginContext.getSubject();
        Principal princ = subj.getPrincipals().iterator().next();

        krbAccountName = princ.getName();

        // DEBUG

        if (logger.isDebugEnabled())
            logger.debug("Logged on using principal " + krbAccountName);
    }

    if (logger.isInfoEnabled())
        logger.info("SSOAuthenticationFilter initialised.");
}

From source file:org.apache.hadoop.hive.shims.Hadoop23Shims.java

@Override
public UserGroupInformation cloneUgi(UserGroupInformation baseUgi) throws IOException {
    // Based on UserGroupInformation::createProxyUser.
    // TODO: use a proper method after we can depend on HADOOP-13081.
    if (getSubjectMethod == null) {
        throw new IOException("The UGI method was not found: " + ugiCloneError);
    }/* w  w  w. j a va 2s.  c om*/
    try {
        Subject origSubject = (Subject) getSubjectMethod.invoke(baseUgi);

        Subject subject = new Subject(false, origSubject.getPrincipals(),
                cloneCredentials(origSubject.getPublicCredentials()),
                cloneCredentials(origSubject.getPrivateCredentials()));
        return ugiCtor.newInstance(subject);
    } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
        throw new IOException(e);
    }
}

From source file:io.fabric8.maven.impl.MavenSecureHttpContext.java

public Subject doAuthenticate(final String username, final String password) {
    try {/*from  w w w .  ja  v a 2  s  . c  o  m*/
        Subject subject = new Subject();
        LoginContext loginContext = new LoginContext(realm, subject, new CallbackHandler() {
            public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
                for (int i = 0; i < callbacks.length; i++) {
                    if (callbacks[i] instanceof NameCallback) {
                        ((NameCallback) callbacks[i]).setName(username);
                    } else if (callbacks[i] instanceof PasswordCallback) {
                        ((PasswordCallback) callbacks[i]).setPassword(password.toCharArray());
                    } else {
                        throw new UnsupportedCallbackException(callbacks[i]);
                    }
                }
            }
        });
        loginContext.login();
        if (role != null && role.length() > 0) {
            String clazz = "org.apache.karaf.jaas.boot.principal.RolePrincipal";
            String name = role;
            int idx = role.indexOf(':');
            if (idx > 0) {
                clazz = role.substring(0, idx);
                name = role.substring(idx + 1);
            }
            boolean found = false;
            for (Principal p : subject.getPrincipals()) {
                if (p.getClass().getName().equals(clazz) && p.getName().equals(name)) {
                    found = true;
                    break;
                }
            }
            if (!found) {
                throw new FailedLoginException("User does not have the required role " + role);
            }
        }
        return subject;
    } catch (AccountException e) {
        LOGGER.warn("Account failure", e);
        return null;
    } catch (LoginException e) {
        LOGGER.debug("Login failed", e);
        return null;
    } catch (GeneralSecurityException e) {
        LOGGER.error("General Security Exception", e);
        return null;
    }
}

From source file:com.google.gsa.Kerberos.java

/**
 * Gets the principal from the subject//from   www  . j  av a  2 s  .  c  o  m
 * 
 * @param subject user subject
 * 
 * @return principal
 */
public String getPrincipalFromSubject(Subject subject) {

    String principal = null;

    logger.debug("Getting principal from Subject");
    try {
        Set principals = subject.getPrincipals();
        if (!principals.isEmpty()) {
            logger.debug("Subject contains at least one Principal");
            Iterator it = principals.iterator();
            if (it.hasNext()) {
                Principal ppal = (Principal) it.next();
                principal = ppal.getName().substring(0, ppal.getName().indexOf("@"));
                logger.debug("Getting the first principal: " + principal);
            }
        }
    } catch (Exception e) {
        logger.error("Error retrieving the client's Principal from the Subject: " + e.getMessage(), e);
    }

    return principal;
}

From source file:com.dtolabs.rundeck.core.cli.acl.AclTool.java

private Subject makeSubject(final String argUser1user, final Collection<String> groupsList1) {
    Subject t = new Subject();
    String user = argUser1user != null ? argUser1user : "user";
    t.getPrincipals().add(new Username(user));
    if (null != groupsList1) {
        for (String s : groupsList1) {
            t.getPrincipals().add(new Group(s));
        }/*from   w  ww .jav a 2  s.c o m*/
    }
    return t;
}

From source file:net.java.jaspicoil.MSPacSpnegoServerAuthModule.java

private boolean authorizeCaller(HttpServletRequest request, byte[] serviceToken, GSSName name,
        final Subject clientSubject) {

    // create Subject with principals from name
    final Subject kerberosServiceSubject = createSubject(name);

    final Set<Principal> kerberosServicePrincipals = kerberosServiceSubject.getPrincipals();

    if (kerberosServicePrincipals.size() > 0) {
        final Set<Principal> clientPrincipals = clientSubject.getPrincipals();

        clientPrincipals.addAll(kerberosServicePrincipals);

        // Pickup the first Principal as the caller
        final Principal caller = kerberosServicePrincipals.iterator().next();

        if (caller != null) {
            // Fetch the list of extra groups
            final Set<String> extraGroups = fetchExtraGroups(request, this.serviceSubject, this.options);

            // Let's add all the groups as valid Principal as part of the
            // clientSubject
            final String[] groups = buildGroupsFromPAC(serviceToken, this.serviceSubject, extraGroups);

            final List<String> groupList = Arrays.asList(groups);

            if (this.mandatoryGroups != null && this.mandatoryGroups.size() > 0) {
                // There was some mandatory group to check
                if (!groupList.containsAll(this.mandatoryGroups)) {
                    // None of the global constraint was found, so exiting
                    debug("Not all the mandatory groups required ({1}) where found in the user groups {0} so failing the authentication.",
                            groupList, this.mandatoryGroups);
                    return false;
                }/*from   ww  w  .  jav  a2 s  .  c  o m*/
            }

            // Check global constraints
            if (this.smartcardSecuredUsersOnly || this.delegatedSecuredUsersOnly) {

                final List<String> contraintGroupList = new ArrayList<String>();
                if (this.smartcardSecuredUsersOnly) {
                    contraintGroupList.add(GROUP_SMARTCARD_AUTHENTICATED);
                }
                if (this.delegatedSecuredUsersOnly) {
                    contraintGroupList.add(GROUP_DELEGATED_AUTHENTICATED);
                }

                // Test if at least one of the constraints are matched
                if (Collections.disjoint(groupList, contraintGroupList)) {
                    // None of the global constraint was found, so exiting
                    debug("The global contrainted group {1} where not found in the user groups {0} so failing the authentication.",
                            groupList, contraintGroupList);
                    return false;
                }

            }

            final GroupPrincipalCallback groupPrincipalCallback = new GroupPrincipalCallback(clientSubject,
                    groups);
            try {
                // notify caller for the groups
                this.handler.handle(new Callback[] { groupPrincipalCallback });
                debug("Groups found {0}", groupList);
            } catch (final IOException e) {
                LOG.log(Level.WARNING, "Unable to set the groups " + groupList, e);
            } catch (final UnsupportedCallbackException e) {
                LOG.log(Level.WARNING, "Unable to set the groups " + groupList, e);
            }
        }

        // Create the caller principal to pass to caller
        final CallerPrincipalCallback callerPrincipalCallback = new CallerPrincipalCallback(clientSubject,
                caller);

        try {
            // notify caller for the Principal
            this.handler.handle(new Callback[] { callerPrincipalCallback });
            debug("Caller principal is {0}", (Object) caller);
            return true;
        } catch (final IOException e) {
            LOG.log(Level.WARNING, "Unable to set caller principal {0}", e);
        } catch (final UnsupportedCallbackException e) {
            LOG.log(Level.WARNING, "Unable to set caller principal {0}", e);
        }
    }
    return false;
}

From source file:org.forgerock.openidm.jaspi.modules.IDMUserAuthModule.java

/**
 * Validates the request by authenticating against either the client certificate in the request, internally or
 * Basic Authentication from the request header internally.
 *
 * @param messageInfo {@inheritDoc}/*from   w w w . j a v a  2 s  . c om*/
 * @param clientSubject {@inheritDoc}
 * @param serviceSubject {@inheritDoc}
 * @param authData {@inheritDoc}
 * @return {@inheritDoc}
 */
@Override
protected AuthStatus validateRequest(MessageInfo messageInfo, Subject clientSubject, Subject serviceSubject,
        AuthData authData) {

    HttpServletRequest req = (HttpServletRequest) messageInfo.getRequestMessage();
    boolean authenticated;

    final String headerLogin = req.getHeader(HEADER_USERNAME);
    String basicAuth = req.getHeader("Authorization");
    // if we see the certificate port this request is for client auth only
    if (allowClientCertOnly(req)) {
        authenticated = authenticateUsingClientCert(req, authData);
        //Auth success will be logged in IDMServerAuthModule super type.
    } else if (headerLogin != null) {
        authenticated = authenticateUser(req, authData);
        //Auth success will be logged in IDMServerAuthModule super type.
    } else if (basicAuth != null) {
        authenticated = authenticateUsingBasicAuth(basicAuth, authData);
        //Auth success will be logged in IDMServerAuthModule super type.
    } else {
        //Auth failure will be logged in IDMServerAuthModule super type.
        return AuthStatus.SEND_FAILURE;
    }
    authData.setResource(queryOnResource);
    logger.debug("Found valid session for {} id {} with roles {}", authData.getUsername(), authData.getUserId(),
            authData.getRoles());

    if (authenticated) {
        clientSubject.getPrincipals().add(new Principal() {
            public String getName() {
                return headerLogin;
            }
        });
    }

    return authenticated ? AuthStatus.SUCCESS : AuthStatus.SEND_FAILURE;
}

From source file:org.apache.jackrabbit.core.SessionImpl.java

/**
 * Protected constructor./*from   ww  w.j  a v  a 2 s.com*/
 *
 * @param rep
 * @param subject
 * @param wspConfig
 * @throws AccessDeniedException if the given subject is not granted access
 *                               to the specified workspace
 * @throws RepositoryException   if another error occurs
 */
protected SessionImpl(RepositoryImpl rep, Subject subject, WorkspaceConfig wspConfig)
        throws AccessDeniedException, RepositoryException {
    alive = true;
    this.rep = rep;
    Set principals = subject.getPrincipals();
    if (principals.isEmpty()) {
        String msg = "unable to instantiate Session: no principals found";
        log.error(msg);
        throw new RepositoryException(msg);
    } else {
        // use 1st principal in case there are more that one
        Principal principal = (Principal) principals.iterator().next();
        userId = principal.getName();
    }
    this.subject = subject;
    nsMappings = new LocalNamespaceMappings(rep.getNamespaceRegistry());
    namePathResolver = new DefaultNamePathResolver(nsMappings, true);
    ntMgr = new NodeTypeManagerImpl(rep.getNodeTypeRegistry(), rep.getNamespaceRegistry(),
            getNamespaceResolver(), getNamePathResolver(), rep.getDataStore());
    String wspName = wspConfig.getName();
    wsp = createWorkspaceInstance(wspConfig, rep.getWorkspaceStateManager(wspName), rep, this);
    itemStateMgr = createSessionItemStateManager(wsp.getItemStateManager());
    hierMgr = itemStateMgr.getHierarchyMgr();
    itemMgr = createItemManager(itemStateMgr, hierMgr);
    accessMgr = createAccessManager(subject, itemStateMgr.getAtticAwareHierarchyMgr());
    versionMgr = createVersionManager(rep);
}