Resolve principal.

@param handler    the handler name
@param resolver   the resolver
@param credential the credential
@param principal  the current authenticated principal from a handler, if any.
@return the principal
174002
protected Principal resolvePrincipal(final AuthenticationHandler handler, final PrincipalResolver resolver,
                                         final Credential credential, final Principal principal) {
        if (resolver.supports(credential)) {
            try {
                val p = resolver.resolve(credential, Optional.ofNullable(principal), Optional.ofNullable(handler));
                LOGGER.debug("[{}] resolved [{}] from [{}]", resolver, p, credential);
                return p;
            } catch (final Exception e) {
                LOGGER.error("[{}] failed to resolve principal from [{}]", resolver, credential, e);
            }
        } else {
            LOGGER.warn(
                "[{}] is configured to use [{}] but it does not support [{}], which suggests a configuration problem.",
                handler.getName(), resolver, credential);
        }
        return null;
    }
547743
private static <CT, I> Function<CT, I> resolveAndExtend(
		Class<CT> contextType,
		List<MethodResolver<CT>> resolvers,
		Class<I> typeToExtend)
	{
		// Resolve generics
		ResolvedTypeWithMembers withMembers = Types.resolveMembers(typeToExtend);

		Map<Method, MethodInvocationHandler<CT>> handlers = new HashMap<>();
		try
		{
			// Go through methods and create invokers for each of them
			for(ResolvedMethod method : withMembers.getMemberMethods())
			{
				// Only try to implement abstract methods
				if(! method.isAbstract()) continue;

				// Create an encounter and let the first method resolver that matches handle the method
				boolean foundInvoker = false;
				MethodEncounter encounter = new MethodEncounterImpl(method);
				for(MethodResolver<CT> resolver : resolvers)
				{
					Optional<MethodInvocationHandler<CT>> opt = resolver.create(encounter);
					if(opt.isPresent())
					{
						// This resolver created an invoker to use
						foundInvoker = true;
						handlers.put(method.getRawMember(), opt.get());
						break;
					}
				}

				if(! foundInvoker)
				{
					// No invoker was found, can not handle the method
					throw new ProxyException("The method " + method.getName() + " could not be handled");
				}
			}
		}
		catch(ProxyException e)
		{
			throw new ProxyException(typeToExtend.getName() + ":\n" + e.getMessage());
		}
		catch(Exception e)
		{
			throw new ProxyException(typeToExtend.getName() + ":\n" + e.getMessage(), e);
		}

		return createFunction(contextType, typeToExtend, Collections.unmodifiableMap(handlers));
	}
118912
public Principal authenticate(String username,
                                  Object credentials,
                                  HttpRequest request)
    {

    	synchronized(this)
    	{
    		long now = System.currentTimeMillis();
    		if (now - _lastHashPurge > _cacheTime || _cacheTime == 0)
    		{
    			super.clear();
    			_roles.clear();
    			_lastHashPurge = now;
    		}
    		Principal user = (Principal)super.get(username);
    		if (user == null)
    		{
    			loadUser(username);
    			user = (Principal)super.get(username);
    		}
    	}
        return super.authenticate(username, credentials, request);
    }
1283710
public I_CmsPrincipal lookupPrincipal(CmsRequestContext context, CmsUUID principalId) {

        CmsDbContext dbc = m_dbContextFactory.getDbContext(context);
        I_CmsPrincipal result = null;
        try {
            result = m_driverManager.lookupPrincipal(dbc, principalId);
        } finally {
            dbc.clear();
        }
        return result;
    }
725191
public String getPrincipal() {
        String principal = target.getPrincipal();
        if (StringUtils.hasText(principal)) {
            return principal;
        } else {
            return defaultUser;
        }
    }
1097733
private Principal getPrincipalUser(String className) throws LoginException {
    // load the principal class
    ClassLoader loader = Thread.currentThread().getContextClassLoader();
    if (loader == null) {
      loader = ClassLoader.getSystemClassLoader();
    }

    Class<? extends Principal> clazz;
    try {
      // Declare a temp variable so that we can suppress warnings locally
      @SuppressWarnings("unchecked")
      Class<? extends Principal> tmpClazz =
          (Class<? extends Principal>) loader.loadClass(className);
      clazz = tmpClazz;
    } catch (ClassNotFoundException e) {
      throw new LoginException("Unable to find JAAS principal class:" + e.getMessage());
    }

    // find corresponding user based on the principal
    Set<? extends Principal> userSet = mSubject.getPrincipals(clazz);
    if (!userSet.isEmpty()) {
      if (userSet.size() == 1) {
        return userSet.iterator().next();
      }
      throw new LoginException("More than one instance of Principal " + className + " is found");
    }
    return null;
  }
1151325
protected String callRestEndpointForMultifactor(final Principal principal, final Service resolvedService) {
        val restTemplate = new RestTemplate();
        val restEndpoint = casProperties.getAuthn().getMfa().getRestEndpoint();
        val entity = new RestEndpointEntity(principal.getId(), resolvedService.getId());
        val responseEntity = restTemplate.postForEntity(restEndpoint, entity, String.class);
        if (responseEntity.getStatusCode() == HttpStatus.OK) {
            return responseEntity.getBody();
        }
        return null;
    }
1180710
public static void setCurrentActionResolver( ActionResolver resolver, HttpServletRequest request,
                                                 ServletContext servletContext )
    {
        StorageHandler sh = Handlers.get( servletContext ).getStorageHandler();
        HttpServletRequest unwrappedRequest = PageFlowUtils.unwrapMultipart( request );
        RequestContext rc = new RequestContext( unwrappedRequest, null );
        String currentJpfAttrName =
            ScopedServletUtils.getScopedSessionAttrName( CURRENT_JPF_ATTR, unwrappedRequest );
        String currentLongLivedJpfAttrName =
                ScopedServletUtils.getScopedSessionAttrName( CURRENT_LONGLIVED_ATTR, unwrappedRequest );

        //
        // This case occurs when the previous page flow is no longer active and there is no new page flow
        //
        if ( resolver == null )
        {
            sh.removeAttribute( rc, currentJpfAttrName );
            sh.removeAttribute( rc, currentLongLivedJpfAttrName );
            return;
        }

        //
        // If this is a long-lived page flow, also store the instance in an attribute that never goes away.
        //
        if ( resolver.isPageFlow() && isLongLived( ( ( PageFlowController ) resolver ).theModuleConfig() ) )
        {
            String longLivedAttrName = getLongLivedFlowAttr( resolver.getModulePath() );
            longLivedAttrName = ScopedServletUtils.getScopedSessionAttrName( longLivedAttrName, unwrappedRequest );

            // Only set this attribute if it's not already there.  We want to avoid our onDestroy() callback that's
            // invoked when the page flow's session attribute is unbound.
            if ( sh.getAttribute( rc, longLivedAttrName ) != resolver )
            {
                sh.setAttribute( rc, longLivedAttrName, resolver );
            }

            sh.setAttribute( rc, currentLongLivedJpfAttrName, resolver.getModulePath() );
            sh.removeAttribute( rc, currentJpfAttrName );
        }
        //
        // Default case for removing a previous page flow in the presence of a new page flow.
        //
        else
        {
            sh.setAttribute( rc, currentJpfAttrName, resolver );
            sh.removeAttribute( rc, currentLongLivedJpfAttrName );
        }
    }
259650
public static URIResolver createSAXURIResolver(Resolver resolver) {
    final SAXResolver saxResolver = new SAXResolver(resolver);
    return new URIResolver() {
      public Source resolve(String href, String base) throws TransformerException {
        try {
          return saxResolver.resolve(href, base);
        }
        catch (SAXException e) {
          throw toTransformerException(e);
        }
        catch (IOException e) {
          throw new TransformerException(e);
        }
      }
    };
  }
967331
public RequestToken changePassword(String password, BaasHandler<Void> handler) {
        return changePassword(password, RequestOptions.DEFAULT, handler);
    }
1208161
@RequestMapping(value = "/deletePermission", method = RequestMethod.POST)
    public void deletePermission(
            @RequestParam("principal") String principal,
            @RequestParam("owner") String owner,
            @RequestParam("activity") String activity,
            @RequestParam("target") String target,
            HttpServletRequest request,
            HttpServletResponse response)
            throws Exception {

        // ensure the current user is authorized to update and view permissions
        final IPerson currentUser = personManager.getPerson((HttpServletRequest) request);

        if (!permissionAdministrationHelper.canEditPermission(currentUser, target)
                || !permissionAdministrationHelper.canViewPermission(currentUser, target)) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }
        JsonEntityBean bean = groupListHelper.getEntityForPrincipal(principal);

        if (bean != null) {

            IAuthorizationPrincipal p = groupListHelper.getPrincipalForEntity(bean);

            IPermission[] directPermissions =
                    permissionStore.select(owner, p.getPrincipalString(), activity, target, null);
            this.authorizationService.removePermissions(directPermissions);

        } else {
            log.warn(
                    "Unable to resolve the following principal (will "
                            + "be omitted from the list of assignments):  "
                            + principal);
        }

        response.setStatus(HttpServletResponse.SC_OK);
        return;
    }
463663
@Override
    public PrincipalUser getUser(String username, String password) {
        requireNotDisposed();
        requireArgument(_isUsernameValid(username), MessageFormat.format("Invalid username: {0}", username));

        PrincipalUser result = null;
        String userDn = _findDNForUser(username);

        if (userDn != null && password != null) {
            result = _findPrincipalUser(userDn, username, password);
        }
        return result;
    }
1114779
protected Principal getPrincipal() {
        final Object principal = requestContext.getProperty("Principal");
        if (principal != null) {
            return (Principal) principal;
        } else {
            return null;
        }
    }
216764
public final TcpClient resolver(AddressResolverGroup<?> resolver) {
		Objects.requireNonNull(resolver, "resolver");
		return bootstrap(b -> b.resolver(resolver));
	}
1349454
public I_CmsPrincipal lookupPrincipal(CmsRequestContext context, String principalName) {

        CmsDbContext dbc = m_dbContextFactory.getDbContext(context);
        I_CmsPrincipal result = null;
        try {
            result = m_driverManager.lookupPrincipal(dbc, CmsOrganizationalUnit.removeLeadingSeparator(principalName));
        } finally {
            dbc.clear();
        }
        return result;
    }
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;
    }
387247
public final UdpServer handle(BiFunction<? super UdpInbound, ? super UdpOutbound, ? extends Publisher<Void>> handler) {
		Objects.requireNonNull(handler, "handler");
		return doOnBound(c -> {
			if (log.isDebugEnabled()) {
				log.debug(format(c.channel(), "Handler is being applied: {}"), handler);
			}

			Mono.fromDirect(handler.apply((UdpInbound) c, (UdpOutbound) c))
			    .subscribe(c.disposeSubscriber());
		});
	}