Creates an auth token.
@param principal the auth principal
@param roles the auth roles
@param expiresInMillis the number of millis to expiry
@return the auth token
518090
public static final AuthToken createAuthToken(String principal, Set<String> roles, int expiresInMillis) {
        AuthToken token = new AuthToken();
        token.setIssuedOn(new Date());
        token.setExpiresOn(new Date(System.currentTimeMillis() + expiresInMillis));
        token.setPrincipal(principal);
        token.setRoles(roles);
        signAuthToken(token);
        return token;
    }
504489
private static Token<EsTokenIdentifier> getAuthToken(ClusterName clusterName, User user) {
        EsToken esToken = getEsAuthToken(clusterName, user);
        if (esToken == null) {
            return null;
        } else {
            return EsTokenIdentifier.createTokenFrom(esToken);
        }
    }
1059553
private static Principal getPrimaryPrincipal(final PrincipalElectionStrategy principalElectionStrategy,
                                                 final Set<Authentication> authentications,
                                                 final Map<String, List<Object>> principalAttributes) {
        return principalElectionStrategy.nominate(new LinkedHashSet<>(authentications), principalAttributes);
    }
234348
public void setPrincipals(java.util.Collection<Principal> principals) {
        if (principals == null) {
            this.principals = null;
            return;
        }

        this.principals = new java.util.ArrayList<Principal>(principals);
    }
516323
@FFDCIgnore(NamingException.class)
    public TimedDirContext createDirContext(String principal, byte[] credential) throws NamingException {
        final String METHODNAME = "createDirContext(String, byte[])";

        String activeURL = getActiveURL();
        Hashtable<String, Object> environment = getEnvironment(URLTYPE_SINGLE, activeURL);
        environment.put(Context.SECURITY_PRINCIPAL, principal);
        environment.put(Context.SECURITY_CREDENTIALS, credential);

        SSLUtilImpl sslUtil = new SSLUtilImpl();
        Properties currentSSLProps = sslUtil.getSSLPropertiesOnThread();
        try {
            if (iSSLAlias != null) {
                try {
                    if (tc.isDebugEnabled())
                        Tr.debug(tc, METHODNAME + " Use WAS SSL Configuration.");
                    sslUtil.setSSLAlias(iSSLAlias, environment);
                } catch (Exception ssle) {
                    throw new NamingException(ssle.getMessage());
                }
            }

            // Set the classloader so that a class in the package can be loaded by JNDI
            ClassLoader origCL = getContextClassLoader();
            setContextClassLoader(getClass());
            try {
                TimedDirContext ctx = null;
                try {
                    ctx = new TimedDirContext(environment, getConnectionRequestControls(), roundToSeconds(System.currentTimeMillis()));
                } catch (NamingException e) {
                    if (!isConnectionException(e)) {
                        throw e;
                    } else {
                        if (tc.isDebugEnabled())
                            Tr.debug(tc, "Encountered an exception while creating a context: " + e.getMessage());
                    }

                    // Get the Next URL
                    environment = getEnvironment(URLTYPE_SEQUENCE, getNextURL(activeURL));
                    // Reset the security credentials on the environment.
                    environment.put(Context.SECURITY_PRINCIPAL, principal);
                    environment.put(Context.SECURITY_CREDENTIALS, credential);

                    ctx = new TimedDirContext(environment, getConnectionRequestControls(), roundToSeconds(System.currentTimeMillis()));
                    String newURL = getProviderURL(ctx);
                    long creationTimeMillisec = System.currentTimeMillis();

                    synchronized (iLock) {
                        // Refresh context pool if another thread hasn't already done so
                        if (creationTimeMillisec > iPoolCreateTimestampMillisec) {
                            createContextPool(iLiveContexts, newURL);
                            ctx.setCreateTimestamp(iPoolCreateTimestampSeconds);
                        }
                    }
                }
                return ctx;
            } finally {
                setContextClassLoader(origCL);
            }
        } finally {
            sslUtil.setSSLPropertiesOnThread(currentSSLProps);
        }
    }
838577
public Principal authenticate(UserRealm realm,
                                  String pathInContext,
                                  HttpRequest httpRequest,
                                  HttpResponse httpResponse)
        throws IOException
    {
        HttpServletRequest request =(ServletHttpRequest)httpRequest.getWrapper();
        HttpServletResponse response = httpResponse==null?null:(HttpServletResponse) httpResponse.getWrapper();
        
        // Handle paths
        String uri = pathInContext;

        // Setup session 
        HttpSession session=request.getSession(response!=null);
        if (session==null)
            return null;
        
        // Handle a request for authentication.
        if ( uri.substring(uri.lastIndexOf("/")+1).startsWith(__J_SECURITY_CHECK) )
        {
            // Check the session object for login info.
            FormCredential form_cred=new FormCredential();
            form_cred.authenticate(realm,
                                            request.getParameter(__J_USERNAME),
                                            request.getParameter(__J_PASSWORD),
                                            httpRequest);
            
            String nuri=(String)session.getAttribute(__J_URI);
            if (nuri==null || nuri.length()==0)
            {
                nuri=request.getContextPath();
                if (nuri.length()==0)
                    nuri="/";
            }
            
            if (form_cred._userPrincipal!=null)
            {
                // Authenticated OK
                if(log.isDebugEnabled())log.debug("Form authentication OK for "+form_cred._jUserName);
                session.removeAttribute(__J_URI); // Remove popped return URI.
                httpRequest.setAuthType(SecurityConstraint.__FORM_AUTH);
                httpRequest.setAuthUser(form_cred._jUserName);
                httpRequest.setUserPrincipal(form_cred._userPrincipal);
                session.setAttribute(__J_AUTHENTICATED,form_cred);

                // Sign-on to SSO mechanism
                if (realm instanceof SSORealm)
                {
                    ((SSORealm)realm).setSingleSignOn(httpRequest,
                                                                    httpResponse,
                                                                    form_cred._userPrincipal,
                                                                    new Password(form_cred._jPassword));
                }

                // Redirect to original request
                if (response!=null)
                {
                    response.setContentLength(0);
                    response.sendRedirect(response.encodeRedirectURL(nuri));
                }
            }   
            else if (response!=null)
            {
                if(log.isDebugEnabled())log.debug("Form authentication FAILED for "+form_cred._jUserName);
                if (_formErrorPage!=null)
                {
                    response.setContentLength(0);
                    response.sendRedirect(response.encodeRedirectURL
                                          (URI.addPaths(request.getContextPath(),
                                                        _formErrorPage)));
                }
                else
                {
                    response.sendError(HttpResponse.__403_Forbidden);
                }
            }
            
            // Security check is always false, only true after final redirection.
            return null;
        }
        
        // Check if the session is already authenticated.
        FormCredential form_cred = (FormCredential) session.getAttribute(__J_AUTHENTICATED);
        
        if (form_cred != null)
        {
            // We have a form credential. Has it been distributed?
            if (form_cred._userPrincipal==null)
            {
                // This form_cred appears to have been distributed.  Need to reauth
                form_cred.authenticate(realm, httpRequest);
                
                // Sign-on to SSO mechanism
                if (form_cred._userPrincipal!=null && realm instanceof SSORealm)
                {
                    ((SSORealm)realm).setSingleSignOn(httpRequest,
                                                                    httpResponse,
                                                                    form_cred._userPrincipal,
                                                                    new Password(form_cred._jPassword));
                }
            }
            else if (!realm.reauthenticate(form_cred._userPrincipal))
                // Else check that it is still authenticated.
                form_cred._userPrincipal=null;

            // If this credential is still authenticated
            if (form_cred._userPrincipal!=null)
            {
                if(log.isDebugEnabled())log.debug("FORM Authenticated for "+form_cred._userPrincipal.getName());
                httpRequest.setAuthType(SecurityConstraint.__FORM_AUTH);
                httpRequest.setAuthUser(form_cred._userPrincipal.getName());
                httpRequest.setUserPrincipal(form_cred._userPrincipal);
                return form_cred._userPrincipal;
            }
            else
                session.setAttribute(__J_AUTHENTICATED,null);
        }
        else if (realm instanceof SSORealm)
        {
            // Try a single sign on.
            Credential cred = ((SSORealm)realm).getSingleSignOn(httpRequest,httpResponse);
            
            if (httpRequest.hasUserPrincipal())
            {
                form_cred=new FormCredential();
                form_cred._userPrincipal=request.getUserPrincipal();
                form_cred._jUserName=form_cred._userPrincipal.getName();
                if (cred!=null)
                    form_cred._jPassword=cred.toString();
                if(log.isDebugEnabled())log.debug("SSO for "+form_cred._userPrincipal);
                           
                httpRequest.setAuthType(SecurityConstraint.__FORM_AUTH);
                session.setAttribute(__J_AUTHENTICATED,form_cred);
                return form_cred._userPrincipal;
            }
        }
        
        // Don't authenticate authform or errorpage
        if (isLoginOrErrorPage(pathInContext))
            return SecurityConstraint.__NOBODY;
        
        // redirect to login page
        if (response!=null)
        {
            if (httpRequest.getQuery()!=null)
                uri+="?"+httpRequest.getQuery();
            session.setAttribute(__J_URI, 
                                 request.getScheme() +
                                 "://" + request.getServerName() +
                                 ":" + request.getServerPort() +
                                 URI.addPaths(request.getContextPath(),uri));
            response.setContentLength(0);
            response.sendRedirect(response.encodeRedirectURL(URI.addPaths(request.getContextPath(),
                                                                          _formLoginPage)));
        }

        return null;
    }
529200
public void authenticate(
            HttpServletRequest request,
            Map<String, String> principals,
            Map<String, String> credentials,
            IPerson person)
            throws PortalSecurityException {

        // Retrieve the security context for the user
        final ISecurityContext securityContext = person.getSecurityContext();

        // Set the principals and credentials for the security context chain
        this.configureSecurityContextChain(
                principals, credentials, securityContext, BASE_CONTEXT_NAME);

        // NOTE: PortalPreAuthenticatedProcessingFilter looks in the security.properties file to
        // determine what tokens to look for that represent the principals and
        // credentials for each context. It then retrieves the values from the request
        // and stores the values in the principals and credentials HashMaps that are
        // passed to the Authentication service.

        // Attempt to authenticate the user
        final long start = System.currentTimeMillis();
        securityContext.authenticate();
        final long elapsed = System.currentTimeMillis() - start;
        // Check to see if the user was authenticated
        if (securityContext.isAuthenticated()) {
            lastAuthentication = authenticationTimes.add(elapsed); // metric
            // Add the authenticated username to the person object
            // the login name may have been provided or reset by the security provider
            // so this needs to be done after authentication.
            final String userName = securityContext.getPrincipal().getUID();
            person.setAttribute(IPerson.USERNAME, userName);
            if (log.isDebugEnabled()) {
                log.debug(
                        "FINISHED SecurityContext authentication for user '"
                                + userName
                                + "' in "
                                + elapsed
                                + "ms #milestone");
            }

            threadNamingRequestFilter.updateCurrentUsername(userName);

            /*
             * Clear cached group info for this user.
             *
             * There seem to be 2 systems in place for this information:
             *   - The old system based on EntityCachingService
             *   - The new system based on ehcache
             *
             * For uPortal 5, we should work to remove the old system.
             */
            GroupService.finishedSession(person); // Old system
            for (IAuthenticationListener authListener : authenticationListeners) { // New system
                authListener.userAuthenticated(person);
            }

            // Clear all existing cached data about the person
            this.usernameTaggedCacheEntryPurger.purgeTaggedCacheEntries(userName);

            // Retrieve the additional descriptor from the security context
            final IAdditionalDescriptor addInfo =
                    person.getSecurityContext().getAdditionalDescriptor();
            // Process the additional descriptor if one was created
            if (addInfo != null) {
                // Replace the passed in IPerson with the additional descriptor if the
                // additional descriptor is an IPerson object created by the security context
                // NOTE: This is not the preferred method, creation of IPerson objects should be
                //       handled by the PersonManager.
                if (addInfo instanceof IPerson) {
                    final IPerson newPerson = (IPerson) addInfo;
                    person.setFullName(newPerson.getFullName());

                    for (final String attributeName : newPerson.getAttributeMap().keySet()) {
                        person.setAttribute(attributeName, newPerson.getAttribute(attributeName));
                    }
                }
                // If the additional descriptor is a map then we can
                // simply copy all of these additional attributes into the IPerson
                else if (addInfo instanceof Map) {
                    // Cast the additional descriptor as a Map
                    final Map<?, ?> additionalAttributes = (Map<?, ?>) addInfo;
                    // Copy each additional attribute into the person object
                    for (final Iterator<?> keys = additionalAttributes.keySet().iterator();
                            keys.hasNext(); ) {
                        // Get a key
                        final String key = (String) keys.next();
                        // Set the attribute
                        person.setAttribute(key, additionalAttributes.get(key));
                    }
                } else if (addInfo
                        instanceof ChainingSecurityContext.ChainingAdditionalDescriptor) {
                    // do nothing
                } else {
                    if (log.isWarnEnabled()) {
                        log.warn(
                                "Authentication Service received unknown additional descriptor ["
                                        + addInfo
                                        + "]");
                    }
                }
            }

            // Populate the person object using the PersonDirectory if applicable
            if (PropertiesManager.getPropertyAsBoolean(
                    "org.apereo.portal.services.Authentication.usePersonDirectory")) {
                // Retrieve all of the attributes associated with the person logging in
                final String username = person.getUserName();

                final long timestamp = System.currentTimeMillis();
                if (log.isDebugEnabled()) {
                    log.debug(
                            "STARTING user attribute gathering for user '"
                                    + userName
                                    + "' #milestone");
                }

                final IPersonAttributes personAttributes =
                        this.personAttributeDao.getPerson(username);

                if (log.isDebugEnabled()) {
                    log.debug(
                            "FINISHED user attribute gathering for user '"
                                    + userName
                                    + "' in "
                                    + Long.toString(System.currentTimeMillis() - timestamp)
                                    + "ms #milestone");
                }

                if (personAttributes != null) {
                    // attribs may be null.  IPersonAttributeDao returns null when it does not
                    // recognize a user at all, as
                    // distinguished from returning an empty Map of attributes when it recognizes a
                    // user has having no
                    // attributes.

                    person.setAttributes(personAttributes.getAttributes());
                }
            }
            // Make sure the the user's fullname is set
            if (person.getFullName() == null) {
                // Use portal display name if one exists
                if (person.getAttribute("portalDisplayName") != null) {
                    person.setFullName((String) person.getAttribute("portalDisplayName"));
                }
                // If not try the eduPerson displayName
                else if (person.getAttribute("displayName") != null) {
                    person.setFullName((String) person.getAttribute("displayName"));
                }
                // If still no FullName use an unrecognized string
                if (person.getFullName() == null) {
                    person.setFullName(
                            "Unrecognized person: " + person.getAttribute(IPerson.USERNAME));
                }
            }
            // Find the uPortal userid for this user or flunk authentication if not found.
            final boolean autocreate =
                    PropertiesManager.getPropertyAsBoolean(
                            "org.apereo.portal.services.Authentication.autoCreateUsers");
            try {
                // Attempt to retrieve the UID
                final int newUID = this.userIdentityStore.getPortalUID(person, autocreate);
                person.setID(newUID);
            } catch (final AuthorizationException ae) {
                log.error("Exception retrieving ID", ae);
                throw new PortalSecurityException(
                        "Authentication Service: Exception retrieving UID");
            }
        }

        // Publish a login event for the person
        this.portalEventFactory.publishLoginEvent(request, this, person);
    }
569403
public Principal authenicate(String uid, char[] password)
   throws  SecurityException
   {

      String rootDN = Config.getProperty(ROOT_DN_PROP);
      
      int timeout = Config.getPropertyInteger(TIMEOUT_SECS_PROP).intValue();
      Debugger.println(LDAP.class,"timeout="+timeout);
      
      String uidAttributeName = Config.getProperty(UID_ATTRIB_NM_PROP);
      String groupAttributeName = Config.getProperty(GROUP_ATTRIB_NM_PROP,"");
      String memberOfAttributeName = Config.getProperty(MEMBEROF_ATTRIB_NM_PROP,"");
      
      return authenicate(uid,  password,rootDN,uidAttributeName,memberOfAttributeName,groupAttributeName,timeout);
   }
844641
public X500Principal asX500Principal() {
        if (x500Principal == null) {
            try {
                Object[] args = new Object[] {this};
                x500Principal =
                        (X500Principal)principalConstructor.newInstance(args);
            } catch (Exception e) {
                throw new RuntimeException("Unexpected exception", e);
            }
        }
        return x500Principal;
    }
462480
@Override
    public IAuthorizationPrincipal newPrincipal(String key, Class type) {
        final Tuple<String, Class> principalKey = new Tuple<>(key, type);
        final Element element = this.principalCache.get(principalKey);
        // principalCache is self populating, it can never return a null entry
        return (IAuthorizationPrincipal) element.getObjectValue();
    }
742460
private void writePrincipals(List<Principal> principals)
            throws JsonGenerationException, IOException {
        if (principals.size() == 1 && principals.get(0).equals(Principal.All)) {
            writeJsonKeyValue(JsonDocumentFields.PRINCIPAL, Principal.All.getId());
        } else {
            writeJsonObjectStart(JsonDocumentFields.PRINCIPAL);

            Map<String, List<String>> principalsByScheme = groupPrincipalByScheme(principals);

            List<String> principalValues;
            for (Map.Entry<String, List<String>> entry : principalsByScheme.entrySet()) {
                principalValues = principalsByScheme.get(entry.getKey());

                if (principalValues.size() == 1) {
                    writeJsonKeyValue(entry.getKey(), principalValues.get(0));
                } else {
                    writeJsonArray(entry.getKey(), principalValues);
                }

            }
            writeJsonObjectEnd();
        }
    }
741778
function generateBearerToken(tokenSecret, expiresInMinutes = 60 * 24 * 14, scope = []) {
  if (!tokenSecret) {
    throw new Error('Token secret is undefined');
  }

  const data = {
    user: this._id.toString(),
  };

  if (scope.length) {
    data.scope = scope;
  }

  const token = jwt.sign(data, tokenSecret, {
    expiresInMinutes,
  });

  return {
    type: 'Bearer',
    value: token,
  };
}
1164657
protected Principal authenticateAndGetPrincipal(final UsernamePasswordCredential credential) throws GeneralSecurityException {
        val lc = getLoginContext(credential);
        try {
            lc.login();
            val principals = lc.getSubject().getPrincipals();
            LOGGER.debug("JAAS principals extracted from subject are [{}}", principals);
            if (principals != null && !principals.isEmpty()) {
                val secPrincipal = principals.iterator().next();
                LOGGER.debug("JAAS principal detected from subject login context is [{}}", secPrincipal.getName());
                return this.principalFactory.createPrincipal(secPrincipal.getName());
            }
        } finally {
            if (lc != null) {
                lc.logout();
            }
        }
        return null;
    }
1017069
private String build(Map<String, Object> claims, Date expireTime) {
        return Jwts.builder()
                .setClaims(claims)
                .setExpiration(expireTime)
                .signWith(SignatureAlgorithm.HS512, jwtProperties.getSecret())
                .compact();
    }
487075
public static Set<Event> evaluateEventForProviderInContext(final Principal principal,
                                                               final RegisteredService service,
                                                               final Optional<RequestContext> context,
                                                               final MultifactorAuthenticationProvider provider) {
        LOGGER.debug("Attempting check for availability of multifactor authentication provider [{}] for [{}]", provider, service);
        if (provider != null) {
            LOGGER.debug("Provider [{}] is successfully verified", provider);
            val id = provider.getId();
            val event = MultifactorAuthenticationUtils.validateEventIdForMatchingTransitionInContext(id, context,
                MultifactorAuthenticationUtils.buildEventAttributeMap(principal, Optional.of(service), provider));
            return CollectionUtils.wrapSet(event);
        }
        LOGGER.debug("Provider could not be verified");
        return new HashSet<>(0);
    }
1348410
public double expiresIn(AuthRequest req) {
        String val = tokenStore.get(req.asString());
        return val == null ? Double.NEGATIVE_INFINITY :
                Double.valueOf(TokenInfo.fromString(val).getExpires()) - clock.now();
    }
938367
public static Optional<Principal> withWebIdClaim(final Claims claims) {
        final String webid = claims.get(WEBID, String.class);
        if (webid == null) return empty();
        LOGGER.debug("Using JWT claim with webid: {}", webid);
        return of(new OAuthPrincipal(webid));
    }