Gets credentials from delegated client.

@param webContext the web context
@param client     the client
@return the credentials from delegated client
978438
protected Credentials getCredentialsFromDelegatedClient(final J2EContext webContext, final BaseClient<Credentials, CommonProfile> client) {
        val credentials = client.getCredentials(webContext);
        LOGGER.debug("Retrieved credentials from client as [{}]", credentials);
        if (credentials == null) {
            throw new IllegalArgumentException("Unable to determine credentials from the context with client " + client.getName());
        }
        return credentials;
    }
388823
def GetCredentials(package_name, scopes, client_id, client_secret, user_agent,
                   credentials_filename=None,
                   api_key=None,  # pylint: disable=unused-argument
                   client=None,  # pylint: disable=unused-argument
                   oauth2client_args=None,
                   **kwds):
    """"""
    scopes = util.NormalizeScopes(scopes)
    client_info = {
        'client_id': client_id,
        'client_secret': client_secret,
        'scope': ' '.join(sorted(scopes)),
        'user_agent': user_agent or '%s-generated/0.1' % package_name,
    }
    for method in _CREDENTIALS_METHODS:
        credentials = method(client_info, **kwds)
        if credentials is not None:
            return credentials
    credentials_filename = credentials_filename or os.path.expanduser(
        '~/.apitools.token')
    credentials = CredentialsFromFile(credentials_filename, client_info,
                                      oauth2client_args=oauth2client_args)
    if credentials is not None:
        return credentials
    raise exceptions.CredentialsError('Could not create valid credentials')
1177606
public Event buildAuthenticationRequestEvent(final RequestContext context) {
        val clients = new ArrayList<WsFedClient>();
        val request = WebUtils.getHttpServletRequestFromExternalWebflowContext(context);
        val service = (Service) context.getFlowScope().get(CasProtocolConstants.PARAMETER_SERVICE);
        this.configurations.forEach(cfg -> {
            val c = new WsFedClient();
            c.setName(cfg.getName());
            val id = UUID.randomUUID().toString();
            val rpId = wsFederationHelper.getRelyingPartyIdentifier(service, cfg);
            c.setAuthorizationUrl(cfg.getAuthorizationUrl(rpId, id));
            c.setReplyingPartyId(rpId);
            c.setId(id);
            c.setRedirectUrl(getRelativeRedirectUrlFor(cfg, service, request));
            c.setAutoRedirect(cfg.isAutoRedirect());
            clients.add(c);

            if (cfg.isAutoRedirect()) {
                WebUtils.putDelegatedAuthenticationProviderPrimary(context, cfg);
            }
        });
        context.getFlowScope().put(PARAMETER_NAME_WSFED_CLIENTS, clients);
        return new EventFactorySupport().event(this, CasWebflowConstants.TRANSITION_ID_PROCEED);
    }
1208114
@Override
    public SSLContext getSSLContext(Map<String, Object> connectionInfo, SSLConfig sslConfig) throws Exception {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            Tr.entry(tc, "getSSLContext", new Object[] { connectionInfo });

        // first try to get the SSLContext from the cache.
        SSLContext sslContext = sslContextCacheJAVAX.get(sslConfig);

        setOutboundConnectionInfoInternal(connectionInfo);

        if (sslContext != null) {
            if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
                Tr.exit(tc, "getSSLContext -> (from cache)");
            return sslContext;
        }

        // Create the SSL context needed by the JSSE.
        sslContext = getSSLContextInstance(sslConfig);

        List<KeyManager> keyMgrs = new ArrayList<KeyManager>();
        List<TrustManager> trustMgrs = new ArrayList<TrustManager>();
        getKeyTrustManagers(connectionInfo, sslConfig, keyMgrs, trustMgrs);

        if (!keyMgrs.isEmpty() && !trustMgrs.isEmpty()) {
            KeyManager[] keyManagers = keyMgrs.toArray(new KeyManager[keyMgrs.size()]);
            TrustManager[] trustManagers = trustMgrs.toArray(new TrustManager[trustMgrs.size()]);
            // use default SecureRandom
            sslContext.init(keyManagers, trustManagers, null);
        } else if (keyMgrs.isEmpty() && !trustMgrs.isEmpty()) {
            TrustManager[] trustManagers = trustMgrs.toArray(new TrustManager[trustMgrs.size()]);
            // use default SecureRandom
            sslContext.init(null, trustManagers, null);
        } else {
            throw new SSLException("Null trust and key managers.");
        }

        // this may need to be made configurable at some point.
        if (sslContextCacheJAVAX.size() > 100) {
            // instead of clearing the entry cache, grab a few to delete
            Iterator<SSLConfig> keys = sslContextCacheJAVAX.keySet().iterator();
            SSLConfig[] victims = new SSLConfig[] { keys.next(), keys.next(), keys.next(), keys.next(), keys.next() };
            // delete the victim entries after using the iterator (not while)
            for (SSLConfig victim : victims) {
                sslContextCacheJAVAX.remove(victim);
            }
        }

        sslContextCacheJAVAX.put(sslConfig, sslContext);
        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
            Tr.debug(tc, "SSLContext cache size: " + sslContextCacheJAVAX.size());

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            Tr.exit(tc, "getSSLContext -> (new)");
        return sslContext;
    }
94134
@Nullable
    public final Credentials toCredentials(final AuthScope authscope) {
        try {

            if (!matches(MatchInfo.fromAuthScope(authscope))) {
                return null;
            }
        } catch (UnknownHostException | MalformedURLException | SocketException e) {
            throw new RuntimeException(e);
        }
        if (this.username == null) {
            return null;
        }

        final String passwordString;
        if (this.password != null) {
            passwordString = new String(this.password);
        } else {
            passwordString = null;
        }
        return new UsernamePasswordCredentials(this.username, passwordString);
    }
762570
@Override
    public Credentials validate(final SAML2MessageContext context) {

        final SAMLObject message = context.getMessage();

        // IDP-initiated
        if (message instanceof LogoutRequest) {
            final LogoutRequest logoutRequest = (LogoutRequest) message;
            final SignatureTrustEngine engine = this.signatureTrustEngineProvider.build();
            validateLogoutRequest(logoutRequest, context, engine);

            return null;

        } else if (message instanceof LogoutResponse) {
            // SP-initiated
            final LogoutResponse logoutResponse = (LogoutResponse) message;
            final SignatureTrustEngine engine = this.signatureTrustEngineProvider.build();
            validateLogoutResponse(logoutResponse, context, engine);

            // nothing to reply to the logout response
            throw new OkAction("");

        } else {
            throw new SAMLException("Must be a LogoutRequest or LogoutResponse type");
        }
    }
103606
public static <T extends Credential> T getCredential(final RequestContext context, final @NonNull Class<T> clazz) {
        val credential = getCredential(context);
        if (credential == null) {
            return null;
        }
        if (!clazz.isAssignableFrom(credential.getClass())) {
            throw new ClassCastException("credential [" + credential.getId()
                + " is of type " + credential.getClass()
                + " when we were expecting " + clazz);
        }
        return (T) credential;
    }
779003
public static Credential getServiceAccountCredential(String serviceAccountId,
      String privateKeyFile) throws GeneralSecurityException, IOException {
    return getServiceAccountCredential(serviceAccountId, privateKeyFile, DatastoreOptions.SCOPES);
  }
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();
        }
    }
427635
def authorize_client_credentials(
        self, client_id, client_secret=None, scope="private_agent"
    ):
        
        self.auth_data = {
            "grant_type": "client_credentials",
            "scope": [ scope ],
            "client_id": client_id,
            "client_secret": client_secret
        }

        self._do_authorize()
978076
public static SecurityContext getSecurityContext() {
        Session session = ExecutionContext.getSession();
        @SuppressWarnings("resource")
        WebSocketSession ws = session == null ? null : session.getSocket();
        return ws == null ? null
                : (SecurityContext) ws.getAttributes().get(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY);
    }
322644
private synchronized void fetchAccessToken() throws ConnectionException, HTTPException {
        if (accessToken != null) {
            return;
        }

        Map<String, String> params = new HashMap<>();
        params.put(Constants.PARAM_CLIENT_ID, clientId);
        params.put(Constants.PARAM_CLIENT_SECRET, clientSecret);

        if (isUserAuthFlow()) {
            params.put(Constants.PARAM_GRANT_TYPE, Constants.PARAM_PASSWORD);
            params.put(Constants.PARAM_USERNAME, username);
            params.put(Constants.PARAM_PASSWORD, password);

        } else {
            params.put(Constants.PARAM_GRANT_TYPE, Constants.GRANT_TYPE_CLIENT_CREDENTIALS);
        }

        loadAccessToken(params);
    }
245117
protected BaseClient<Credentials, CommonProfile> findDelegatedClientByName(final HttpServletRequest request, final String clientName, final Service service) {
        val client = (BaseClient<Credentials, CommonProfile>) this.clients.findClient(clientName);
        LOGGER.debug("Delegated authentication client is [{}] with service [{}}", client, service);
        if (service != null) {
            request.setAttribute(CasProtocolConstants.PARAMETER_SERVICE, service.getId());
            if (!isDelegatedClientAuthorizedForService(client, service)) {
                LOGGER.warn("Delegated client [{}] is not authorized by service [{}]", client, service);
                throw new UnauthorizedServiceException(UnauthorizedServiceException.CODE_UNAUTHZ_SERVICE, StringUtils.EMPTY);
            }
        }
        return client;
    }
758595
private SslContext getSslContext() {
        final SslContext sslCtx;
        if (clientConfig.isEnableTls()) {
            try {
                SslContextBuilder clientSslCtxBuilder = SslContextBuilder.forClient();
                if (Strings.isNullOrEmpty(clientConfig.getTrustStore())) {
                    clientSslCtxBuilder = clientSslCtxBuilder.trustManager(FingerprintTrustManagerFactory
                                                                                   .getInstance(FingerprintTrustManagerFactory.getDefaultAlgorithm()));
                    log.debug("SslContextBuilder was set to an instance of {}", FingerprintTrustManagerFactory.class);
                } else {
                    clientSslCtxBuilder = SslContextBuilder.forClient()
                                                           .trustManager(new File(clientConfig.getTrustStore()));
                }
                sslCtx = clientSslCtxBuilder.build();
            } catch (SSLException | NoSuchAlgorithmException e) {
                throw new RuntimeException(e);
            }
        } else {
            sslCtx = null;
        }
        return sslCtx;
    }
826824
public Credentials getCredentials() {
        if (!Utils.isEmpty(tenant) || !Utils.isEmpty(user)) {
            return new Credentials(tenant, user, password);
        }
        return null;
    }
1285135
public S buildService(final WebContext context, final IndirectClient client, final String state) {
        init();

        final String finalCallbackUrl = client.computeFinalCallbackUrl(context);

        return getApi().createService(this.key, this.secret, finalCallbackUrl, this.scope, null, state, this.responseType, null,
                this.httpClientConfig, null);
    }
353697
def getContext(self):
        """"""
        ctx = ClientContextFactory.getContext(self)
        ctx.set_options(OP_NO_SSLv3)
        return ctx