This method handle the authorization code; it's validated the response
state and call the server to get the tokens using the authorization code.

@param req
@param res
@param authzCode
@return
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;
    }
487540
public final boolean handle(HttpServletRequest req, HttpServletResponse res) {
		return handle(req, res, Request.getPath(req));
	}
46683
function verifyAuthorizationCode (req, res, next) {
  var params = req.connectParams

  if (params.grant_type === 'authorization_code') {
    AuthorizationCode.getByCode(params.code, function (err, ac) {
      if (err) { return next(err) }

      // Can't find authorization code
      if (!ac) {
        return next(new AuthorizationError({
          error: 'invalid_grant',
          error_description: 'Authorization not found',
          statusCode: 400
        }))
      }

      // Authorization code has been previously used
      if (ac.used === true) {
        return next(new AuthorizationError({
          error: 'invalid_grant',
          error_description: 'Authorization code invalid',
          statusCode: 400
        }))
      }

      // Authorization code is expired
      if (nowSeconds() > ac.expires_at) {
        return next(new AuthorizationError({
          error: 'invalid_grant',
          error_description: 'Authorization code expired',
          statusCode: 400
        }))
      }

      // Mismatching redirect uri
      if (ac.redirect_uri !== params.redirect_uri) {
        return next(new AuthorizationError({
          error: 'invalid_grant',
          error_description: 'Mismatching redirect uri',
          statusCode: 400
        }))
      }

      // Mismatching client id
      if (ac.client_id !== req.client._id) {
        return next(new AuthorizationError({
          error: 'invalid_grant',
          error_description: 'Mismatching client id',
          statusCode: 400
        }))
      }

      // Mismatching user id
      // if (ac.user_id !== req.user._id) {
      //  return next(new AuthorizationError({
      //    error: 'invalid_grant',
      //    error_description: 'Mismatching client id',
      //    statusCode: 400
      //  }))
      // }

      req.code = ac

      // Update the code to show that it's been used.
      AuthorizationCode.patch(ac._id, { used: true }, function (err) {
        next(err)
      })
    })
  } else {
    next()
  }
}
896007
function authorizationCodeGrant (code, done) {
  var endpoint = this.endpoints.token
  var provider = this.provider
  var client = this.client
  var url = endpoint.url
  var method = endpoint.method && endpoint.method.toLowerCase()
  var auth = endpoint.auth
  var parser = endpoint.parser
  var accept = endpoint.accept || 'application/json'
  var params = {}

  // required token parameters
  params.grant_type = 'authorization_code'
  params.code = code
  params.redirect_uri = provider.redirect_uri

  // start building the request
  var req = request[method || 'post'](url)

  // Authenticate the client with HTTP Basic
  if (auth === 'client_secret_basic') {
    req.set('Authorization', 'Basic ' + this.base64credentials())
  }

  // Authenticate the client with POST params
  if (auth === 'client_secret_post') {
    params.client_id = client.client_id
    params.client_secret = client.client_secret
  }

  // Add request body params and set other headers
  req.send(qs.stringify(params))
  req.set('accept', accept)
  req.set('user-agent', agent)

  // Execute the request
  return req.end(function (err, res) {
    if (err) { return done(err) }
    var response = (parser === 'x-www-form-urlencoded')
      ? qs.parse(res.text)
      : res.body

    if (res.statusCode !== 200) {
      return done(response)
    }

    done(null, response)
  })
}
1104918
protected String setOauth2LoginState(HttpServletRequest req, HttpServletResponse resp, String authzEndpoint){
        String state = UUID.randomUUID().toString().replace("-","");
        req.getSession().setAttribute("oauth2_login_state", state);
        authzEndpoint = Urls.appendQueryString(authzEndpoint,"state",state);
        return authzEndpoint;
    }
1369199
private User authcz(final Cache<AuthCredentials, User> cache, Cache<User, Set<String>> roleCache, final AuthCredentials ac,
            final AuthenticationBackend authBackend, final Set<AuthorizationBackend> authorizers) {
        if (ac == null) {
            return null;
        }
        try {

            //noop backend configured and no authorizers
            //that mean authc and authz was completely done via HTTP (like JWT or PKI)
            if (authBackend.getClass() == NoOpAuthenticationBackend.class && authorizers.isEmpty()) {
                //no cache
                return authBackend.authenticate(ac);
            }

            return cache.get(ac, new Callable<User>() {
                @Override
                public User call() throws Exception {
                    if (log.isTraceEnabled()) {
                        log.trace("Credentials for user " + ac.getUsername() + " not cached, return from " + authBackend.getType()
                                + " backend directly");
                    }
                    final User authenticatedUser = authBackend.authenticate(ac);
                    authz(authenticatedUser, roleCache, authorizers);

                    return authenticatedUser;
                }
            });
        } catch (Exception e) {
            if (log.isDebugEnabled()) {
                log.debug("Can not authenticate " + ac.getUsername() + " due to " + e.toString(), e);
            }
            return null;
        } finally {
            ac.clearSecrets();
        }
    }
618787
public void postProgrammaticAuthenticate(final HttpServletRequest req, final HttpServletResponse resp, final AuthenticationResult authResult,
                                             final boolean alwaysSetCallerSubject, final boolean addSSOCookie) {
        if (System.getSecurityManager() == null) {
            setSubjectAndCookies(req, resp, authResult, alwaysSetCallerSubject, addSSOCookie);
        } else {
            AccessController.doPrivileged(new PrivilegedAction<Object>() {

                @Override
                public Object run() {
                    setSubjectAndCookies(req, resp, authResult, alwaysSetCallerSubject, addSSOCookie);
                    return null;
                }
            });
        }
    }
922998
def request_access_token(self, code, redirect_uri=None):
        '''
        
        '''
        redirect = redirect_uri or self._redirect_uri
        resp_text = _http('POST', 'https://graph.qq.com/oauth2.0/token',
                          client_id=self._client_id, client_secret=self._client_secret,
                          redirect_uri=redirect, code=code, grant_type='authorization_code')
        return self._parse_access_token(resp_text)
206892
public AuthorizationCodeUriRequest.Builder authorizationCodeUri() {
    return new AuthorizationCodeUriRequest.Builder()
            .setDefaults(httpManager, scheme, host, port)
            .client_id(clientId)
            .response_type("code")
            .redirect_uri(redirectUri);
  }
731135
public void postProgrammaticAuthenticate(HttpServletRequest req, HttpServletResponse resp, AuthenticationResult authResult) {
        postProgrammaticAuthenticate(req, resp, authResult, false, true);
    }
292759
public Single<Boolean> revokeToken(FullHttpRequest req) throws OAuthException {
        RevokeTokenRequest revokeRequest = new RevokeTokenRequest(req);
        revokeRequest.checkMandatoryParams();
        String clientId = revokeRequest.getClientId();
        // check valid client_id, status does not matter as token of inactive client app could be revoked too
        return isExistingClient(clientId).flatMap(existed -> {
            if (!existed) throw new OAuthException(ResponseBuilder.INVALID_CLIENT_ID, HttpResponseStatus.BAD_REQUEST);
            else {
                String token = revokeRequest.getAccessToken();
                return db.findAccessToken(token)
                        .map(Optional::of)
                        .switchIfEmpty(Single.just(Optional.empty()))
                        .flatMap(accessToken -> {
                            if (accessToken.isPresent()) {
                                if (accessToken.get().tokenExpired()) {
                                    LOG.info(String.format("Access token {%s} has already expired, nothing need to do.", token));
                                    return Single.just(true);
                                }
                                if (clientId.equals(accessToken.get().getClientId())) {
                                    return db.removeAccessToken(accessToken.get().getToken())
                                            .andThen(Single.just(true)
                                                    .doOnSuccess(ignored -> LOG.info(String.format("access token {%s} set status invalid", token))));
                                } else {
                                    LOG.info(String.format("access token {%s} is not obtained for that client {%s}", token, clientId));
                                    return Single.just(false);
                                }
                            } else {
                                LOG.info(String.format("access token {%s} not found", token));
                                return Single.just(false);
                            }
                        })
                        ;
            }
        });
    }
869199
def process_request(self, req, resp):  # pylint: disable=unused-argument
        

        try:
            creds = self._get_creds(req)
            self.auth_creds(*creds)
        except (AuthRejected, AuthRequired, InvalidAuthSyntax) as exc:
            exc.headers = self._error_headers
            if not self.optional:
                abort(exc)
636656
public AccessToken obtainAccessTokenByCode(String authorizationCode) throws InvalidCodeException, TokenExpiredException {
        AccessToken token = tp().obtainAccessTokenByAuthzCode(authorizationCode);
        return token;
    }
272250
function(code) {
                console.log('oauthInterface.token.get');
                this.params.data.code = code;

                return this.request({
                    url: this._buildUri(this.uri),
                    method: corbel.request.method.POST,
                    contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
                    data: this.params.data
                });
            }
193458
public OauthGetTokenResponse getToken(String code) {
        BeanUtil.requireNonNull(code, "code is null");
        OauthGetTokenResponse response = null;
        String url = BASE_API_URL + "sns/oauth2/access_token?appid=" + this.config.getAppid() + "&secret=" + this.config.getSecret() + "&code=" + code + "&grant_type=authorization_code";
        BaseResponse r = executeGet(url);
        String resultJson = isSuccess(r.getErrcode()) ? r.getErrmsg() : r.toJsonString();
        response = JSONUtil.toBean(resultJson, OauthGetTokenResponse.class);
        return response;
    }
296933
protected boolean isAccessTokenRequest(final HttpServletRequest request, final HttpServletResponse response) {
        val requestPath = request.getRequestURI();
        val pattern = String.format("(%s|%s)", OAuth20Constants.ACCESS_TOKEN_URL, OAuth20Constants.TOKEN_URL);
        return doesUriMatchPattern(requestPath, pattern);
    }
977063
protected void handleErrorCodes(final int responseCode) throws FetcherException {
        // Handle 2xx codes as OK, so ignore them here
        // 3xx codes are handled by the HttpURLConnection class
        if (responseCode == 403) {
            // Authentication is required
            throwAuthenticationError(responseCode);
        } else if (responseCode >= 400 && responseCode < 500) {
            throw4XXError(responseCode);
        } else if (responseCode >= 500 && responseCode < 600) {
            throw new FetcherException(responseCode, "The server encounted an error. HTTP Response code was:" + responseCode);
        }
    }