Restore authentication request in context service (return null for a logout call).

@param requestContext the request context
@param webContext     the web context
@param clientName     the client name
@return the service
164783
protected Service restoreAuthenticationRequestInContext(final RequestContext requestContext,
                                                            final J2EContext webContext,
                                                            final String clientName) {
        val logoutEndpoint = isLogoutRequest(webContext.getRequest());
        if (logoutEndpoint) {
            return null;
        } else {
            try {
                val client = (BaseClient<Credentials, CommonProfile>) this.clients.findClient(clientName);
                return delegatedClientWebflowManager.retrieve(requestContext, webContext, client);
            } catch (final Exception e) {
                LOGGER.error(e.getMessage(), e);
            }
            throw new UnauthorizedServiceException(UnauthorizedServiceException.CODE_UNAUTHZ_SERVICE, "Service unauthorized");
        }
    }
1127525
@Nullable
    @Override
    protected AuthenticationInfo queryForAuthenticationInfo(
            AuthenticationToken token, LdapContextFactory ldapContextFactory) throws NamingException {
        try {
            return queryForAuthenticationInfo0(token, ldapContextFactory);
        } catch (ServiceUnavailableException e) {
            // It might be a temporary failure, so try again.
            return queryForAuthenticationInfo0(token, ldapContextFactory);
        }
    }
528536
public synchronized HttpContext getHttpContext() {
        if (jolokiaHttpContext == null) {
            final String user = getConfiguration(USER);
            final String authMode = getConfiguration(AUTH_MODE);
            if (user == null) {
                if (ServiceAuthenticationHttpContext.shouldBeUsed(authMode)) {
                    jolokiaHttpContext = new ServiceAuthenticationHttpContext(bundleContext, authMode);
                } else {
                    jolokiaHttpContext = new DefaultHttpContext();
                }
            } else {
                jolokiaHttpContext =
                    new BasicAuthenticationHttpContext(getConfiguration(REALM),
                                                       createAuthenticator(authMode));
            }
        }
        return jolokiaHttpContext;
    }
1263987
protected void validateLogoutRequest(final LogoutRequest logoutRequest, final SAML2MessageContext context,
                                               final SignatureTrustEngine engine) {

        validateSignatureIfItExists(logoutRequest.getSignature(), context, engine);

        // don't check because of CAS v5
        //validateIssueInstant(logoutRequest.getIssueInstant());

        validateIssuerIfItExists(logoutRequest.getIssuer(), context);

        NameID nameId = logoutRequest.getNameID();
        final EncryptedID encryptedID = logoutRequest.getEncryptedID();
        if (encryptedID != null) {
            nameId = decryptEncryptedId(encryptedID, decrypter);
        }

        String sessionIndex = null;
        final List<SessionIndex> sessionIndexes = logoutRequest.getSessionIndexes();
        if (sessionIndexes != null && !sessionIndexes.isEmpty()) {
            final SessionIndex sessionIndexObject = sessionIndexes.get(0);
            if (sessionIndexObject != null) {
                sessionIndex = sessionIndexObject.getSessionIndex();
            }
        }

        final String sloKey = computeSloKey(sessionIndex, nameId);
        if (sloKey != null) {
            final String bindingUri = context.getSAMLBindingContext().getBindingUri();
            if (SAMLConstants.SAML2_SOAP11_BINDING_URI.equals(bindingUri)) {
                logoutHandler.destroySessionBack(context.getWebContext(), sloKey);
            } else {
                logoutHandler.destroySessionFront(context.getWebContext(), sloKey);
            }
        }
    }
652710
protected Event handleException(final J2EContext webContext, final BaseClient<Credentials, CommonProfile> client, final Exception e) {
        if (e instanceof RequestSloException) {
            try {
                webContext.getResponse().sendRedirect("logout");
            } catch (final IOException ioe) {
                throw new IllegalArgumentException("Unable to call logout", ioe);
            }
            return stopWebflow();
        }
        val msg = String.format("Delegated authentication has failed with client %s", client.getName());
        LOGGER.error(msg, e);
        throw new IllegalArgumentException(msg);
    }
87724
protected RegisteredService resolveRegisteredServiceInRequestContext(final RequestContext requestContext) {
        val resolvedService = resolveServiceFromAuthenticationRequest(requestContext);
        if (resolvedService != null) {
            val service = getWebflowEventResolutionConfigurationContext().getServicesManager().findServiceBy(resolvedService);
            RegisteredServiceAccessStrategyUtils.ensureServiceAccessIsAllowed(resolvedService, service);
            return service;
        }
        LOGGER.debug("Authentication request is not accompanied by a service given none is specified");
        return null;
    }
1337451
public void logout(Context context, ResponseListener listener) {
        AuthorizationRequestManager.RequestOptions options = new AuthorizationRequestManager.RequestOptions();
        options.parameters = new HashMap<String,String>(1);
        options.parameters.put("client_id", preferences.clientId.get());
        options.headers = new HashMap<>(1);
        addSessionIdHeader(options.headers);
        options.requestMethod = Request.GET;
        try {
            authorizationRequestSend(context,"logout", options, listener);
        } catch (Exception e) {
            logger.debug("Could not log out");
        }
    }
798753
public static ContentModeratorClient authenticate(AzureRegionBaseUrl baseUrl, ServiceClientCredentials credentials) {
        return authenticate("https://{baseUrl}/", credentials)
                .withBaseUrl(baseUrl);
    }
25989
private String getBearerToken(HttpConnectionInterceptorContext context) {
        final AtomicReference<String> iamTokenResponse = new AtomicReference<String>();
        boolean result = super.requestCookie(context, iamServerUrl, iamTokenRequestBody,
                "application/x-www-form-urlencoded", "application/json",
                new StoreBearerCallable(iamTokenResponse));
        if (result) {
            return iamTokenResponse.get();
        } else {
            return null;
        }
    }
90810
public static RegisteredService getRegisteredService(final RequestContext context) {
        return context != null ? (RegisteredService) context.getFlowScope().get(PARAMETER_REGISTERED_SERVICE) : null;
    }
1017386
protected Optional<C> retrieveCredentials(final WebContext context) {
        try {
            final Optional<C> optCredentials = this.credentialsExtractor.extract(context);
            optCredentials.ifPresent(credentials -> {
                final long t0 = System.currentTimeMillis();
                try {
                    this.authenticator.validate(credentials, context);
                } finally {
                    final long t1 = System.currentTimeMillis();
                    logger.debug("Credentials validation took: {} ms", t1 - t0);
                }
            });
            return optCredentials;
        } catch (CredentialsException e) {
            logger.info("Failed to retrieve or validate credentials: {}", e.getMessage());
            logger.debug("Failed to retrieve or validate credentials", e);

            return Optional.empty();
        }
    }
663072
function (context, authenticationRequest, callback) {
            //
            var authProvider = this.getAuthenticationProviderForRequest(authenticationRequest);

            if (authProvider) {
                flow()
                    .seq("authentication", function (cb) {
                        // authenticate
                        authProvider.authenticate(authenticationRequest, cb);
                    })
                    .seq(function (cb) {
                        // init authentication
                        this.vars.authentication.init(cb);
                    })
                    .exec(function (err, results) {
                        var authentication = results.authentication;
                        if (!err && authentication) {
                            context.user.addAuthentication(authentication);
                        }
                        // return authentication with user id
                        callback(err, authentication);
                    })
            } else {
                callback(AuthenticationError.NO_PROVIDER_FOUND, null);
            }
        }
1366043
public Ticket store(final J2EContext webContext, final BaseClient client) {
        val properties = buildTicketProperties(webContext);

        val originalService = argumentExtractor.extractService(webContext.getRequest());
        val service = authenticationRequestServiceSelectionStrategies.resolveService(originalService);
        properties.put(CasProtocolConstants.PARAMETER_SERVICE, originalService);
        properties.put(CasProtocolConstants.PARAMETER_TARGET_SERVICE, service);

        val transientFactory = (TransientSessionTicketFactory) this.ticketFactory.get(TransientSessionTicket.class);
        val ticket = transientFactory.create(originalService, properties);
        val ticketId = ticket.getId();
        LOGGER.debug("Storing delegated authentication request ticket [{}] for service [{}] with properties [{}]",
            ticketId, ticket.getService(), ticket.getProperties());
        this.ticketRegistry.addTicket(ticket);
        webContext.setRequestAttribute(PARAMETER_CLIENT_ID, ticketId);

        val sessionStore = webContext.getSessionStore();
        if (client instanceof SAML2Client) {
            sessionStore.set(webContext, SAML2StateGenerator.SAML_RELAY_STATE_ATTRIBUTE, ticketId);
        }
        if (client instanceof OAuth20Client) {
            val oauthClient = (OAuth20Client) client;
            val config = oauthClient.getConfiguration();
            config.setWithState(true);
            config.setStateGenerator(new StaticOrRandomStateGenerator(ticketId));
        }
        if (client instanceof OidcClient) {
            val oidcClient = (OidcClient) client;
            val config = oidcClient.getConfiguration();
            config.addCustomParam(PARAMETER_CLIENT_ID, ticketId);
            config.setWithState(true);
            config.setStateGenerator(new StaticOrRandomStateGenerator(ticketId));
        }
        if (client instanceof CasClient) {
            val casClient = (CasClient) client;
            val config = casClient.getConfiguration();
            config.addCustomParam(DelegatedClientWebflowManager.PARAMETER_CLIENT_ID, ticketId);
        }
        if (client instanceof OAuth10Client) {
            sessionStore.set(webContext, OAUTH10_CLIENT_ID_SESSION_KEY, ticket.getId());
        }
        return ticket;
    }
975086
public Principal authenticate(String username,
                                  Object credentials,
                                  HttpRequest request)
    {
        KnownUser user;
        synchronized (this)
        {
            user = (KnownUser)super.get(username);
        }
        if (user==null)
            return null;

        if (user.authenticate(credentials))
            return user;
        
        return null;
    }
718052
public static Authentication getCurrentAuthentication() {
        RequestContext context = RequestContext.getCurrent();
        if (context != null) {
            return getAuthentication(context.getRequest());
        } else {
            return null;
        }
    }
78388
public static HttpServletRequest getHttpServletRequestFromExternalWebflowContext(final RequestContext context) {
        Assert.isInstanceOf(ServletExternalContext.class, context.getExternalContext(),
            "Cannot obtain HttpServletRequest from event of type: "
                + context.getExternalContext().getClass().getName());

        return (HttpServletRequest) context.getExternalContext().getNativeRequest();
    }
163306
public static Credential getCredential(final RequestContext context) {
        val cFromRequest = (Credential) context.getRequestScope().get(PARAMETER_CREDENTIAL);
        val cFromFlow = (Credential) context.getFlowScope().get(PARAMETER_CREDENTIAL);
        val cFromConversation = (Credential) context.getConversationScope().get(PARAMETER_CREDENTIAL);

        var credential = cFromRequest;
        if (credential == null || StringUtils.isBlank(credential.getId())) {
            credential = cFromFlow;
        }
        if (credential == null || StringUtils.isBlank(credential.getId())) {
            credential = cFromConversation;
            if (credential != null && !StringUtils.isBlank(credential.getId())) {
                context.getFlowScope().put(PARAMETER_CREDENTIAL, credential);
            }
        }

        if (credential == null) {
            val session = context.getFlowExecutionContext().getActiveSession();
            credential = session.getScope().get(PARAMETER_CREDENTIAL, Credential.class);
        }
        if (credential != null && StringUtils.isBlank(credential.getId())) {
            return null;
        }
        return credential;
    }