Build with predefined renew and gateway parameters.

@param casClient the cas client config
@param context   the context
@param renew     ask for credentials again
@param gateway   skip asking for credentials
@return the redirect action
354958
protected RedirectAction build(final CasClient casClient, final WebContext context, final boolean renew, final boolean gateway) {
        val serviceUrl = casClient.computeFinalCallbackUrl(context);
        val casServerLoginUrl = casClient.getConfiguration().getLoginUrl();
        val redirectionUrl = casServerLoginUrl + (casServerLoginUrl.contains("?") ? "&" : "?")
            + CasProtocolConstants.PARAMETER_SERVICE + '=' + EncodingUtils.urlEncode(serviceUrl)
            + (renew ? '&' + CasProtocolConstants.PARAMETER_RENEW + "=true" : StringUtils.EMPTY)
            + (gateway ? '&' + CasProtocolConstants.PARAMETER_GATEWAY + "=true" : StringUtils.EMPTY);
        LOGGER.debug("Final redirect url is [{}]", redirectionUrl);
        return RedirectAction.redirect(redirectionUrl);
    }
1113676
protected void activate(ComponentContext context) {
        securityServiceRef.activate(context);
        unauthSubjectServiceRef.activate(context);
        authServiceRef.activate(context);
        credServiceRef.activate(context);
    }
1336999
public void activate(ComponentContext cc) {
        executorServiceRef.activate(cc);
        contextServiceRef.activate(cc);
        ReactiveStreamsFactoryResolver.setInstance(new ReactiveStreamsFactoryImpl());
        ReactiveStreamsEngineResolver.setInstance(this);
        singleton = this;
    }
1200936
@Override
  public void renew(Map stageCredentials) throws SnowflakeSQLException
  {
    stageInfo.setCredentials(stageCredentials);
    setupAzureClient(stageInfo, encMat);
  }
397731
@Subscribe
    @SneakyThrows
    public final synchronized void renew(final DataSourceChangedEvent dataSourceChangedEvent) {
        dataSource.close();
        dataSource = new MasterSlaveDataSource(
                DataSourceConverter.getDataSourceMap(dataSourceChangedEvent.getDataSourceConfigurations()), dataSource.getMasterSlaveRule(), dataSource.getShardingProperties().getProps());
    }
850575
@Trivial
    protected void activate(ComponentContext context) throws Exception {
        Dictionary<String, ?> props = context.getProperties();
        final boolean trace = TraceComponent.isAnyTracingEnabled();
        if (trace && tc.isEntryEnabled())
            Tr.entry(this, tc, "activate", props);

        String sourcePID = (String) props.get("ibm.extends.source.pid"); // com.ibm.ws.jca.jmsQueueConnectionFactory_gen_3f3cb305-4146-41f9-8a57-b231d09013e6
        configElementName = sourcePID == null ? "connectionFactory" : sourcePID.substring(15, sourcePID.indexOf('_', 15));

        cfInterfaceNames = props.get("creates.objectClass");
        mcfImplClassName = (String) props.get(CONFIG_PROPS_PREFIX + "managedconnectionfactory-class");
        jndiName = (String) props.get(JNDI_NAME);
        id = (String) props.get("config.displayId");

        componentContext = context;
        isServerDefined = true; // We don't support app-defined connection factories yet

        //Integer trlevel = props.get("transactionSupport");
        if (props.get("transactionSupport") != null)
            connectionFactoryTransactionSupport = TransactionSupportLevel.valueOf((String) props.get("transactionSupport"));

        // filter out actual config properties for the connection factory
        for (Enumeration<String> keys = props.keys(); keys.hasMoreElements();) {
            String key = keys.nextElement();
            if (key.length() > CONFIG_PROPS_PREFIX_LENGTH && key.charAt(CONFIG_PROPS_PREFIX_LENGTH - 1) == '.' && key.startsWith(CONFIG_PROPS_PREFIX)) {
                String propName = key.substring(CONFIG_PROPS_PREFIX_LENGTH);
                if (propName.indexOf('.') < 0 && propName.indexOf('-') < 0)
                    properties.put(propName, props.get(key));
            }
        }

        bootstrapContextRef.activate(context);

        if (trace && tc.isEntryEnabled())
            Tr.exit(this, tc, "activate");
    }
692784
public OAuthAccessToken refreshToken(RequestContext requestContext, OAuthAccessToken token) {
    OAuthAccessToken result = token;
    
    String[] scopes = token.getScopes();
    String tokenUrl = String.format("%s/realms/%s/protocol/openid-connect/token", getServerUrl(), getRealm());
    
    HttpPost httpPost = new HttpPost(tokenUrl);
    
    try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
      List<NameValuePair> params = new ArrayList<NameValuePair>();
      params.add(new BasicNameValuePair("client_id", getApiKey()));
      params.add(new BasicNameValuePair("client_secret", getApiSecret()));
      params.add(new BasicNameValuePair("grant_type", "refresh_token"));
      params.add(new BasicNameValuePair("refresh_token", token.getRefreshToken()));

      httpPost.setEntity(new UrlEncodedFormEntity(params));
      try (CloseableHttpResponse response = httpclient.execute(httpPost)) {
        StatusLine statusLine = response.getStatusLine();
        
        if (statusLine.getStatusCode() == 200) {
          HttpEntity entity = response.getEntity();
          
          ObjectMapper objectMapper = new ObjectMapper();
          try (InputStream stream = entity.getContent()) {
            RefreshTokenResponse refreshTokenResponse = objectMapper.readValue(stream, RefreshTokenResponse.class);
            Date expiresAt = getExpiresAt(refreshTokenResponse.getExpiresIn());
            result = new OAuthAccessToken(token.getExternalId(), refreshTokenResponse.getAccessToken(), refreshTokenResponse.getRefreshToken(), expiresAt, scopes);
            AuthUtils.purgeOAuthAccessTokens(requestContext, getName());
            AuthUtils.storeOAuthAccessToken(requestContext, getName(), result);            
          }
          
          EntityUtils.consume(entity);
        } else {
          logger.log(Level.WARNING, String.format("Failed to refresh access token with message [%d]: %s", statusLine.getStatusCode(), statusLine.getReasonPhrase()));
        }
      }
    } catch (IOException e) {
      logger.log(Level.WARNING, "Failed to refresh access token", e);
    }
    
    return result;
  }
1150143
@Deprecated
    public static SslContext newClientContext(SslProvider provider) throws SSLException {
        return newClientContext(provider, null, null);
    }
579341
protected URI determineUnauthorizedServiceRedirectUrl(final RequestContext context) {
        val redirectUrl = WebUtils.getUnauthorizedRedirectUrlFromFlowScope(context);
        val currentEvent = context.getCurrentEvent();
        val eventAttributes = currentEvent.getAttributes();
        LOGGER.debug("Finalizing the unauthorized redirect URL [{}] when processing event [{}] with attributes [{}]",
            redirectUrl, currentEvent.getId(), eventAttributes);
        return redirectUrl;
    }
281854
public ArrayList<OvhRenewDescription> serviceId_renew_GET(String serviceId, Boolean includeOptions) throws IOException {
		String qPath = "/service/{serviceId}/renew";
		StringBuilder sb = path(qPath, serviceId);
		query(sb, "includeOptions", includeOptions);
		String resp = exec(qPath, "GET", sb.toString(), null);
		return convertTo(resp, t2);
	}
62785
protected LoginContext getLoginContext(final UsernamePasswordCredential credential) throws GeneralSecurityException {
        val callbackHandler = new UsernamePasswordCallbackHandler(credential.getUsername(), credential.getPassword());
        if (this.loginConfigurationFile != null && StringUtils.isNotBlank(this.loginConfigType)
            && this.loginConfigurationFile.exists() && this.loginConfigurationFile.canRead()) {
            final Configuration.Parameters parameters = new URIParameter(loginConfigurationFile.toURI());
            val loginConfig = Configuration.getInstance(this.loginConfigType, parameters);
            return new LoginContext(this.realm, null, callbackHandler, loginConfig);
        }
        return new LoginContext(this.realm, callbackHandler);
    }
892492
public String setRedirectUrlIfNotDefined(HttpServletRequest req, ConvergedClientConfig clientConfig) {
        //String redirect_url = clientConfig.getRedirectUrlFromServerToClient();
        String redirect_url = null;
        // in oidc case, configimpl completely builds this url, in social we need to finish building it.
        if (clientConfig.isSocial()) {
            redirect_url = getRedirectUrlFromServerToClient(clientConfig.getId(), clientConfig.getContextPath(), clientConfig.getRedirectUrlFromServerToClient());
        } else {
            redirect_url = clientConfig.getRedirectUrlFromServerToClient();
        }

        // in oidc and social case, null unless redirectToRPHostAndPort specified.
        if (redirect_url == null || redirect_url.isEmpty()) {
            String uri = clientConfig.getContextPath() + "/redirect/" + clientConfig.getId();
            redirect_url = new OidcClientUtil().getRedirectUrl(req, uri);
        }
        redirect_url = clientConfig.getRedirectUrlWithJunctionPath(redirect_url);
        return redirect_url;
    }
295424
@Subscribe
    public synchronized void renew(final MasterSlaveRuleChangedEvent masterSlaveRuleChangedEvent) {
        if (getName().equals(masterSlaveRuleChangedEvent.getShardingSchemaName())) {
            masterSlaveRule = new OrchestrationMasterSlaveRule(masterSlaveRuleChangedEvent.getMasterSlaveRuleConfiguration());
        }
    }
292563
@Override
  public void renew(Map stageCredentials)
  throws SnowflakeSQLException
  {
    // We renew the client with fresh credentials and with its original parameters
    setupSnowflakeS3Client(stageCredentials, this.clientConfig, this.encMat, this.stageRegion);
  }
1093597
protected void prepareForLoginPage(final RequestContext context) {
        val currentService = WebUtils.getService(context);
        val service = authenticationRequestServiceSelectionStrategies.resolveService(currentService, WebApplicationService.class);

        val request = WebUtils.getHttpServletRequestFromExternalWebflowContext(context);
        val response = WebUtils.getHttpServletResponseFromExternalWebflowContext(context);
        val webContext = new J2EContext(request, response, this.sessionStore);

        val urls = new LinkedHashSet<ProviderLoginPageConfiguration>();
        this.clients
            .findAllClients()
            .stream()
            .filter(client -> client instanceof IndirectClient && isDelegatedClientAuthorizedForService(client, service))
            .map(IndirectClient.class::cast)
            .forEach(client -> {
                try {
                    val provider = buildProviderConfiguration(client, webContext, currentService);
                    provider.ifPresent(p -> {
                        urls.add(p);
                        if (p.isAutoRedirect()) {
                            WebUtils.putDelegatedAuthenticationProviderPrimary(context, p);
                        }
                    });
                } catch (final Exception e) {
                    LOGGER.error("Cannot process client [{}]", client, e);
                }
            });

        if (!urls.isEmpty()) {
            context.getFlowScope().put(FLOW_ATTRIBUTE_PROVIDER_URLS, urls);
        } else if (response.getStatus() != HttpStatus.UNAUTHORIZED.value()) {
            LOGGER.warn("No delegated authentication providers could be determined based on the provided configuration. "
                + "Either no clients are configured, or the current access strategy rules prohibit CAS from using authentication providers for this request.");
        }
    }
547231
@Override
    public void renew(Map<String, String> credentials, Map topologyConf) {
        renew(credentials, topologyConf, null);
    }
130811
def post(self, request, provider=None):
        
        # if settings.CAS_FEDERATE is not True redirect to the login page
        if not settings.CAS_FEDERATE:
            logger.warning("CAS_FEDERATE is False, set it to True to use federation")
            return redirect("cas_server:login")
        # POST with a provider suffix, this is probably an SLO request. csrf is disabled for
        # allowing SLO requests reception
        try:
            provider = FederatedIendityProvider.objects.get(suffix=provider)
            auth = self.get_cas_client(request, provider)
            try:
                auth.clean_sessions(request.POST['logoutRequest'])
            except (KeyError, AttributeError):
                pass
            return HttpResponse("ok")
        # else, a User is trying to log in using an identity provider
        except FederatedIendityProvider.DoesNotExist:
            # Manually checking for csrf to protect the code below
            reason = CsrfViewMiddleware().process_view(request, None, (), {})
            if reason is not None:  # pragma: no cover (csrf checks are disabled during tests)
                return reason  # Failed the test, stop here.
            form = forms.FederateSelect(request.POST)
            if form.is_valid():
                params = utils.copy_params(
                    request.POST,
                    ignore={"provider", "csrfmiddlewaretoken", "ticket", "lt"}
                )
                if params.get("renew") == "False":
                    del params["renew"]
                url = utils.reverse_params(
                    "cas_server:federateAuth",
                    kwargs=dict(provider=form.cleaned_data["provider"].suffix),
                    params=params
                )
                return HttpResponseRedirect(url)
            else:
                return redirect("cas_server:login")