raise OauthException(
                                    'invalid_request', 
                                    "Missing request parameter: %s" % param)

        except OauthException, exc:
            return (self._error_access_token_response(exc.error, 
                                                      exc.error_description), 
                    None, None)

        token_request = AccessTokenRequest(params.get('grant_type', None),
                                           params.get('code', None),
                                           params.get('redirect_uri', None))

        try:
            response = make_access_token(
                token_request, client_id, self.access_token_register,
                self.access_token_generator, self.authorization_grant_register,
                request)
        except OauthException, exc:
            return (self._error_access_token_response(exc.error, 
                                                      exc.error_description), 
                    None, None)

        if response:
            return self._access_token_response(response), None, None
        else:
            return (None, httplib.INTERNAL_SERVER_ERROR, 
                    'Access token generation failed.')

    def _access_token_response(self, resp):
        """Constructs the JSON response to an access token request.
        @type resp: ndg.oauth.server.lib.oauth.access_token.AccessTokenResponse
Beispiel #2
0
                        'invalid_request',
                        "Missing request parameter: %s" % param)

        except OauthException, exc:
            return (self._error_access_token_response(exc.error,
                                                      exc.error_description),
                    None, None)

        token_request = AccessTokenRequest(params.get('grant_type', None),
                                           params.get('code', None),
                                           params.get('redirect_uri', None))

        try:
            response = make_access_token(token_request, client_id,
                                         self.access_token_register,
                                         self.access_token_generator,
                                         self.authorization_grant_register,
                                         request)
        except OauthException, exc:
            return (self._error_access_token_response(exc.error,
                                                      exc.error_description),
                    None, None)

        if response:
            return self._access_token_response(response), None, None
        else:
            return (None, httplib.INTERNAL_SERVER_ERROR,
                    'Access token generation failed.')

    def _access_token_response(self, resp):
        """Constructs the JSON response to an access token request.
    def authorize(self, request, client_authorized):
        """Handle an authorization request.

        It is assumed that the caller has checked whether the user is
        authenticated and that the user has authorised the client and scope.

        Request query parameters (from 
        http://tools.ietf.org/html/draft-ietf-oauth-v2-22):

        response_type
              REQUIRED.  Value MUST be set to "code" or "token" in the case
              of an implicit grant.
        client_id
              REQUIRED.  The client identifier as described in Section 2.2.
        redirect_uri
              OPTIONAL, as described in Section 3.1.2.
        scope
              OPTIONAL.  The scope of the access request as described by
              Section 3.3.
        state
              RECOMMENDED.  An opaque value used by the client to maintain
              state between the request and callback.  The authorization
              server includes this value when redirecting the user-agent back
              to the client.  The parameter SHOULD be used for preventing
              cross-site request forgery as described in Section 10.12.

        Response:
              application/x-www-form-urlencoded format:
        code
              REQUIRED.  The authorization code generated by the
              authorization server.  The authorization code MUST expire
              shortly after it is issued to mitigate the risk of leaks.  A
              maximum authorization code lifetime of 10 minutes is
              RECOMMENDED.  The client MUST NOT use the authorization code
              more than once.  If an authorization code is used more than
              once, the authorization server MUST deny the request and SHOULD
              attempt to revoke all tokens previously issued based on that
              authorization code.  The authorization code is bound to the
              client identifier and redirection URI.
        state
              REQUIRED if the "state" parameter was present in the client
              authorization request.  The exact value received from the
              client.

        @type request: webob.Request
        @param request: HTTP request object

        @type client_authorized: bool
        @param client_authorized: True if resource owner has authorized client

        @rtype: tuple: (str, int, str)
        @return: tuple (
                     redirect_uri
                     HTTP status if error
                     error description
                 )
        """
        log.debug("Starting authorization request")

        # Parameters should only be taken from the query string.
        params = request.GET
        authz_request = AuthorizeRequest(params.get('response_type', None),
                                         params.get('client_id', None),
                                         params.get('redirect_uri', None),
                                         params.get('scope', None),
                                         params.get('state', None))

        try:
            self.check_request(request, params, post_only=False)

            # Check for required parameters.
            required_parameters = ['response_type', 'client_id']
            for param in required_parameters:
                if param not in params:
                    log.error("Missing request parameter %s from params: %s",
                              param, params)
                    raise OauthException('invalid_request', 
                                        "Missing request parameter: %s" % param)

            if not client_authorized:
                raise OauthException('access_denied', 
                                     'User has declined authorization')

            client_error = self.client_register.is_valid_client(
                                                    authz_request.client_id, 
                                                    authz_request.redirect_uri)
            if client_error:
                log.error("Invalid client: %s", client_error)
                return (None, httplib.BAD_REQUEST, client_error)

            # redirect_uri must be included in the request if the client has
            # more than one registered.
            client = self.client_register.register[authz_request.client_id]
            if (len(client.redirect_uris) != 1 and 
                not authz_request.redirect_uri):
                log.error("An authorization request has been made without a "
                          "return URI")
                return (None, 
                        httplib.BAD_REQUEST, 
                        ('An authorization request has been made without a '
                        'return URI.'))

            response_type = params.get('response_type', None)
            
            # Response may be an authorisation code or in the case of an 
            # Implicit Grant a token
            if response_type == self.__class__.AUTHZ_CODE_RESP_TYPE:
                log.debug('Client requesting an authorization code')
                
                # Preconditions satisfied - generate grant.
                grant, code = self.authorizer.generate_authorization_grant(
                                                                authz_request, 
                                                                request)
                authz_response = AuthorizeResponse(code, authz_request.state)
    
                if not self.authorization_grant_register.add_grant(grant):
                    log.error('Registering grant failed')
                    raise OauthException('server_error', 
                                         'Authorization grant could not be '
                                         'created')

                log.debug("Redirecting back after successful authorization.")
                return self._redirect_after_authorize(authz_request, 
                                                      authz_response)
                                            
            elif response_type == self.__class__.TOK_RESP_TYPE:
                log.debug('Implicit Grant - client requesting a token')
        
                impl_grant_response = make_access_token(authz_request, 
                                                    self.access_token_register,
                                                    self.access_token_generator)
                
                log.debug("Redirecting back after successful implicit grant.")
                return self._redirect_after_authorize(authz_request, 
                                                      impl_grant_response)
            else:
                raise OauthException('unsupported_response_type', 
                                     "Response type %s not supported" % 
                                     response_type)

        except OauthException, exc:
            log.error("Redirecting back after error: %s - %s", 
                      exc.error, exc.error_description)
            
            return self._redirect_after_authorize(authz_request, None, 
                                                  exc.error,
                                                  exc.error_description)
Beispiel #4
0
    def authorize(self, request, client_authorized):
        """Handle an authorization request.

        It is assumed that the caller has checked whether the user is
        authenticated and that the user has authorised the client and scope.

        Request query parameters (from 
        http://tools.ietf.org/html/draft-ietf-oauth-v2-22):

        response_type
              REQUIRED.  Value MUST be set to "code" or "token" in the case
              of an implicit grant.
        client_id
              REQUIRED.  The client identifier as described in Section 2.2.
        redirect_uri
              OPTIONAL, as described in Section 3.1.2.
        scope
              OPTIONAL.  The scope of the access request as described by
              Section 3.3.
        state
              RECOMMENDED.  An opaque value used by the client to maintain
              state between the request and callback.  The authorization
              server includes this value when redirecting the user-agent back
              to the client.  The parameter SHOULD be used for preventing
              cross-site request forgery as described in Section 10.12.

        Response:
              application/x-www-form-urlencoded format:
        code
              REQUIRED.  The authorization code generated by the
              authorization server.  The authorization code MUST expire
              shortly after it is issued to mitigate the risk of leaks.  A
              maximum authorization code lifetime of 10 minutes is
              RECOMMENDED.  The client MUST NOT use the authorization code
              more than once.  If an authorization code is used more than
              once, the authorization server MUST deny the request and SHOULD
              attempt to revoke all tokens previously issued based on that
              authorization code.  The authorization code is bound to the
              client identifier and redirection URI.
        state
              REQUIRED if the "state" parameter was present in the client
              authorization request.  The exact value received from the
              client.

        @type request: webob.Request
        @param request: HTTP request object

        @type client_authorized: bool
        @param client_authorized: True if resource owner has authorized client

        @rtype: tuple: (str, int, str)
        @return: tuple (
                     redirect_uri
                     HTTP status if error
                     error description
                 )
        """
        log.debug("Starting authorization request")

        # Parameters should only be taken from the query string.
        params = request.GET
        authz_request = AuthorizeRequest(params.get('response_type', None),
                                         params.get('client_id', None),
                                         params.get('redirect_uri', None),
                                         params.get('scope', None),
                                         params.get('state', None))

        try:
            self.check_request(request, params, post_only=False)

            # Check for required parameters.
            required_parameters = ['response_type', 'client_id']
            for param in required_parameters:
                if param not in params:
                    log.error("Missing request parameter %s from params: %s",
                              param, params)
                    raise OauthException(
                        'invalid_request',
                        "Missing request parameter: %s" % param)

            if not client_authorized:
                raise OauthException('access_denied',
                                     'User has declined authorization')

            client_error = self.client_register.is_valid_client(
                authz_request.client_id, authz_request.redirect_uri)
            if client_error:
                log.error("Invalid client: %s", client_error)
                return (None, httplib.BAD_REQUEST, client_error)

            # redirect_uri must be included in the request if the client has
            # more than one registered.
            client = self.client_register.register[authz_request.client_id]
            if (len(client.redirect_uris) != 1
                    and not authz_request.redirect_uri):
                log.error("An authorization request has been made without a "
                          "return URI")
                return (None, httplib.BAD_REQUEST,
                        ('An authorization request has been made without a '
                         'return URI.'))

            response_type = params.get('response_type', None)

            # Response may be an authorisation code or in the case of an
            # Implicit Grant a token
            if response_type == self.__class__.AUTHZ_CODE_RESP_TYPE:
                log.debug('Client requesting an authorization code')

                # Preconditions satisfied - generate grant.
                grant, code = self.authorizer.generate_authorization_grant(
                    authz_request, request)
                authz_response = AuthorizeResponse(code, authz_request.state)

                if not self.authorization_grant_register.add_grant(grant):
                    log.error('Registering grant failed')
                    raise OauthException(
                        'server_error', 'Authorization grant could not be '
                        'created')

                log.debug("Redirecting back after successful authorization.")
                return self._redirect_after_authorize(authz_request,
                                                      authz_response)

            elif response_type == self.__class__.TOK_RESP_TYPE:
                log.debug('Implicit Grant - client requesting a token')

                impl_grant_response = make_access_token(
                    authz_request, self.access_token_register,
                    self.access_token_generator)

                log.debug("Redirecting back after successful implicit grant.")
                return self._redirect_after_authorize(authz_request,
                                                      impl_grant_response)
            else:
                raise OauthException(
                    'unsupported_response_type',
                    "Response type %s not supported" % response_type)

        except OauthException, exc:
            log.error("Redirecting back after error: %s - %s", exc.error,
                      exc.error_description)

            return self._redirect_after_authorize(authz_request, None,
                                                  exc.error,
                                                  exc.error_description)