Register an oauth scope. If the scope already exists, returns an error.

@param req http request
@return String message that will be returned in the response
9119
public String registerScope(FullHttpRequest req) throws OAuthException {
        String contentType = (req.headers() != null) ? req.headers().get(HttpHeaderNames.CONTENT_TYPE) : null;
        // check Content-Type
        if (contentType != null && contentType.contains(ResponseBuilder.APPLICATION_JSON)) {
            try {
                Scope scope = InputValidator.validate(req.content().toString(CharsetUtil.UTF_8), Scope.class);
                if (scope.valid()) {
                    if (!Scope.validScopeName(scope.getScope())) {
                        LOG.error("scope name is not valid");
                        throw new OAuthException(SCOPE_NAME_INVALID_ERROR, HttpResponseStatus.BAD_REQUEST);
                    }
                    LOG.info(">>>>>>>>>>>>>>> scope = " + scope);
                    Scope foundScope = DBManagerFactory.getInstance().findScope(scope.getScope()).blockingGet();
                    if (foundScope != null) {
                        LOG.error("scope already exists");
                        throw new OAuthException(SCOPE_ALREADY_EXISTS, HttpResponseStatus.BAD_REQUEST);
                    } else {
                        // store in the DB, if already exists such a scope, overwrites it
                        DBManagerFactory.getInstance().storeScope(scope).blockingGet();
                    }
                } else {
                    LOG.error("scope is not valid");
                    throw new OAuthException(MANDATORY_FIELDS_ERROR, HttpResponseStatus.BAD_REQUEST);
                }
            } catch (Throwable e) {
                LOG.error("cannot handle scope request", e);
                throw new OAuthException(e, null, HttpResponseStatus.BAD_REQUEST);
            }
        } else {
            throw new OAuthException(ResponseBuilder.UNSUPPORTED_MEDIA_TYPE, HttpResponseStatus.BAD_REQUEST);
        }
        return SCOPE_STORED_OK_MESSAGE;
    }
1086157
function(params, stateData) {
          // Handle an error response from the OAuth server
          if (params.error) {
            authLogger.log("RedirectLoginService.finish(), error", params.error, params.error_description, params.error_uri);
            return $q.reject({
              error: params.error,
              error_description: params.error_description,
              error_uri: params.error_uri
            });
          }

          // Handle an access_token fragment response
          if (params.access_token) {
            return $q.when({
              token: params.access_token,
              ttl: params.expires_in,
              then: stateData.then,
              verified: stateData.verified
            });
          }

          // No token and no error is invalid
          return $q.reject({
            error: "invalid_request",
            error_description: "No API token returned"
          });
        }
1248957
function(scopes) {
                console.log('iamInterface.group.addScopes', scopes);
                corbel.validate.value('id', this.id);
                return this.request({
                    url: this._buildUriWithDomain(this.uri, this.id) + '/scope',
                    method: corbel.request.method.PUT,
                    data: scopes,
                    withAuth: true
                });
            }
215943
public function getReAuthenticationUrl(array $scope = [], $callback_url = '')
    {
        $scope = $this->getScope($scope);
        $callback_url = $this->getCallbackUrl($callback_url);

        return $this->getRedirectLoginHelper()->getReAuthenticationUrl($callback_url, $scope);
    }
979003
function() {
        if (_oauth_client_id === "") {
          return $q.reject({error:'invalid_request', error_description:'RedirectLoginServiceProvider.OAuthClientID() not set'});
        }
        if (_oauth_authorize_uri === "") {
          return $q.reject({error:'invalid_request', error_description:'RedirectLoginServiceProvider.OAuthAuthorizeURI() not set'});
        }
        if (_oauth_redirect_uri === "") {
          return $q.reject({error:'invalid_request', error_description:'RedirectLoginServiceProvider.OAuthRedirectURI not set'});
        }

        // Never send a local fragment to remote servers
        var returnUri = new URI($location.url()).fragment("");
        var authorizeParams = {
          client_id: _oauth_client_id,
          response_type: 'token',
          state: makeState(returnUri.toString()),
          redirect_uri: _oauth_redirect_uri
        };

        if (_oauth_scope) {
          authorizeParams.scope = _oauth_scope;
        }

        if (_oauth_token_uri) {
          authorizeParams.response_type = "code";
          // TODO: add PKCE
        }

        var deferred = $q.defer();
        var uri = new URI(_oauth_authorize_uri);
        uri.query(authorizeParams);
        authLogger.log("RedirectLoginService.login(), redirecting", uri.toString());
        window.location.href = uri.toString();
        // Return a promise we never intend to keep, because we're redirecting to another page
        return deferred.promise;
      }
352856
public function getOauthRedirect($callback, $state = '', $scope = 'snsapi_base')
    {
        $redirect_uri = urlencode($callback);
        return self::OAUTH_PREFIX . self::OAUTH_AUTHORIZE_URL . "appid={$this->appid}&redirect_uri={$redirect_uri}&response_type=code&scope={$scope}&state={$state}#wechat_redirect";
    }
145840
public function retrieveTokenRequest(array $scope = array()) {
    $parameters = array(
      'oauth_callback' => $this->getCallbackUrl()
    );

    $requestUrl = self::_URL_REQUEST;

    if (!empty($scope)) {
        $requestUrl .= '?scope=' . implode('+', $scope);
    }

    $response = $this->fetch(self::_METHOD_TOKENS, $requestUrl, NULL, $parameters);
    parse_str($response['linkedin'], $response['linkedin']);
    
    /**
	   * Check for successful request (a 200 response from LinkedIn server) 
	   * per the documentation linked in method comments above.
	   */
    if(($response['info']['http_code'] == 200) && (array_key_exists('oauth_callback_confirmed', $response['linkedin'])) && ($response['linkedin']['oauth_callback_confirmed'] == 'true')) {
      // tokens retrieved
      $this->setToken($response['linkedin']);
      
      // set the response
      $return_data            = $response;
      $return_data['success'] = TRUE;        
    } else {
      // error getting the request tokens
      $this->setToken(NULL);
      
      // set the response
      $return_data = $response;
      if((array_key_exists('oauth_callback_confirmed', $response['linkedin'])) && ($response['linkedin']['oauth_callback_confirmed'] == 'true')) {
        $return_data['error'] = 'HTTP response from LinkedIn end-point was not code 200';
      } else {
        $return_data['error'] = 'OAuth callback URL was not confirmed by the LinkedIn end-point';
      }
      $return_data['success'] = FALSE;
    }
    return $return_data;
	}
94183
public function getRequestToken()
    {
        try {
            $response = $this->post('/oauth/initiate')->send();
        } catch (ClientErrorResponseException $e) {
            throw OauthException::factory($e->getRequest(), $e->getResponse());
        }
        return new RequestToken($this, $response);
    }
562742
function determineClientScope (req, res, next) {
  var params = req.connectParams
  var subject = req.client
  var scope = params.scope || subject.default_client_scope

  if (params.grant_type === 'client_credentials') {
    Scope.determine(scope, subject, function (err, scope, scopes) {
      if (err) { return next(err) }
      req.scope = scope
      req.scopes = scopes
      next()
    })
  } else {
    next()
  }
}
1282446
def get(self, request, *_args, **_kwargs):
        

        access_token = self.access_token

        scope_string = request.GET.get('scope')
        scope_request = scope_string.split() if scope_string else None

        claims_string = request.GET.get('claims')
        claims_request = json.loads(claims_string) if claims_string else None

        if not provider.scope.check(constants.OPEN_ID_SCOPE, access_token.scope):
            return self._bad_request('Missing openid scope.')

        try:
            claims = self.userinfo_claims(access_token, scope_request, claims_request)
        except ValueError, exception:
            return self._bad_request(str(exception))

        # TODO: Encode and sign responses if requested.

        response = JsonResponse(claims)

        return response
568124
private String getCustomReloginErrorPage(HttpServletRequest req) {
        String reLogin = CookieHelper.getCookieValue(req.getCookies(), ReferrerURLCookieHandler.CUSTOM_RELOGIN_URL_COOKIENAME);
        if (reLogin != null && reLogin.length() > 0) {
            if (reLogin.indexOf("?") < 0)
                reLogin += "?error=error";
        }
        return reLogin;
    }
1146054
public String getOauthPageUrl(String redirectUrl, OauthScope scope, String state) {
        BeanUtil.requireNonNull(redirectUrl, "redirectUrl is null");
        BeanUtil.requireNonNull(scope, "scope is null");
        String userState = StrUtil.isBlank(state) ? "STATE" : state;
        String url = null;
        try {
            url = URLEncoder.encode(redirectUrl, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            LOG.error("异常", e);
        }
        StringBuilder stringBuilder = new StringBuilder("https://open.weixin.qq.com/connect/oauth2/authorize?");
        stringBuilder.append("appid=").append(this.config.getAppid())
                .append("&redirect_uri=").append(url)
                .append("&response_type=code&scope=").append(scope.toString())
                .append("&state=")
                .append(userState)
                .append("#wechat_redirect");
        return stringBuilder.toString();
    }
215055
public function requestToken ()
	{
		OAuthRequestLogger::start($this);
		try
		{
			$this->verify(false);
			
			$options = array();
			$ttl     = $this->getParam('xoauth_token_ttl', false);
			if ($ttl)
			{
				$options['token_ttl'] = $ttl;
			}

 			// 1.0a Compatibility : associate callback url to the request token
 			$cbUrl   = $this->getParam('oauth_callback', true);
 			if ($cbUrl) {
 				$options['oauth_callback'] = $cbUrl;
 			}
			
			// Create a request token
			$store  = OAuthStore::instance();
			$token  = $store->addConsumerRequestToken($this->getParam('oauth_consumer_key', true), $options);
			$result = 'oauth_callback_confirmed=1&oauth_token='.$this->urlencode($token['token'])
					.'&oauth_token_secret='.$this->urlencode($token['token_secret']);

			if (!empty($token['token_ttl']))
			{
				$result .= '&xoauth_token_ttl='.$this->urlencode($token['token_ttl']);
			}

			$request_token = $token['token'];
			
			header('HTTP/1.1 200 OK');
			header('Content-Length: '.strlen($result));
			header('Content-Type: application/x-www-form-urlencoded');

			echo $result;
		}
		catch (OAuthException2 $e)
		{
			$request_token = false;

			header('HTTP/1.1 401 Unauthorized');
			header('Content-Type: text/plain');

			echo "OAuth Verification Failed: " . $e->getMessage();
		}

		OAuthRequestLogger::flush();
		return $request_token;
	}
1262767
def read_validate_params(self, request):
        
        self.client = self.client_authenticator.by_identifier(request)

        response_type = request.get_param("response_type")

        if self.client.response_type_supported(response_type) is False:
            raise OAuthInvalidError(error="unauthorized_client")

        self.state = request.get_param("state")

        self.scope_handler.parse(request, "query")

        return True
881257
function oauthErrorResponder(req, res, err) {
  var accepts = req.accepts(['html', 'json']);
  var config = req.app.get('stormpathConfig');

  if (accepts === 'json') {
    return writeJsonError(res, err);
  }

  return renderLoginFormWithError(req, res, config, err);
}
43689
def auth_uri(self):

        """"""

        return self.oauth.auth_uri(redirect_uri=self.redirect_uri, scope=self.scope)
324538
protected function validateTokenScopes(array $scopes)
    {
        $scopes = array_map(function ($scope) {
            return (string) $scope;
        }, $scopes);

        $registeredScopes = $this->scopeService->getAll();

        $registeredScopes = array_map(function ($scope) {
            return (string) $scope;
        }, $registeredScopes);

        $diff = array_diff($scopes, $registeredScopes);

        if (count($diff) > 0) {
            throw OAuth2Exception::invalidScope(sprintf(
                'Some scope(s) do not exist: %s',
                implode(', ', $diff)
            ));
        }
    }