/*
This method is the main method calling by the WebAuthenticatorProxy to handle TAI and SSO
503536
@Override
    public AuthenticationResult authenticate(WebRequest webRequest) {
        AuthenticationResult authResult = handleTAI(webRequest, true);
        if ((authResult.getStatus() == AuthResult.CONTINUE) && continueAfterUnprotectedURI(webRequest)) {
            authResult = handleSSO(webRequest, null);
            if (authResult.getStatus() == AuthResult.CONTINUE) {
                webRequest.setCallAfterSSO(true);
                authResult = handleTAI(webRequest, false);
            }
        }

        return authResult;

    }
760710
private AuthenticationResult handleFormLogin(HttpServletRequest req, HttpServletResponse res, WebRequest webRequest) {
        AuthenticationResult authResult = null;
        authResult = ssoAuthenticator.authenticate(webRequest);

        if (authResult != null) {
            authResult.setAuditCredType(AuditEvent.CRED_TYPE_FORM);
        }

        if (authResult != null && authResult.getStatus() != AuthResult.FAILURE) {
            postParameterHelper.restore(req, res);
            return authResult;
        }

        try {
            authResult = providerAuthenticatorProxy.authenticate(req, res, null);
        } catch (Exception e) {
            return new AuthenticationResult(AuthResult.FAILURE, e.getLocalizedMessage());
        }

        if (authResult.getStatus() == AuthResult.CONTINUE) {
            authResult = null;
            if (webRequest.isFormLoginRedirectEnabled()) {
                authResult = handleRedirect(req, res, webRequest);
                if (authResult != null) {
                    authResult.setAuditCredType(AuditEvent.CRED_TYPE_FORM);
                    authResult.setAuditOutcome(AuditEvent.OUTCOME_REDIRECT);
                }

            }
        }
        return authResult;
    }
1287464
@Override
    public void handleResponse(final HttpProxyResponse response)
            throws ProxyAuthException {
        if (!isHandshakeComplete()
                && ("close".equalsIgnoreCase(StringUtilities
                        .getSingleValuedHeader(response.getHeaders(),
                                "Proxy-Connection")) || "close"
                        .equalsIgnoreCase(StringUtilities
                                .getSingleValuedHeader(response.getHeaders(),
                                        "Connection")))) {
            getProxyIoSession().setReconnectionNeeded(true);
        }

        if (response.getStatusCode() == 407) {
            if (authHandler == null) {
                autoSelectAuthHandler(response);
            }
            authHandler.handleResponse(response);
        } else {
            throw new ProxyAuthException("Error: unexpected response code "
                    + response.getStatusLine() + " received from proxy.");
        }
    }
92515
public void start()
        throws Exception
    {
        if (getHttpContext().getAuthenticator()==null)
        {
            // Find out the Authenticator.
            if (SecurityConstraint.__BASIC_AUTH.equalsIgnoreCase(_authMethod))
                getHttpContext().setAuthenticator(new BasicAuthenticator());
            else if (SecurityConstraint.__CERT_AUTH.equalsIgnoreCase(_authMethod))
                getHttpContext().setAuthenticator(new ClientCertAuthenticator());
            else
                log.warn("Unknown Authentication method:"+_authMethod);
        }
        
        super.start();
    }
324366
public static @Nonnull Authentication getAuthentication() {
        Authentication a = SecurityContextHolder.getContext().getAuthentication();
        // on Tomcat while serving the login page, this is null despite the fact
        // that we have filters. Looking at the stack trace, Tomcat doesn't seem to
        // run the request through filters when this is the login request.
        // see http://www.nabble.com/Matrix-authorization-problem-tp14602081p14886312.html
        if(a==null)
            a = ANONYMOUS;
        return a;
    }
616343
@Override
    public synchronized void processAuthorize(WebSocketChannel channel, String authorizeToken) {
        nextHandler.processAuthorize(channel, authorizeToken); 
    }
227247
@FFDCIgnore({ com.ibm.ws.security.authentication.AuthenticationException.class })
    @Override
    public AuthenticationResult authenticate(WebRequest webRequest) {
        Subject sessionSubject = null;
        JaspiRequest jaspiRequest = new JaspiRequest(webRequest, null);
        // can set authenticate method here if webrequest has no websecuritycontext
        AuthenticationResult result = null;
        AuthConfigProvider provider = getAuthConfigProvider(jaspiRequest.getAppContext());

        if (provider != null) {
            try {
                if (jaspiRequest.getWebSecurityContext() != null) {
                    JaspiAuthContext jaspiContext = getJaspiAuthContext(jaspiRequest, provider);
                    webRequest.getWebSecurityContext().setJaspiAuthContext(jaspiContext);
                }
                // if we have a jaspi session subject from a previous request
                // then set it as the current subject (both caller and invocation)
                sessionSubject = getSessionSubject(jaspiRequest);
                if (sessionSubject != null) {
                    SubjectManager sm = new SubjectManager();
                    sm.setCallerSubject(sessionSubject);
                    sm.setInvocationSubject(sessionSubject);
                }
                result = authenticate(new Subject(),
                                      getJaspiAuthType(jaspiRequest),
                                      jaspiRequest,
                                      provider);

            } catch (AuthenticationException e) {
                if (tc.isDebugEnabled())
                    Tr.debug(tc, "Internal error during JASPI authentication", e);
                if (result == null)
                    result = new AuthenticationResult(AuthResult.FAILURE, e.getMessage());
            }
        } else {
            result = new AuthenticationResult(AuthResult.CONTINUE, "No JASPIC provider found for request: " + webRequest.getHttpServletRequest().getRequestURI());
        }

        if (provider != null && provider.getClass() != null) {
            result.setAuditAuthConfigProviderName(provider.getClass().toString());
            result.setAuditAuthConfigProviderAuthType(getRequestAuthType(jaspiRequest.getHttpServletRequest(), "AUTH_TYPE"));
        }
        return result;
    }
1160429
private void handleAuthenticationType(final Object authenticationType) {
		if (request != null) {
			if (authenticationType != null) {
				// be defensive
				if (!(authenticationType instanceof String)) {
					final String message = "Attribute "
							+ HttpContext.AUTHENTICATION_TYPE
							+ " expected to be a String but was an ["
							+ authenticationType.getClass() + "]";
					LOG.error(message);
					throw new IllegalArgumentException(message);
				}
			}
			getOsgiAuth().setAuthMethod((String) authenticationType);
		} else {
			LOG.warn("Authentication type cannot be set to "
					+ authenticationType
					+ ". HttpService specific authentication is disabled because the ServletRequest object cannot be used: "
					+ "Expected to be an instance of "
					+ Request.class.getName() + " but got "
					+ originalRequest.getClass().getName() + ".");
		}
	}
372995
@Override
    @Transactional(value = "transactionManager", readOnly = true)
    public Authentication authenticate(Authentication authentication)
        throws AuthenticationException {

        // prepare an exception
        final String exceptionMessage = "User and password do not match.";

        // get username/password
        String accountName = authentication.getName();
        String rawPassword = (String) authentication.getCredentials();

        LOG.debug("Trying to authenticate User '" + accountName + "'");

        User user = userDao.findByAccountName(accountName);

        // prepare set of authorities
        Set<GrantedAuthority> grantedAuthorities = new HashSet<GrantedAuthority>();

        String encryptedPassword = null;

        if (user == null) {
            LOG.warn("No user for account name '" + accountName + "' could be found.");
            throw new UsernameNotFoundException(exceptionMessage);
        } else if (!user.isActive()) {
            LOG.warn("The user with the account name '" + accountName + "' is not active.");
            throw new DisabledException(exceptionMessage);
        } else {

            encryptedPassword = user.getPassword();

            // check if rawPassword matches the hash from db
            if (passwordEncoder.matches(rawPassword, encryptedPassword)) {

                Set<Role> allUserRoles = getAllUserRoles(user);

                // create granted authorities for the security context
                for (Role role : allUserRoles) {
                    grantedAuthorities.add(new SimpleGrantedAuthority(role.getName()));
                }

            } else {
                LOG.warn("The given password for user '" + accountName + "' does not match.");
                throw new BadCredentialsException(exceptionMessage);
            }

        }

        // Create corresponding token to forward in Spring Security's filter
        // chain. We will use the SHOGun-Core user as the principal.
        Authentication authResult = null;
        if (grantedAuthorities.isEmpty()) {
            // if the user has no authorities, we will build the
            // UsernamePasswordAuthenticationToken without authorities, which
            // leads to an unauthenticated user, i.e. isAuthenticated() of
            // authenticationToken will return false afterwards.
            LOG.warn("The user '" + accountName + "' has no authorities and will thereby NOT be authenticated.");
            authResult = new UsernamePasswordAuthenticationToken(user, encryptedPassword);
        } else {
            // if we pass some grantedAuthorities, isAuthenticated() of
            // authenticationToken will return true afterwards
            authResult = new UsernamePasswordAuthenticationToken(user, encryptedPassword, grantedAuthorities);

            LOG.debug("The user '" + accountName
                + "' got the following (explicit) roles: "
                + StringUtils.join(getRawRoleNames(grantedAuthorities), ", "));
        }

        final boolean isAuthenticated = authResult.isAuthenticated();
        final String authLog = isAuthenticated ? "has succesfully" : "has NOT";
        LOG.info("The user '" + accountName + "' " + authLog + " been authenticated.");

        return authResult;
    }
374631
public void setAuthenticationToken(Authentication authentication) {
        if( logger.isDebugEnabled() ) {
            logger.debug( "New authentication token: " + authentication );
        }

        final HttpInvokerRequestExecutor hire = getHttpInvokerRequestExecutor();
        if( hire instanceof BasicAuthHttpInvokerRequestExecutor ) {
            if( logger.isDebugEnabled() ) {
                logger.debug( "Pass it along to executor" );
            }
            ((BasicAuthHttpInvokerRequestExecutor) hire).setAuthenticationToken( authentication );
        }
    }
338190
@Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        String methodName = method.getName();
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            Tr.entry(this, tc, methodName, args);
        Object r = null;
        try {
            if (args == null || args.length == 0) {
                if ("canRegisterSynchronization".equals(methodName))
                    r = canRegisterSynchronization();
                else if ("getCurrentStatus".equals(methodName))
                    r = getCurrentStatus();
                else if ("hashCode".equals(methodName))
                    r = System.identityHashCode(this);
                else if ("retrieveTransactionManager".equals(methodName))
                    r = retrieveTransactionManager();
                else if ("retrieveUserTransaction".equals(methodName))
                    r = retrieveUserTransaction();
                else if ("toString".equals(methodName))
                    r = new StringBuilder(getClass().getName()).append('@').append(Integer.toHexString(System.identityHashCode(this))).toString();
            } else {
                if ("equals".equals(methodName))
                    r = proxy == args[0]; // assumes one proxy per invocation handler
                else if ("getTransactionIdentifier".equals(methodName))
                    r = getTransactionIdentifier((Transaction) args[0]);
                else if ("registerSynchronization".equals(methodName))
                    registerSynchronization((Synchronization) args[0]);
            }
        } catch (Throwable x) {
            if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
                Tr.exit(this, tc, methodName, x);
            throw x;
        }

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            Tr.exit(this, tc, methodName, r);
        return r;
    }
1279517
private void afterExecute(HttpMethod method) throws IOException {
        AuthState hostAuthState = method.getHostAuthState();
        if (hostAuthState.isPreemptive() || hostAuthState.isAuthAttempted()) {
            AuthScheme authScheme = hostAuthState.getAuthScheme();

            if (authScheme instanceof SpnegoAuthScheme && settings.getNetworkSpnegoAuthMutual()) {
                // Perform Mutual Authentication
                SpnegoAuthScheme spnegoAuthScheme = ((SpnegoAuthScheme) authScheme);
                Map challenges = AuthChallengeParser.parseChallenges(method.getResponseHeaders(WWW_AUTHENTICATE));
                String id = spnegoAuthScheme.getSchemeName();
                String challenge = (String) challenges.get(id.toLowerCase());
                if (challenge == null) {
                    throw new IOException(id + " authorization challenge expected, but not found");
                }
                spnegoAuthScheme.ensureMutualAuth(challenge);
            }
        }
    }
989843
private WebReply unprotectedSpecialURI(WebRequest webRequest, String uriName, String methodName) {
        LoginConfiguration loginConfig = webRequest.getLoginConfig();
        if (loginConfig == null)
            return null;

        String authenticationMethod = loginConfig.getAuthenticationMethod();
        FormLoginConfiguration formLoginConfig = loginConfig.getFormLoginConfiguration();
        if (formLoginConfig == null || authenticationMethod == null)
            return null;

        String loginPage = formLoginConfig.getLoginPage();
        String errorPage = formLoginConfig.getErrorPage();

        // We check to see if we are either a FORM or CLIENT_CERT auth method.
        // These are the only valid auth methods supported (CLIENT_CERT can
        // fail over to FORM).
        if (isValidAuthMethodForFormLogin(authenticationMethod) && loginPage != null && errorPage != null) {
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(tc, " We have a custom login or error page request, web app login URL:[" + loginPage
                             + "], errorPage URL:[" + errorPage + "], and the requested URI:[" + uriName + "]");
            }
            if (loginPage.equals(uriName) || errorPage.equals(uriName)) {
                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
                    Tr.debug(tc, "authorize, login or error page[" + uriName + "]  requested, permit: ", PERMIT_REPLY);
                return PERMIT_REPLY;
            } else if ((uriName != null && uriName.equals("/j_security_check")) &&
                       (methodName != null && methodName.equals("POST"))) {
                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
                    Tr.debug(tc, "authorize, login or error page[" + uriName + "]  requested, permit: ", PERMIT_REPLY);
                return PERMIT_REPLY;
            }
        } else {
            if (webRequest.getHttpServletRequest().getDispatcherType().equals(DispatcherType.ERROR)) {
                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
                    Tr.debug(tc, "authorize, error page[" + uriName + "]  requested, permit: ", PERMIT_REPLY);
                return PERMIT_REPLY;
            }
        }
        return null;
    }
735534
public static HttpResponse execute(final String url, final String method,
                                       final String basicAuthUsername,
                                       final String basicAuthPassword) {
        return execute(url, method, basicAuthUsername, basicAuthPassword, new HashMap<>(), new HashMap<>());
    }
552473
public HttpClientBuilder basicAuth(String username, String password) {
		basicAuthUsername = username;
		basicAuthPassword = password;
		return this;
	}
770732
@Override
	public ProxyAuthenticationMethod getMethod() {
		switch (authenticationMethod) {
		case BASIC:
			return ProxyAuthenticationMethod.BASIC;
		case DIGEST:
			return ProxyAuthenticationMethod.DIGEST;
		case URL:
			return ProxyAuthenticationMethod.URL;
		default:
			return null;
		}
	}
1192418
private void generateAuthenticationEvent(HttpServletRequest request, HttpServletResponse response) {
    try {
      Optional<JwtHttpHandler.Token> token = jwtHttpHandler.getToken(request, response);
      String userLogin = token.isPresent() ? token.get().getUserDto().getLogin() : null;
      authenticationEvent.logoutSuccess(request, userLogin);
    } catch (AuthenticationException e) {
      authenticationEvent.logoutFailure(request, e.getMessage());
    }
  }