Build an OAuth authorization request.

@param clientId The OAuth client id obtained from tvtag.
@param redirectUri The URI to redirect to with appended auth code query parameter.
@throws OAuthSystemException
15747
public static OAuthClientRequest getAuthorizationRequest(String clientId, String redirectUri)
            throws OAuthSystemException {
        return OAuthClientRequest
                .authorizationLocation(OAUTH2_AUTHORIZATION_URL)
                .setScope("public read write")
                .setResponseType(ResponseType.CODE.toString())
                .setClientId(clientId)
                .setRedirectURI(redirectUri)
                .buildQueryMessage();
    }
422202
def get_access_token_from_code(
        self, code, redirect_uri, app_id, app_secret
    ):
        
        args = {
            "code": code,
            "redirect_uri": redirect_uri,
            "client_id": app_id,
            "client_secret": app_secret,
        }

        return self.request(
            "{0}/oauth/access_token".format(self.version), args
        )
987618
def authenticate_redirect(self, callback_uri=None, cancel_uri=None,
                              extended_permissions=None, callback=None):
        
        self.require_setting(self._CLIENT_ID_SETTING, self._API_NAME)

        scope = self._BASE_SCOPE
        if extended_permissions:
            scope += extended_permissions

        args = {'client_id': self.settings[self._CLIENT_ID_SETTING],
                'redirect_uri': self.oauth2_redirect_uri(callback_uri),
                'scope': ','.join(scope)}

        # If cookie_secret is set, use it for GitHub's state value
        if not self.state and 'cookie_secret' in self.settings:
            sha1 = hashlib.sha1(self.settings['cookie_secret'])
            self.state = str(sha1.hexdigest())

        # If state is set, add it to args
        if self.state:
            args['state'] = self.state

        LOGGER.info('Redirect args: %r', args)

        # Redirect the user to the proper URL
        self.redirect(self._OAUTH_AUTHORIZE_URL +
                      auth.urllib_parse.urlencode(args))
        callback()
1075175
public static String connectOauth2Authorize(String appid,String redirect_uri,boolean snsapi_userinfo,String state,String component_appid){
		try {
			StringBuilder sb = new StringBuilder();
			sb.append(OPEN_URI + "/connect/oauth2/authorize?")
			.append("appid=").append(appid)
			.append("&redirect_uri=").append(URLEncoder.encode(redirect_uri, "utf-8"))
			.append("&response_type=code")
			.append("&scope=").append(snsapi_userinfo?"snsapi_userinfo":"snsapi_base")
			.append("&state=").append(state==null?"":state);
			if(component_appid!=null){
				sb.append("&component_appid=").append(component_appid);
			}
			 sb.append("#wechat_redirect");
			return sb.toString();
		} catch (UnsupportedEncodingException e) {
			logger.error("", e);
		}
		return null;
	}
93385
def authenticate_with_auth_code(authorization_code, redirect_uri)
      response = @oauth_connection.post do |req|
        req.url '/oauth/token'
        req.headers['Content-Type'] = 'application/x-www-form-urlencoded'
        req.body = {:grant_type => 'authorization_code', :client_id => api_key, :client_secret => api_secret, :code => authorization_code, :redirect_uri => redirect_uri}
      end

      @oauth_token = OAuthToken.new(response.body)
      configure_oauth
      @oauth_token
    end
1306830
public HttpUrl authorizeUrl(String scopes, HttpUrl redirectUrl, ByteString state, String team) {
    HttpUrl.Builder builder = baseUrl.newBuilder("/oauth/authorize")
        .addQueryParameter("client_id", clientId)
        .addQueryParameter("scope", scopes)
        .addQueryParameter("redirect_uri", redirectUrl.toString())
        .addQueryParameter("state", state.base64());

    if (team != null) {
      builder.addQueryParameter("team", team);
    }

    return builder.build();
  }
962731
public ProviderAuthenticationResult handleAuthorizationCode(HttpServletRequest req,
            HttpServletResponse res,
            String authzCode,
            String responseState,
            ConvergedClientConfig clientConfig) {

        String clientId = clientConfig.getClientId();
        OidcClientRequest oidcClientRequest = (OidcClientRequest) req.getAttribute(ClientConstants.ATTRIB_OIDC_CLIENT_REQUEST);
        ProviderAuthenticationResult oidcResult = null;
        oidcResult = authenticatorUtil.verifyResponseState(req, res, responseState, clientConfig);
        if (oidcResult != null) {
            return oidcResult; // only if something bad happened, otherwise proceed to exchange auth code for tokens.
        }
        if (!OIDCClientAuthenticatorUtil.checkHttpsRequirement(clientConfig, clientConfig.getTokenEndpointUrl())) {
            Tr.error(tc, "OIDC_CLIENT_URL_PROTOCOL_NOT_HTTPS", clientConfig.getTokenEndpointUrl());
            oidcResult = new ProviderAuthenticationResult(AuthResult.SEND_401, HttpServletResponse.SC_UNAUTHORIZED);
            return oidcResult;
        }
        String redirect_url = authenticatorUtil.setRedirectUrlIfNotDefined(req, clientConfig);
        if (!OIDCClientAuthenticatorUtil.checkHttpsRequirement(clientConfig, redirect_url)) {
            Tr.error(tc, "OIDC_CLIENT_URL_PROTOCOL_NOT_HTTPS", redirect_url);
            oidcResult = new ProviderAuthenticationResult(AuthResult.SEND_401, HttpServletResponse.SC_UNAUTHORIZED);
            return oidcResult;
        }

        SSLSocketFactory sslSocketFactory = null;
        try {
            sslSocketFactory = getSSLSocketFactory(clientConfig.getTokenEndpointUrl(), clientConfig.getSSLConfigurationName(), clientId);
        } catch (SSLException e) {
            Tr.error(tc, "OIDC_CLIENT_HTTPS_WITH_SSLCONTEXT_NULL", new Object[] { e.getMessage() != null ? e.getMessage() : "invalid ssl context", clientConfig.getClientId() });
            return new ProviderAuthenticationResult(AuthResult.SEND_401, HttpServletResponse.SC_UNAUTHORIZED);
        }

        // go get the tokens and validate them.
        try {

            String url = clientConfig.getTokenEndpointUrl();
            if (url == null || url.length() == 0) {
                throw new MalformedURLException("MalformedURLException");
            }
            HashMap<String, String> tokens = oidcClientUtil.getTokensFromAuthzCode(url,
                    clientId,
                    clientConfig.getClientSecret(),
                    redirect_url,
                    authzCode,
                    clientConfig.getGrantType(),
                    sslSocketFactory,
                    clientConfig.isHostNameVerificationEnabled(),
                    clientConfig.getTokenEndpointAuthMethod(),
                    OIDCClientAuthenticatorUtil.getResources(clientConfig),
                    clientConfig.getTokenRequestParams(),
                    clientConfig.getUseSystemPropertiesForHttpClientConnections());

            oidcClientRequest.setTokenType(ClientConstants.TYPE_ID_TOKEN);

            // this has a LOT of dependencies.
            oidcResult = jose4jUtil.createResultWithJose4J(responseState, tokens, clientConfig, oidcClientRequest);

            //if tokens were valid, go get the userinfo if configured to do so, and update the authentication result to include it.
            UserInfoHelper uih = new UserInfoHelper(clientConfig);
            if (uih.willRetrieveUserInfo()) {
                OidcTokenImplBase idToken = null;
                if (oidcResult.getCustomProperties() != null) {
                    idToken = (OidcTokenImplBase) oidcResult.getCustomProperties().get(Constants.ID_TOKEN_OBJECT);
                }
                String subjFromIdToken = null;
                if (idToken != null) {
                    subjFromIdToken = idToken.getSubject();
                }
                if (subjFromIdToken != null) {
                    uih.getUserInfo(oidcResult, sslSocketFactory, tokens.get(Constants.ACCESS_TOKEN), subjFromIdToken);
                }
            }

        } catch (BadPostRequestException e) {
            Tr.error(tc, "OIDC_CLIENT_TOKEN_REQUEST_FAILURE", new Object[] { e.getErrorMessage(), clientId, clientConfig.getTokenEndpointUrl() });
            sendErrorJSON(res, e.getStatusCode(), "invalid_request", e.getErrorMessage());
            oidcResult = new ProviderAuthenticationResult(AuthResult.FAILURE, e.getStatusCode());
        } catch (Exception e) {
            Tr.error(tc, "OIDC_CLIENT_TOKEN_REQUEST_FAILURE", new Object[] { e.getLocalizedMessage(), clientId, clientConfig.getTokenEndpointUrl() });
            oidcResult = new ProviderAuthenticationResult(AuthResult.SEND_401, HttpServletResponse.SC_UNAUTHORIZED);
        }
        return oidcResult;
    }
624474
protected void issueAuthenticationRequestRedirect(final Pair<? extends SignableSAMLObject, MessageContext> pair,
                                                      final HttpServletRequest request,
                                                      final HttpServletResponse response) throws Exception {
        val authnRequest = (AuthnRequest) pair.getLeft();
        val serviceUrl = constructServiceUrl(request, response, pair);
        LOGGER.debug("Created service url [{}]", DigestUtils.abbreviate(serviceUrl));

        val initialUrl = CommonUtils.constructRedirectUrl(samlProfileHandlerConfigurationContext.getCasProperties().getServer().getLoginUrl(),
            CasProtocolConstants.PARAMETER_SERVICE, serviceUrl, authnRequest.isForceAuthn(),
            authnRequest.isPassive());

        val urlToRedirectTo = buildRedirectUrlByRequestedAuthnContext(initialUrl, authnRequest, request);

        LOGGER.debug("Redirecting SAML authN request to [{}]", urlToRedirectTo);
        val authenticationRedirectStrategy = new DefaultAuthenticationRedirectStrategy();
        authenticationRedirectStrategy.redirect(request, response, urlToRedirectTo);
    }
419525
public function getAuthorizationRequestUrl($authorizeUrl, $clientId, $redirectUrl, $parameters = [])
    {
        $parameters = array_merge($parameters, array(
            'response_type' => 'code',
            'client_id' => $clientId,
            //'nonce' => $stateGuid->toString(),
            'redirect_uri' => $redirectUrl,
            //'post_logout_redirect_uri' => $redirectUrl,
            //'response_mode' => 'form_post',
            //'scope' => 'openid+profile'
        ));
        return $authorizeUrl . "?" . http_build_query($parameters);
    }
1092505
protected function setAuthCode($oauthCode, $accountId, $redirectUri, $expires = null, $scope = null)
    {
        if (null === $account = $this->app['repo.api-accounts']->find($accountId)) {
            throw new RuntimeException(sprintf('Account with id %s is not valid', $accountId));
        }
        $code = $this->app['manipulator.api-oauth-code']->create($account, $redirectUri, $expires, $scope);
        $this->app['manipulator.api-oauth-code']->setCode($code, $oauthCode);

        return $this;
    }
455337
public String blockingIssueAuthorizationCode(HttpRequest req) throws OAuthException {
        AuthRequest authRequest = new AuthRequest(req);
        LOG.info("received client_id:" + authRequest.getClientId());
        if (!isActiveClientId(authRequest.getClientId()).blockingGet()) {
            throw new OAuthException(ResponseBuilder.INVALID_CLIENT_ID, HttpResponseStatus.BAD_REQUEST);
        }
        authRequest.validate();

        String scope = scopeService.getValidScope(authRequest.getScope(), authRequest.getClientId()).blockingGet();
        if (scope == null) {
            throw new OAuthException(ResponseBuilder.SCOPE_NOK_MESSAGE, HttpResponseStatus.BAD_REQUEST);
        }

        AuthCode authCode = new AuthCode(generateCode(), authRequest.getClientId(), authRequest.getRedirectUri(),
                authRequest.getState(), scope, authRequest.getResponseType(), authRequest.getUserId());
        LOG.info("authCode: {" + authCode.getCode() + "}");
        db.storeAuthCode(authCode).blockingAwait();

        // return redirect URI, append param code=[Authcode]
        QueryStringEncoder enc = new QueryStringEncoder(authRequest.getRedirectUri());
        enc.addParam("code", authCode.getCode());
        return enc.toString();
    }
870335
def authorize_url(self, scope='', **kwargs):
        
        self._check_configuration("site", "authorization_url", "redirect_uri",
                                  "client_id")
        if isinstance(scope, (list, tuple, set, frozenset)):
            self._check_configuration("scope_sep")
            scope = self.scope_sep.join(scope)
        oauth_params = {
            'redirect_uri': self.redirect_uri,
            'client_id': self.client_id,
            'scope': scope,
        }
        oauth_params.update(kwargs)
        return "%s%s?%s" % (self.site, quote(self.authorization_url),
                            urlencode(oauth_params))
71114
def get_authorize_url(self, redirect_uri=None, **kw):
        '''
        
        '''
        redirect = redirect_uri if redirect_uri else self.redirect_uri
        if not redirect:
            raise APIError('21305', 'Parameter absent: redirect_uri', 'OAuth2 request')
        response_type = kw.pop('response_type', 'code')
        return '%s%s?%s' % (self.auth_url, 'authorize',
                            _encode_params(client_id=self.client_id,
                                           response_type=response_type,
                                           redirect_uri=redirect, **kw))
1312293
protected function createAuthCodeClient(ClientRepository $clients)
    {
        $userId = $this->ask(
            'Which user ID should the client be assigned to?'
        );

        $name = $this->option('name') ?: $this->ask(
            'What should we name the client?'
        );

        $redirect = $this->ask(
            'Where should we redirect the request after authorization?',
            url('/auth/callback')
        );

        $client = $clients->create(
            $userId, $name, $redirect
        );

        $this->info('New client created successfully.');
        $this->line('<comment>Client ID:</comment> '.$client->_id);
        $this->line('<comment>Client secret:</comment> '.$client->secret);
    }
947923
def authorize_url(self, client_id, redirect_uri, scope, state=None):
        """"""
        params = [
            ('client_id', client_id),
            ('redirect_uri', redirect_uri),
            ('scope', scope)
        ]
        if state:
            params.append(('state', state))
        return "%s?%s" % (CreateSend.oauth_uri, urlencode(params))
918562
function OAuth2Client(callContext, authority) {
  this._tokenEndpoint = authority.tokenEndpoint;
  this._deviceCodeEndpoint = authority.deviceCodeEndpoint;

  this._log = new Logger('OAuth2Client', callContext._logContext);
  this._callContext = callContext;
  this._cancelPollingRequest = false;
}
46210
protected static HttpClientBuilder addAuthentication(final HttpClientBuilder builder, 
            final URI uri, final String username,
            String password) {
        if (isNotBlank(username)) {
            CredentialsProvider provider = new BasicCredentialsProvider();
            AuthScope scope = new AuthScope(uri.getHost(), uri.getPort(), "realm");
            UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password);
            provider.setCredentials(scope, credentials);
            builder.setDefaultCredentialsProvider(provider);

            builder.addInterceptorFirst(new PreemptiveAuth());
        }
        return builder;
    }